Elffuss BraidHub

kikocis/utopia public

Merge pull request #218 from deeplethe/dev

Sources for object storage, WebDAV and Notion; a plainer feature table
Changesetfa91ee90e6a9cfe04638ede32404fb2053610c93ed378d6039ceff73f7bb4d4a
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 04:13 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-03 04:13 +08:00
Parents439b4250d5de, c187c3135e0a

Browse the files at this changeset

55 files changed

modified Cargo.lock +109 −10
@@ -707,6 +707,16 @@
707707 source = "registry+https://github.com/rust-lang/crates.io-index"
708708 checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
709709
710+[[package]]
711+name = "crc-fast"
712+version = "1.10.0"
713+source = "registry+https://github.com/rust-lang/crates.io-index"
714+checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5"
715+dependencies = [
716+ "digest 0.10.7",
717+ "spin 0.10.1",
718+]
719+
710720 [[package]]
711721 name = "crc32fast"
712722 version = "1.5.1"
@@ -1298,7 +1308,7 @@
12981308 dependencies = [
12991309 "futures-core",
13001310 "futures-sink",
1301- "spin",
1311+ "spin 0.9.9",
13021312 ]
13031313
13041314 [[package]]
@@ -1659,6 +1669,12 @@
16591669 source = "registry+https://github.com/rust-lang/crates.io-index"
16601670 checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
16611671
1672+[[package]]
1673+name = "humantime"
1674+version = "2.4.0"
1675+source = "registry+https://github.com/rust-lang/crates.io-index"
1676+checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"
1677+
16621678 [[package]]
16631679 name = "hybrid-array"
16641680 version = "0.4.14"
@@ -2002,6 +2018,15 @@
20022018 "either",
20032019 ]
20042020
2021+[[package]]
2022+name = "itertools"
2023+version = "0.15.0"
2024+source = "registry+https://github.com/rust-lang/crates.io-index"
2025+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"
2026+dependencies = [
2027+ "either",
2028+]
2029+
20052030 [[package]]
20062031 name = "itoa"
20072032 version = "1.0.18"
@@ -2127,7 +2152,7 @@
21272152 source = "registry+https://github.com/rust-lang/crates.io-index"
21282153 checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
21292154 dependencies = [
2130- "spin",
2155+ "spin 0.9.9",
21312156 ]
21322157
21332158 [[package]]
@@ -2237,7 +2262,7 @@
22372262 "indexmap",
22382263 "itoa",
22392264 "log",
2240- "md-5",
2265+ "md-5 0.10.6",
22412266 "nom 8.0.0",
22422267 "rand 0.10.2",
22432268 "rangemap",
@@ -2305,6 +2330,16 @@
23052330 "digest 0.10.7",
23062331 ]
23072332
2333+[[package]]
2334+name = "md-5"
2335+version = "0.11.0"
2336+source = "registry+https://github.com/rust-lang/crates.io-index"
2337+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
2338+dependencies = [
2339+ "cfg-if",
2340+ "digest 0.11.3",
2341+]
2342+
23082343 [[package]]
23092344 name = "measure_time"
23102345 version = "0.9.0"
@@ -2394,7 +2429,7 @@
23942429 "httparse",
23952430 "memchr",
23962431 "mime",
2397- "spin",
2432+ "spin 0.9.9",
23982433 "version_check",
23992434 ]
24002435
@@ -2410,6 +2445,18 @@
24102445 source = "registry+https://github.com/rust-lang/crates.io-index"
24112446 checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
24122447
2448+[[package]]
2449+name = "nix"
2450+version = "0.31.3"
2451+source = "registry+https://github.com/rust-lang/crates.io-index"
2452+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
2453+dependencies = [
2454+ "bitflags",
2455+ "cfg-if",
2456+ "cfg_aliases",
2457+ "libc",
2458+]
2459+
24132460 [[package]]
24142461 name = "no_std_io2"
24152462 version = "0.9.4"
@@ -2517,6 +2564,49 @@
25172564 "memchr",
25182565 ]
25192566
2567+[[package]]
2568+name = "object_store"
2569+version = "0.14.1"
2570+source = "registry+https://github.com/rust-lang/crates.io-index"
2571+checksum = "d354792e39fa5f0009e47623cf8b15b099bf9a652fa55c6f817fe28ac84fea50"
2572+dependencies = [
2573+ "async-trait",
2574+ "aws-lc-rs",
2575+ "base64",
2576+ "bytes",
2577+ "chrono",
2578+ "crc-fast",
2579+ "form_urlencoded",
2580+ "futures-channel",
2581+ "futures-core",
2582+ "futures-util",
2583+ "http",
2584+ "http-body-util",
2585+ "httparse",
2586+ "humantime",
2587+ "hyper",
2588+ "itertools 0.15.0",
2589+ "md-5 0.11.0",
2590+ "nix",
2591+ "parking_lot",
2592+ "percent-encoding",
2593+ "quick-xml 0.41.0",
2594+ "rand 0.10.2",
2595+ "reqwest",
2596+ "rustls-pki-types",
2597+ "serde",
2598+ "serde_json",
2599+ "serde_urlencoded",
2600+ "thiserror 2.0.20",
2601+ "tokio",
2602+ "tracing",
2603+ "url",
2604+ "walkdir",
2605+ "wasm-bindgen-futures",
2606+ "web-time",
2607+ "windows-sys 0.61.2",
2608+]
2609+
25202610 [[package]]
25212611 name = "once_cell"
25222612 version = "1.21.4"
@@ -2970,6 +3060,7 @@
29703060 dependencies = [
29713061 "encoding_rs",
29723062 "memchr",
3063+ "serde",
29733064 ]
29743065
29753066 [[package]]
@@ -3739,6 +3830,12 @@
37393830 "lock_api",
37403831 ]
37413832
3833+[[package]]
3834+name = "spin"
3835+version = "0.10.1"
3836+source = "registry+https://github.com/rust-lang/crates.io-index"
3837+checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3"
3838+
37423839 [[package]]
37433840 name = "spki"
37443841 version = "0.7.3"
@@ -3874,7 +3971,7 @@
38743971 "hmac",
38753972 "itoa",
38763973 "log",
3877- "md-5",
3974+ "md-5 0.10.6",
38783975 "memchr",
38793976 "once_cell",
38803977 "percent-encoding",
@@ -3915,7 +4012,7 @@
39154012 "home",
39164013 "itoa",
39174014 "log",
3918- "md-5",
4015+ "md-5 0.10.6",
39194016 "memchr",
39204017 "once_cell",
39214018 "rand 0.8.8",
@@ -4128,7 +4225,7 @@
41284225 "fnv",
41294226 "fs4",
41304227 "htmlescape",
4131- "itertools",
4228+ "itertools 0.14.0",
41324229 "levenshtein_automata",
41334230 "log",
41344231 "lru",
@@ -4177,7 +4274,7 @@
41774274 dependencies = [
41784275 "downcast-rs",
41794276 "fastdivide",
4180- "itertools",
4277+ "itertools 0.14.0",
41814278 "serde",
41824279 "tantivy-bitpacker",
41834280 "tantivy-common",
@@ -4240,7 +4337,7 @@
42404337 checksum = "8a2cfc3ac5164cbadc28965ffb145a8f47582a60ae5897859ad8d4316596c606"
42414338 dependencies = [
42424339 "futures-util",
4243- "itertools",
4340+ "itertools 0.14.0",
42444341 "tantivy-bitpacker",
42454342 "tantivy-common",
42464343 "tantivy-fst",
@@ -4299,7 +4396,7 @@
42994396 "either",
43004397 "icu_provider",
43014398 "icu_segmenter",
4302- "itertools",
4399+ "itertools 0.14.0",
43034400 "memchr",
43044401 "strum",
43054402 "thiserror 2.0.20",
@@ -4831,6 +4928,8 @@
48314928 "flate2",
48324929 "futures-util",
48334930 "jsonwebtoken",
4931+ "object_store",
4932+ "quick-xml 0.42.0",
48344933 "reqwest",
48354934 "serde",
48364935 "serde_json",
modified README.md +14 −14
@@ -48,23 +48,23 @@
4848
4949 ## Features
5050
51-The system is a Rust binary and a Postgres service. pgvector and a queue-table design keep the stack and its service dependencies light.
51+One Rust binary and one Postgres. Full-text search is embedded in the binary, vectors go in pgvector, and the job queue is a table: nothing else to run.
5252
5353 | | |
5454 |---|---|
55-| **A complete application** | A system console, a graph browser and an ontology workbench that runs in the browser. Install it and it works; there is no library to assemble first. |
56-| **Knowledge ingest** | PDF, DOCX, PPTX, XLSX/XLS/ODS, CSV/TSV, Markdown, HTML and plain text, with legacy text encodings detected on the way in. Web pages, RSS, GitHub and Jira sync on a cron; anything else pushes in with a per-source token. Failed parses reprocess in place, and a whole source or base can be re-extracted in bulk. |
57-| **Search and chat** | Hybrid retrieval over Tantivy full-text and pgvector, fused with RRF; Chinese full-text uses jieba tokenisation. Answers stream with inline citations that jump straight to the source passage. Any OpenAI-compatible endpoint works (DeepSeek, Qwen, GLM, Ollama, vLLM), so the whole system can run on an isolated network. |
58-| **Agent harness and agentic RAG** | The application is itself a harness: the whole system can be driven through conversation. The built-in agent carries tools for document search, entity lookup, fact and change history, and querying a mounted database, and calls them over several turns before it answers. |
59-| **Ontology and cold start** | A base ships with no vocabulary of its own. Cold start comes from packs: schema.org, W3C Org, PROV-O, FOAF and IOF Core, gzipped into the binary and chosen at creation ([ask for your industry](https://github.com/deeplethe/utopia/issues/new?labels=enhancement&title=Ontology%20pack%20request)). Vocabulary met outside them is recorded with a source quote and a count, and frequent items merge in on confirmation, so the ontology grows with the corpus. |
60-| **Bitemporal graph** | Extraction against the editable ontology produces entities and facts, each carrying a validity interval and its evidence rows. Correcting a fact closes the old version and links the new one to it rather than overwriting. Queries read back at any point in history, and the entity panel shows both timelines at once: when something held in the world, and when the system changed its mind. |
61-| **Entity resolution and review** | Three-stage entity resolution; every merge is logged and can be undone. Low-confidence extractions, merge candidates and cardinality conflicts go to a review queue rather than interrupting anyone. Confirming, rejecting or closing a fact by hand leaves a record. |
62-| **Reasoning and derivation** | Rules are expressed in temporal Datalog and driven by forward chaining. Derived facts carry validity and provenance like extracted ones, and their derivation path expands all the way back to the original sentence. Ontology axioms (type inheritance, relation hierarchy, transitivity, symmetry, inverses, disjointness, cardinality) compile into rules and take part in reasoning. |
63-| **Conflict detection** | Three checks, three different verdicts. Temporal conflicts resolve to closing the old fact, keeping both, or rejecting the new one. Axiom violations in the data (self-loop, asymmetry, transitive cycle, cardinality) resolve to retracting the fact, relaxing the axiom, or accepting both. Defects in the ontology itself come first, because violations computed on a self-contradictory ontology are noise. |
64-| **Ontology-driven querying** | Register a Postgres connection once, mount it on a base, and chat queries documents and the database together. An exploration pass reads the mounted schema against the concepts already in the base and proposes mappings; the agent proposes, a person confirms. The method behind it ([Ontology2SQL](https://github.com/deeplethe/ontology2sql)) is state of the art on BIRD Mini-Dev for both SQLite and PostgreSQL ([submission](https://github.com/bird-bench/bird-bench.github.io/pull/218)). |
65-| **Multi-user and permissions** | Permissions are scoped per knowledge base, each with its own members and roles. Open bases are readable by everyone in the deployment, restricted ones only by invited users. A deployment has one system administrator, the first account registered, and each base carries owner, admin, editor and viewer roles. |
66-| **Decision ledger** | Confirming and rejecting facts, merging and reverting entities, rebuilding the graph: all of them leave a record with the operator, the time, and a snapshot of the object as it then stood. The record remains queryable after the object is invalidated or rebuilt. |
67-| **[Decision intelligence (in development)](#roadmap)** | Recording decisions, replaying both the understanding and the course a decision took, and reasoning over overlaid scenarios. |
55+| **A complete application** | A system console, a graph browser and an ontology workbench in one web UI. A product, not a library: install it and it works. |
56+| **Knowledge ingest** | Upload PDF, DOCX, PPTX, XLSX, XLS, ODS, CSV, TSV, Markdown, HTML or plain text, with legacy encodings detected on the way in. Web pages, RSS, GitHub, Jira and S3-compatible buckets sync on a schedule; everything else comes in through the API. |
57+| **Search and chat** | Full-text on Tantivy, vectors on pgvector, fused with RRF. Answers stream with inline citations that open the passage they came from. Any OpenAI-compatible endpoint works (DeepSeek, Qwen, GLM, Ollama, vLLM), so the whole system can run air-gapped. |
58+| **Agent harness and agentic RAG** | The whole system can be driven through conversation. The built-in agent searches documents, walks the graph (an entity's facts as of any date, or what changed in a period) and queries a mounted database. The same read-only tools are exposed over MCP. |
59+| **Ontology and cold start** | A new knowledge base has no vocabulary of its own; it starts from the packs you pick at creation. Five ship inside the binary: schema.org, W3C Org, PROV-O, FOAF and IOF Core ([ask for your industry](https://github.com/deeplethe/utopia/issues/new?labels=enhancement&title=Ontology%20pack%20request)). Terms outside the packs are counted as they appear; confirm the common ones and they join the ontology. |
60+| **Bitemporal graph** | Extraction turns documents into entities and facts, following an ontology you can edit. Every fact carries when it held and where it came from. Correcting a fact closes the old version and links the new one to it rather than overwriting, so the graph keeps two timelines: when something was true in the world, and when the system came to believe it. |
61+| **Entity resolution and review** | Duplicates are resolved in three stages: exact name or alias, embedding similarity, then a model's call on the doubtful pairs. Every merge can be undone. Uncertain cases go to a review queue: low-confidence extractions, suspected duplicates and cardinality conflicts. |
62+| **Reasoning and derivation** | Ontology axioms compile into rules: transitivity, symmetry, inverses and relation hierarchy derive new facts by forward chaining. Derivation is off by default, since a wrong axiom derives wrong facts. A derived fact is marked as such on the graph, carries validity and confidence like any other, and shows what it was derived from. When it contradicts an asserted fact, the asserted one stands. |
63+| **Conflict detection** | Three kinds of conflict, three sets of choices. A new fact that clashes with an older one: close the old, keep both, or reject the new. Data that breaks an axiom (self-loop, asymmetry, transitive cycle, cardinality): retract the fact, relax the axiom, or accept both. The ontology itself is checked first, because violations of a self-contradictory ontology are noise. |
64+| **Ontology-driven querying** | Mount a Postgres database on a base and chat can query it alongside the documents. The agent proposes how its tables map onto the ontology, and you confirm. The method behind it, [Ontology2SQL](https://github.com/deeplethe/ontology2sql), is state of the art on BIRD Mini-Dev for SQLite and PostgreSQL ([submission](https://github.com/bird-bench/bird-bench.github.io/pull/218)). |
65+| **Multi-user and permissions** | Each knowledge base has its own members and roles: owner, admin, editor and viewer. Open bases are readable by everyone in the deployment, restricted ones only by invitation. The first account registered becomes the system administrator. |
66+| **Decision ledger** | Confirming or rejecting a fact, merging or reverting an entity, rebuilding the graph: each leaves a record of who, when, and what the object looked like at the time. The ledger is append-only, and a record outlives its object, even the base it belonged to. |
67+| **[Decision intelligence (in development)](#roadmap)** | Record a decision, replay both what was understood and the course it took, and reason over overlaid scenarios. |
6868
6969 ## Quick start
7070
modified crates/utopia-core/src/error.rs +30 −0
@@ -50,3 +50,33 @@
5050 }
5151
5252 pub type AppResult<T> = Result<T, AppError>;
53+
54+/// 标在一个**不会因为重试而变好**的失败上(见 issue #195)。
55+///
56+/// 队列的默认假设是「再等一会儿也许就好了」,多数失败确实如此:端点抖一下、
57+/// 数据库忙一瞬、限流一分钟就过去。余额耗尽不是——三次重试隔着 30 秒、2 分钟、
58+/// 4 分半,七分钟里没有人会去充值,重试只是把同一句错误重说三遍,而运维需要
59+/// 看见的那条「失败」被推迟了七分钟才出现。
60+///
61+/// **判据留在处理器那一侧,不在队列里。** 什么算没救跟领域有关——
62+/// `utopia-store` 看不见 `utopia-llm` 的错误类型,也不该看见。处理器把这个标记
63+/// 挂上去(`err.context(Terminal)`),队列只问「挂了没有」。
64+///
65+/// 挂上它不影响别的:告警照报(`observe_job_failure` 一并认这个标记,
66+/// 否则失败得更快反而没人被告知),`last_error` 照写。
67+#[derive(Debug, Clone, Copy)]
68+pub struct Terminal;
69+
70+impl std::fmt::Display for Terminal {
71+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72+ f.write_str("will not recover by retrying")
73+ }
74+}
75+
76+impl std::error::Error for Terminal {}
77+
78+/// 这次失败被标成不必重试了吗。**沿整条 context 链找**——处理器挂上标记之后,
79+/// 上层还会继续 `context(...)`,只看最外层就等于没看
80+pub fn is_terminal(err: &anyhow::Error) -> bool {
81+ err.chain().any(|e| e.is::<Terminal>())
82+}
modified crates/utopia-core/src/lib.rs +1 −1
@@ -4,4 +4,4 @@
44 pub mod error;
55 pub mod models;
66
7-pub use error::{AppError, AppResult};
7+pub use error::{is_terminal, AppError, AppResult, Terminal};
modified crates/utopia-core/src/models.rs +28 −0
@@ -926,8 +926,36 @@
926926 /// 与列表分开取是有意的:列表有上限(一页十条),数数没有。从前左栏读的是
927927 /// 数组长度,而接口固定只回 100 条——一个有 164 条待办的库,界面写着 100,
928928 /// 清完还会再冒出来。
929+/// 等人点头的一条事实(0015)。`quote` 是那句记忆的全文——确认界面要把原句和
930+/// 三元组并排显示,只列三元组等于要人凭空判断它对不对。
931+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
932+pub struct PendingFactView {
933+ pub id: Uuid,
934+ pub subject_id: Uuid,
935+ pub subject_name: String,
936+ pub predicate_id: Option<Uuid>,
937+ /// 本体里的关系名;为空时前端显示 `proposed_predicate`(斜体,标明是原话)
938+ pub predicate_label: Option<String>,
939+ pub proposed_predicate: Option<String>,
940+ pub object_id: Option<Uuid>,
941+ pub object_name: Option<String>,
942+ pub object_value: Option<serde_json::Value>,
943+ pub valid_from: Option<DateTime<Utc>>,
944+ pub valid_from_precision: Option<String>,
945+ pub valid_to: Option<DateTime<Utc>>,
946+ pub valid_to_precision: Option<String>,
947+ pub confidence: f32,
948+ pub chunk_id: Uuid,
949+ pub quote: String,
950+ pub proposed_by: Option<Uuid>,
951+ pub proposed_by_name: Option<String>,
952+ pub created_at: DateTime<Utc>,
953+}
954+
929955 #[derive(Debug, Clone, Copy, Default, Serialize, sqlx::FromRow)]
930956 pub struct ReviewCounts {
957+ /// 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话
958+ pub pending: i64,
931959 pub duplicates: i64,
932960 pub conflicts: i64,
933961 pub unconfirmed: i64,
modified crates/utopia-reason/src/lib.rs +8 −0
@@ -78,6 +78,13 @@
7878 /// 同一主语与谓词同时指向两个宾语,而 p 声明了 functional
7979 /// (inverse_functional 则是同一宾语被两个主语指)
8080 Functional,
81+ /// `A p B`,而 A 不在 p 声明的 domain 里、或 B 不在 range 里(#190 / #196)。
82+ ///
83+ /// **这一类不由本 crate 算出**:它要看实体的类型与 domain / range 的闭包,那是
84+ /// 库里的东西,`utopia-store::reasoning::signature_breaks` 用 SQL 量。列在这里
85+ /// 是为了与其它四类走同一条落库、清陈、裁决的路——left 与 right 同一条事实,
86+ /// 与自反那类同款
87+ Signature,
8188 }
8289
8390 impl Kind {
@@ -87,6 +94,7 @@
8794 Kind::Asymmetry => "asymmetry",
8895 Kind::Cycle => "cycle",
8996 Kind::Functional => "functional",
97+ Kind::Signature => "signature",
9098 }
9199 }
92100 }
modified crates/utopia-server/Cargo.toml +2 −0
@@ -39,3 +39,5 @@
3939 feed-rs.workspace = true
4040 async-trait = "0.1.92"
4141 sqlparser = "0.62.0"
42+object_store = { version = "0.14.1", features = ["aws", "azure", "gcp"] }
43+quick-xml.workspace = true
modified crates/utopia-server/src/alerting.rs +47 −4
@@ -15,9 +15,10 @@
1515
1616 /// 任务失败时看一眼是不是模型端点不可用。
1717 ///
18-/// **只在任务最终放弃时报**(`attempts >= max_attempts`)。中间那几次重试报了
19-/// 就是同一件事发三遍——重试本来就是为了不惊动人,报出去等于把它的意义抵消掉。
20-/// 一个任务至多一条告警,不需要任何去重状态。
18+/// **只在任务最终放弃时报**——次数用完,或者这次失败被标成了不必重试
19+/// ([`hopeless`],#195)。中间那几次重试报了就是同一件事发三遍:重试本来就是
20+/// 为了不惊动人,报出去等于把它的意义抵消掉。一个任务至多一条告警,
21+/// 不需要任何去重状态。
2122 ///
2223 /// 判据是错误的**类型**,不匹配错误文本——调用链上任何一层加一句 context
2324 /// 都会改文本。分类本身抽在 [`alert_for`]。
@@ -26,7 +27,9 @@
2627 job: &utopia_store::jobs::Job,
2728 err: &anyhow::Error,
2829 ) {
29- if job.attempts < job.max_attempts {
30+ // 标成不必重试的那些**这一次就是最后一次**,所以现在就报(#195)。
31+ // 漏掉这一句的后果是失败得更快、却反而没人被告知——比不改还糟
32+ if job.attempts < job.max_attempts && !utopia_core::is_terminal(err) {
3033 return;
3134 }
3235 let Some((kind, severity)) = alert_for(err) else {
@@ -53,6 +56,17 @@
5356 state.emit_alert();
5457 }
5558
59+/// 这次失败还值不值得重试。
60+///
61+/// **只有欠费是没救的。** 限流会自己恢复,端点不可达可能是重启中的服务,
62+/// 别的错误更没有理由一次定生死——只有余额不会在七分钟里自己长回来(#195)。
63+///
64+/// 判据与 [`alert_for`] 同源(`utopia_llm::out_of_credit`,类型不是文本),
65+/// 于是「报成 error 那一类」与「不再重试那一类」永远是同一类,不会分叉。
66+pub fn hopeless(err: &anyhow::Error) -> bool {
67+ utopia_llm::out_of_credit(err).is_some()
68+}
69+
5670 /// 一次任务失败该报哪一类告警,报不报。
5771 ///
5872 /// **抽成纯函数是为了能测**:`observe_job_failure` 要 `AppState` 和一个真数据库,
@@ -212,4 +226,33 @@
212226 let err = anyhow::anyhow!("LLM request failed (401 Unauthorized): bad key");
213227 assert_eq!(alert_for(&err), None);
214228 }
229+
230+ /// **余额不会在七分钟里自己长回来**,所以那三次退避重试只是把同一句错误
231+ /// 重说三遍,还把该看见的失败推迟了七分钟(#195)。
232+ #[test]
233+ fn an_empty_balance_is_not_worth_retrying() {
234+ let err = anyhow::Error::new(OutOfCredit {
235+ status: 402,
236+ detail: "insufficient balance".into(),
237+ })
238+ .context("抽取失败");
239+ assert!(super::hopeless(&err));
240+ }
241+
242+ /// 而限流正是这套退避的服务对象——两类分开(#176)的意义就在这里。
243+ #[test]
244+ fn a_rate_limit_still_gets_its_retries() {
245+ let err = anyhow::Error::new(RateLimited {
246+ status: 429,
247+ retry_after: Some(std::time::Duration::from_secs(30)),
248+ detail: "TPM limit reached".into(),
249+ });
250+ assert!(!super::hopeless(&err));
251+ }
252+
253+ /// 反面:普通失败照常重试。一次网络抖动不该一次定生死。
254+ #[test]
255+ fn an_ordinary_failure_still_gets_its_retries() {
256+ assert!(!super::hopeless(&anyhow::anyhow!("结果解析失败")));
257+ }
215258 }
modified crates/utopia-server/src/api/chat.rs +17 −16
@@ -29,17 +29,14 @@
2929 const MAX_HISTORY: usize = 20;
3030 const MAX_ROUNDS: usize = 6;
3131
32-/// **`remember` 暂时停用**(见 `docs/decisions/0015`)。
32+/// `remember` 曾整个停用过一段(见 `docs/decisions/0015`):它那时会把一句话直接
33+/// 变成图上一条活边,实测里「记住 Acme 把总部搬到了深圳」落成的是一条**空谓词、
34+/// 0.9 置信**的边,而助手宣称的和图里得到的不是一回事。
3335 ///
34-/// 它今天会把一句话直接变成图上一条活边,而中间那一步没人看得见:实测里
35-/// 「记住 Acme 把总部搬到了深圳」落成的是一条 **空谓词、0.9 置信** 的边——
36-/// 本体里没有「搬迁到」这类关系,抽取落不上就留空(按 0010 这是对的),
37-/// 于是助手宣称的和图里得到的不是一回事。
38-///
39-/// 0018 建好了 `pending_facts`:抽出来的先等人点头。**抽取侧接上那张表
40-/// 之后,把这里改回 true。** 在那之前宁可没有这个工具,也不要一个会
41-/// 悄悄改图的工具。
42-pub(super) const REMEMBER_ENABLED: bool = false;
36+/// 现在抽取侧接上了 `pending_facts`:记忆抽出的事实先等人点头,再进账本。
37+/// 这个开关留着,是为了下次再发现「工具会悄悄改图」时有地方立刻拉闸——
38+/// 宁可没有这个工具,也不要一个会悄悄改图的工具。
39+pub(super) const REMEMBER_ENABLED: bool = true;
4340
4441 #[derive(Deserialize)]
4542 pub struct ChatReq {
@@ -95,10 +92,11 @@
9592 "name": "remember",
9693 "description": "Record one memory episode into the knowledge base's temporal \
9794 memory. Use ONLY when the user explicitly asks to remember/record \
98- something, or clearly states a decision or fact to keep. The episode is \
99- extracted into the knowledge graph; if it contradicts an existing \
100- single-valued fact, the old fact's validity is closed automatically \
101- (never deleted). Do not use for casual conversation.",
95+ something, or clearly states a decision or fact to keep. The sentence \
96+ is stored immediately; facts extracted from it are PROPOSED and shown \
97+ to the user for confirmation before they enter the knowledge graph. \
98+ Never claim a fact was added to the graph. Do not use for casual \
99+ conversation.",
102100 "parameters": {
103101 "type": "object",
104102 "properties": {
@@ -188,8 +186,10 @@
188186
189187 const MEMORY_PROMPT: &str = "\
190188 Memory: you can persist knowledge with the remember tool. Use it when the user says \
191- \"remember/record this\" or states a decision meant to last. Confirm in your reply what \
192- was recorded. Never invent memories, and never call it for small talk.";
189+ \"remember/record this\" or states a decision meant to last. In your reply, say that the \
190+ sentence was recorded and that the facts extracted from it will be shown for the user's \
191+ confirmation before entering the graph; never say a fact is already in the graph. \
192+ Never invent memories, and never call it for small talk.";
193193
194194 /// 工具的 JSON schema——**给模型看的那一份**。
195195 ///
@@ -687,6 +687,7 @@
687687 workspace_id,
688688 mounted_sources: &mounted_sources,
689689 can_write,
690+ actor: Some(user.id),
690691 };
691692 let (result, step) = tools::dispatch(&ctx, &mut sink, &call.name, &args).await;
692693 // **这一步发生在正文的哪个位置。**
modified crates/utopia-server/src/api/mcp.rs +1 −0
@@ -176,6 +176,7 @@
176176 workspace_id: kb.workspace_id,
177177 mounted_sources: &[],
178178 can_write: false,
179+ actor: Some(user.id),
179180 };
180181 let mut sink = ToolSink::default();
181182 let (text, _step) = tools::dispatch(&ctx, &mut sink, name, &args).await;
modified crates/utopia-server/src/api/mod.rs +9 −0
@@ -333,6 +333,15 @@
333333 )
334334 .route("/kbs/{id}/review", get(review_routes::list))
335335 .route("/kbs/{id}/review/history", get(review_routes::history))
336+ // 记忆抽出、等人点头的事实(0015):按句取、逐条裁
337+ .route(
338+ "/kbs/{id}/review/pending",
339+ get(review_routes::pending_for_chunk),
340+ )
341+ .route(
342+ "/kbs/{id}/review/pending/{pending_id}",
343+ post(review_routes::decide_pending),
344+ )
336345 .route("/kbs/{id}/review/{review_id}", post(review_routes::decide))
337346 // 语义层映射的表态(0011)。跟消解审核并排——都是「引擎提议、人裁决」
338347 .route(
modified crates/utopia-server/src/api/ontology_routes.rs +18 −7
@@ -1006,7 +1006,12 @@
10061006 // 这里的 forms 是人在面板上勾的,完全可能同时勾了 `produced` 和 `produced_by`,
10071007 // 而一个 swap 标志伺候不了混合。自动那条路不存在这个问题:同组说法共享屈折基,
10081008 // 结尾有没有 `by` 必然一致。真要修得让 adopt 逐条判方向,那是另一件事。
1009- let (batch_id, remapped) = utopia_store::graph::adopt_proposed_predicates(
1009+ let utopia_store::graph::Adopted {
1010+ batch_id,
1011+ moved: remapped,
1012+ left_off,
1013+ corrected,
1014+ } = utopia_store::graph::adopt_proposed_predicates(
10101015 &state.pool,
10111016 kb_id,
10121017 predicate_id,
@@ -1027,14 +1032,16 @@
10271032 Some(predicate_id),
10281033 json!({
10291034 "key": key, "label": req.label, "forms": req.forms,
1030- "facts_remapped": remapped, "batch": batch_id,
1035+ "facts_remapped": remapped, "facts_left_off": left_off,
1036+ "facts_direction_corrected": corrected, "batch": batch_id,
10311037 }),
10321038 )
10331039 .await;
10341040 state.emit_review(kb_id);
1035- Ok(Json(
1036- json!({ "id": predicate_id, "remapped": remapped, "batch": batch_id }),
1037- ))
1041+ Ok(Json(json!({
1042+ "id": predicate_id, "remapped": remapped, "left_off": left_off,
1043+ "corrected": corrected, "batch": batch_id,
1044+ })))
10381045 }
10391046
10401047 /// 撤销一次采纳:新写的行作废、旧行复活。关系类型留着(有事实指向过它,
@@ -1372,8 +1379,12 @@
13721379 None => unconvertible += 1,
13731380 }
13741381 }
1375- let (batch_id, remapped) =
1376- utopia_store::graph::adopt_value_facts(&state.pool, kb_id, attribute_id, &rewrites).await?;
1382+ // 属性那一路没有签名可判(宾语是字面值),`left_off` 恒为 0
1383+ let utopia_store::graph::Adopted {
1384+ batch_id,
1385+ moved: remapped,
1386+ ..
1387+ } = utopia_store::graph::adopt_value_facts(&state.pool, kb_id, attribute_id, &rewrites).await?;
13771388 for form in spec.forms {
13781389 let _ =
13791390 utopia_store::ontology::clear_miss(&state.pool, kb_id, "attribute_type", form).await;
modified crates/utopia-server/src/api/review_routes.rs +86 −0
@@ -75,6 +75,8 @@
7575 let offset = q.offset.unwrap_or(0).max(0);
7676
7777 let items = match queue {
78+ // 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话
79+ "pending" => json!(utopia_store::pending::list(&state.pool, kb_id, limit, offset).await?),
7880 "duplicates" => {
7981 json!(utopia_store::resolution::list_reviews(&state.pool, kb_id, limit, offset).await?)
8082 }
@@ -636,6 +638,90 @@
636638 /// 就按它改图。开关关着时不静默跳过:回一个明确的错,界面才说得出为什么没动。
637639 ///
638640 /// 同步跑,与一致性检查同一个理由:纯计算,没有模型调用也没有网络。
641+#[derive(Deserialize)]
642+pub struct PendingQuery {
643+ pub chunk_id: Uuid,
644+}
645+
646+/// 一句记忆抽出的全部待确认项——对话里那张确认卡按这个取(0015)。
647+/// Viewer 也能看:看得见提议、看不见按钮,与 Review 页同一口径
648+pub async fn pending_for_chunk(
649+ State(state): State<AppState>,
650+ AuthUser(user): AuthUser,
651+ Path(kb_id): Path<Uuid>,
652+ Query(q): Query<PendingQuery>,
653+) -> ApiResult<Json<serde_json::Value>> {
654+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
655+ let items = utopia_store::pending::for_chunk(&state.pool, kb_id, q.chunk_id).await?;
656+ Ok(Json(json!({ "items": items })))
657+}
658+
659+#[derive(Deserialize)]
660+pub struct DecidePendingBody {
661+ /// `confirm` 进账本;`reject` 记进 `rejected_facts`,下一轮重抽不再提
662+ pub action: String,
663+}
664+
665+/// 人对一条待确认事实点头或摇头。
666+///
667+/// 两个动作都进决策台账,快照自包含——行删了之后台账上还读得出当时确认的是什么。
668+/// 确认走与抽取相同的那条路(事实 + 证据 + 时态对账),所以一句「Mira 交给 Devin 了」
669+/// 点头之后,Mira 那条会像从文档里抽出来时一样被闭合
670+pub async fn decide_pending(
671+ State(state): State<AppState>,
672+ AuthUser(user): AuthUser,
673+ Path((kb_id, pending_id)): Path<(Uuid, Uuid)>,
674+ Json(body): Json<DecidePendingBody>,
675+) -> ApiResult<Json<serde_json::Value>> {
676+ require_kb(&state, &user, kb_id, Role::Editor).await?;
677+ match body.action.as_str() {
678+ "confirm" => {
679+ let done = utopia_store::pending::confirm(&state.pool, kb_id, pending_id).await?;
680+ let _ = utopia_store::audit::record(
681+ &state.pool,
682+ Some(kb_id),
683+ user.id,
684+ "fact.nod_confirmed",
685+ "fact",
686+ Some(done.fact_id),
687+ done.snapshot,
688+ )
689+ .await;
690+ state.emit_pending(kb_id);
691+ state.emit_review(kb_id);
692+ state.emit_graph(kb_id);
693+ Ok(Json(json!({
694+ "ok": true,
695+ "fact_id": done.fact_id,
696+ "created": done.created,
697+ "conflicts": done.conflicts,
698+ })))
699+ }
700+ "reject" => {
701+ let snap = utopia_store::pending::reject(&state.pool, kb_id, pending_id, Some(user.id))
702+ .await?;
703+ let _ = utopia_store::audit::record(
704+ &state.pool,
705+ Some(kb_id),
706+ user.id,
707+ "fact.nod_rejected",
708+ "pending_fact",
709+ Some(pending_id),
710+ snap,
711+ )
712+ .await;
713+ state.emit_pending(kb_id);
714+ state.emit_review(kb_id);
715+ Ok(Json(json!({ "ok": true })))
716+ }
717+ other => Err(utopia_core::AppError::invalid(
718+ "unknown_action",
719+ format!("action must be confirm or reject, got {other}"),
720+ )
721+ .into()),
722+ }
723+}
724+
639725 pub async fn run_inference(
640726 State(state): State<AppState>,
641727 AuthUser(user): AuthUser,
modified crates/utopia-server/src/api/tools.rs +16 −5
@@ -32,6 +32,9 @@
3232 pub mounted_sources: &'a [DataSourceView],
3333 /// editor 及以上才有 `remember`
3434 pub can_write: bool,
35+ /// 在说话的人。`remember` 把它记成「谁说的」,一路跟到待确认队列(0015)。
36+ /// 对话里恒有值;MCP 也有——令牌以人的身份行事(0014)
37+ pub actor: Option<Uuid>,
3538 }
3639
3740 /// 工具执行过程中往外攒的东西。
@@ -343,23 +346,31 @@
343346 }
344347 match utopia_store::memory::append_episode(&ctx.state.pool, ctx.kb_id, text, occurred_at).await
345348 {
346- Ok((doc_id, _chunk)) => {
347- // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话
349+ Ok((doc_id, chunk_id)) => {
350+ // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话。
351+ // 抽出来的事实**先等人点头**(0015)——所以这里只能如实说「记下了这句话」,
352+ // 说不出抽出了几条:抽取还没跑。卡片在任务完成时长到对话里
348353 let _ = utopia_store::jobs::enqueue(
349354 &ctx.state.pool,
350355 "memory_ingest",
351- json!({ "document_id": doc_id }),
356+ json!({ "document_id": doc_id, "proposed_by": ctx.actor }),
352357 )
353358 .await;
354359 ctx.state.emit_document(ctx.kb_id, doc_id);
355360 (
356361 format!(
357- "Recorded (effective {}): {text}",
362+ "Recorded the sentence (effective {}): {text}\n\
363+ Facts extracted from it will be shown to the user for confirmation \
364+ before entering the graph. Tell the user exactly that: the sentence is \
365+ recorded, and the extracted facts await their confirmation. Do not claim \
366+ any fact has been added to the knowledge graph.",
358367 occurred_at.format("%Y-%m-%d")
359368 ),
360369 json!({
361370 "kind": "tool", "label": "remember",
362- "detail": text.chars().take(60).collect::<String>()
371+ "detail": text.chars().take(60).collect::<String>(),
372+ // 对话里那张确认卡按它取待确认项;回放时也据此重画
373+ "chunk_id": chunk_id,
363374 }),
364375 )
365376 }
modified crates/utopia-server/src/bootstrap_ontology.rs +23 −4
@@ -160,6 +160,7 @@
160160 let mut added_relations = Vec::new();
161161 let mut added_classes = Vec::new();
162162 let mut moved_total = 0u32;
163+ let mut left_off_total = 0u32;
163164 let mut batches = Vec::new();
164165
165166 for p in &classes {
@@ -268,7 +269,12 @@
268269 }
269270 }
270271 };
271- let (batch, moved) = utopia_store::graph::adopt_proposed_predicates(
272+ let utopia_store::graph::Adopted {
273+ batch_id: batch,
274+ moved,
275+ left_off,
276+ corrected,
277+ } = utopia_store::graph::adopt_proposed_predicates(
272278 &state.pool,
273279 kb_id,
274280 predicate_id,
@@ -277,11 +283,12 @@
277283 )
278284 .await?;
279285 tracing::info!(
280- %kb_id, key = %g.key, forms = ?g.forms, docs = g.docs, facts = g.facts, moved,
281- reused = g.existing.is_some(), swap,
286+ %kb_id, key = %g.key, forms = ?g.forms, docs = g.docs, facts = g.facts, moved, left_off,
287+ corrected, reused = g.existing.is_some(), swap,
282288 "按票数采纳关系"
283289 );
284290 moved_total += moved;
291+ left_off_total += left_off;
285292 if moved > 0 {
286293 batches.push(batch);
287294 }
@@ -392,7 +399,12 @@
392399 };
393400 // LLM 的 map_to 提案同样可能混着主动与被动,一个 swap 标志伺候不了
394401 //(同人工路径,见 ontology_routes 里那段注释)
395- let (batch, moved) = utopia_store::graph::adopt_proposed_predicates(
402+ let utopia_store::graph::Adopted {
403+ batch_id: batch,
404+ moved,
405+ left_off,
406+ corrected,
407+ } = utopia_store::graph::adopt_proposed_predicates(
396408 &state.pool,
397409 kb_id,
398410 predicate_id,
@@ -400,6 +412,11 @@
400412 false,
401413 )
402414 .await?;
415+ tracing::info!(
416+ %kb_id, key, forms = ?forms, moved, left_off, corrected,
417+ "按映射提案采纳关系"
418+ );
419+ left_off_total += left_off;
403420 moved_total += moved;
404421 if moved > 0 {
405422 batches.push(batch);
@@ -437,6 +454,8 @@
437454 "relations": added_relations,
438455 "classes": added_classes,
439456 "facts_remapped": moved_total,
457+ // 签名两边都对不上、没挂上谓词的(#190)。不报这个数,「改写了 N 条」就是报喜不报忧
458+ "facts_left_off": left_off_total,
440459 "batches": batches,
441460 }),
442461 )
modified crates/utopia-server/src/extraction.rs +111 −14
@@ -212,8 +212,14 @@
212212 Ok(())
213213 }
214214
215-pub async fn extract_document(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
216- match run(state, document_id).await {
215+/// `proposed_by`:这篇文档若是记忆日志,抽出的事实等人点头,这一列记「谁说的」。
216+/// 批量摄入的文档传 None——那条路不经待确认队列,这个值用不上
217+pub async fn extract_document(
218+ state: &AppState,
219+ document_id: Uuid,
220+ proposed_by: Option<Uuid>,
221+) -> anyhow::Result<()> {
222+ match run(state, document_id, proposed_by).await {
217223 Ok(()) => Ok(()),
218224 Err(e) => {
219225 // 原因随状态落库:只进日志的错误等于没有错误
@@ -280,7 +286,7 @@
280286 Ok(r.entity_id)
281287 }
282288
283-async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
289+async fn run(state: &AppState, document_id: Uuid, proposed_by: Option<Uuid>) -> anyhow::Result<()> {
284290 let doc = utopia_store::documents::get(&state.pool, document_id).await?;
285291 let kb = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
286292 let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
@@ -389,6 +395,13 @@
389395 // 本轮要从头讲一遍这篇文档的故事,旧信号先清掉(重抽自动作数)
390396 let _ = utopia_store::extraction_drops::clear_for_document(&state.pool, document_id).await;
391397
398+ // **记忆抽出的事实先等人点头**(0015)。一句 remember 一次一句、人就在对话里,
399+ // 确认成本最低的时刻就是说完那句话的时候;而批量摄入一次上万条,逐条确认
400+ // 不可能,那条路仍旧乐观写入 + 事后审阅。判据只有一个:这篇是不是记忆日志。
401+ // 实体照常消解并创建——`pending_facts.subject_id` 是外键,这是 0018 定下的取舍
402+ let await_nod = utopia_store::memory::is_memory_document(&state.pool, document_id).await?;
403+ let mut pending_count = 0usize;
404+
392405 let doc_time = doc.doc_time.map(|t| t.format("%Y-%m-%d").to_string());
393406 let chunks = utopia_store::documents::chunks_for_extraction(&state.pool, document_id).await?;
394407
@@ -716,6 +729,29 @@
716729 // 单位随事实落笔:类型上的单位以后改了,旧值仍按记录时的单位读
717730 object_value["unit"] = serde_json::json!(u);
718731 }
732+ if await_nod {
733+ if let utopia_store::pending::Outcome::Proposed(_) =
734+ utopia_store::pending::propose(
735+ &state.pool,
736+ utopia_store::pending::Proposal {
737+ kb_id: doc.kb_id,
738+ subject_id,
739+ predicate_id: Some(attr.id),
740+ object_id: None,
741+ object_value: Some(&object_value),
742+ proposed_predicate: Some(f.predicate.as_str()),
743+ validity,
744+ confidence,
745+ chunk_id: chunk.id,
746+ proposed_by,
747+ },
748+ )
749+ .await?
750+ {
751+ pending_count += 1;
752+ }
753+ continue;
754+ }
719755 let (fact_id, created) = utopia_store::graph::insert_value_fact(
720756 &state.pool,
721757 doc.kb_id,
@@ -812,12 +848,36 @@
812848 Some(&format!("{subject_name} → {value}")),
813849 )
814850 .await;
851+ let literal = serde_json::json!({ "value": value });
852+ if await_nod {
853+ if let utopia_store::pending::Outcome::Proposed(_) =
854+ utopia_store::pending::propose(
855+ &state.pool,
856+ utopia_store::pending::Proposal {
857+ kb_id: doc.kb_id,
858+ subject_id,
859+ predicate_id: None,
860+ object_id: None,
861+ object_value: Some(&literal),
862+ proposed_predicate: Some(f.predicate.as_str()),
863+ validity,
864+ confidence,
865+ chunk_id: chunk.id,
866+ proposed_by,
867+ },
868+ )
869+ .await?
870+ {
871+ pending_count += 1;
872+ }
873+ continue;
874+ }
815875 let (fact_id, created) = utopia_store::graph::insert_value_fact(
816876 &state.pool,
817877 doc.kb_id,
818878 subject_id,
819879 None,
820- &serde_json::json!({ "value": value }),
880+ &literal,
821881 validity,
822882 confidence,
823883 )
@@ -965,13 +1025,20 @@
9651025 // 那份只覆盖模型在这一块里声明过的实体,而宾语常是别处已存在的实体,
9661026 // 这一块没重新声明它,于是查不到、判不了、掰不动。实测差别不小——
9671027 // 用声明那份时反向只降到 7.0%,剩下的正是宾语类型查不到的那些
968- let s_fits =
969- utopia_store::ontology::entity_fits_domain(&state.pool, pid, subject_id).await;
970- if let Ok(Some(false)) = s_fits {
971- let o_fits =
972- utopia_store::ontology::entity_fits_domain(&state.pool, pid, object_id)
973- .await;
974- if let Ok(Some(true)) = o_fits {
1028+ //
1029+ // 判断本身在 store(`ontology::judge_direction`),**与采纳共用**(#190):
1030+ // 写谓词的路不止这一条,守卫只装在一条上就等于没装。查不出来(库错)
1031+ // 按没有判据处理,照原样落——宁可少掰一条,不能因为一次查询失败丢事实
1032+ let fit = utopia_store::ontology::judge_direction(
1033+ &state.pool,
1034+ pid,
1035+ subject_id,
1036+ object_id,
1037+ )
1038+ .await
1039+ .unwrap_or(utopia_store::ontology::Fit::Unchecked);
1040+ match fit {
1041+ utopia_store::ontology::Fit::Swap => {
9751042 drop_signal(
9761043 state,
9771044 doc.kb_id,
@@ -988,7 +1055,8 @@
9881055 )
9891056 .await;
9901057 (Some(pid), object_id, subject_id)
991- } else {
1058+ }
1059+ utopia_store::ontology::Fit::Neither => {
9921060 // **对调也不合法 → 退回没有谓词。**
9931061 //
9941062 // 这不是方向问题,是这个关系压根不适用:schema.org 的
@@ -1017,13 +1085,36 @@
10171085 .await;
10181086 (None, subject_id, object_id)
10191087 }
1020- } else {
1021- (Some(pid), subject_id, object_id)
1088+ utopia_store::ontology::Fit::Keep | utopia_store::ontology::Fit::Unchecked => {
1089+ (Some(pid), subject_id, object_id)
1090+ }
10221091 }
10231092 } else {
10241093 (predicate_id, subject_id, object_id)
10251094 };
10261095
1096+ if await_nod {
1097+ if let utopia_store::pending::Outcome::Proposed(_) = utopia_store::pending::propose(
1098+ &state.pool,
1099+ utopia_store::pending::Proposal {
1100+ kb_id: doc.kb_id,
1101+ subject_id,
1102+ predicate_id,
1103+ object_id: Some(object_id),
1104+ object_value: None,
1105+ proposed_predicate: Some(f.predicate.as_str()),
1106+ validity,
1107+ confidence,
1108+ chunk_id: chunk.id,
1109+ proposed_by,
1110+ },
1111+ )
1112+ .await?
1113+ {
1114+ pending_count += 1;
1115+ }
1116+ continue;
1117+ }
10271118 {
10281119 let (fact_id, created) = utopia_store::graph::insert_fact(
10291120 &state.pool,
@@ -1092,6 +1183,12 @@
10921183 // (LLM 调用/解析失败的块在上方 continue 掉,不打标,下次重试)
10931184 utopia_store::documents::mark_chunk_extracted(&state.pool, chunk.id).await?;
10941185 }
1186+ // 队列里多了东西才叫醒人:Review 的计数与对话里那张确认卡都靠这一声
1187+ if pending_count > 0 {
1188+ tracing::info!(%document_id, pending_count, "记忆抽出的事实进了待确认队列");
1189+ state.emit_pending(doc.kb_id);
1190+ state.emit_review(doc.kb_id);
1191+ }
10951192
10961193 // 消歧后缀在实体创建时算会早于其事实写入——收尾时对本文档涉及的名字统一刷新
10971194 let names: std::collections::HashSet<&str> =
modified crates/utopia-server/src/ingest_sources.rs +145 −1
@@ -1,5 +1,6 @@
11 //! 来源同步任务:url(网页抓取)/ rss(订阅,pubDate → doc_time)/
2-//! github_issues / jira_issues(工单,更新时刻 → doc_time,正文里带状态变更史)。
2+//! github_issues / jira_issues(工单,更新时刻 → doc_time,正文里带状态变更史)/
3+//! s3(对象存储,LastModified → doc_time)。
34 //! 全部走 sha256 去重(重复内容静默跳过),新文档进标准摄入管道(process_document)。
45 //! folder 是纯容器(上传入内),api 是推送型——两者无拉取语义。
56
@@ -53,6 +54,9 @@
5354 "custom" => sync_custom(state, &source).await,
5455 "github_issues" => sync_github_issues(state, &source).await,
5556 "jira_issues" => sync_jira_issues(state, &source).await,
57+ "s3" | "azure_blob" | "gcs" => sync_object_storage(state, &source).await,
58+ "webdav" => sync_webdav(state, &source).await,
59+ "notion" => sync_notion(state, &source).await,
5660 // folder / api 无拉取语义
5761 _ => Ok(SyncStats::default()),
5862 };
@@ -746,6 +750,146 @@
746750 Ok(stats)
747751 }
748752
753+/// 对象存储同步:列前缀下的对象,逐个摄入。
754+///
755+/// `external_key` 用 `s3://bucket/key`,跟 `file:///` 与页面 URL 同一个约定:
756+/// 出处自描述。换了前缀但内容没变时,`ingest_item` 会认成「搬家」而不是新增,
757+/// 不会重跑一遍抽取。
758+///
759+/// **`doc_time` 取 `LastModified`,而它是写入时刻不是文档自身的时间。**
760+/// 一份 2019 年的合同今天传上去,时间线上会落在今天。对象存储没有更好的
761+/// 来源——除非文件名或正文里带日期,而那是抽取器的活。这一条与 `url` 源
762+/// 同病:`0013` 的第一条判据在这里只满足一半。
763+async fn sync_object_storage(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
764+ let bucket = source.config["bucket"]
765+ .as_str()
766+ .map(str::trim)
767+ .filter(|s| !s.is_empty())
768+ .ok_or_else(|| anyhow::anyhow!("{} source is missing config.bucket", source.kind))?;
769+ let prefix = source.config["prefix"]
770+ .as_str()
771+ .map(str::trim)
772+ .filter(|s| !s.is_empty());
773+
774+ let store = crate::object_storage::client(&source.kind, &source.config)?;
775+ let (objects, truncated) =
776+ crate::object_storage::fetch(&source.kind, store.as_ref(), bucket, prefix).await?;
777+
778+ // 到顶不是错误,但必须说出来——否则「同步成功」下面藏着没进来的东西,
779+ // 而那正是 0005 说的失败无声
780+ if truncated {
781+ tracing::warn!(
782+ %bucket, prefix = prefix.unwrap_or(""),
783+ "对象数到达单次上限,其余留给下一次同步"
784+ );
785+ }
786+
787+ let mut stats = SyncStats::default();
788+ for obj in objects {
789+ // **不猜 mime。** `utopia_ingest::parse` 先看魔数、再看扩展名,
790+ // 注释写着「扩展名可能撒谎」——在这里按文件名猜一个,只是多一个
791+ // 会撒谎的来源,而且要为此多一个依赖。`octet-stream` 是诚实的:
792+ // 我们拿到的就是一串字节,没看过里面是什么。
793+ let action = ingest_item(
794+ state,
795+ source.kb_id,
796+ source.id,
797+ &obj.external_key,
798+ &obj.filename,
799+ "application/octet-stream",
800+ &obj.bytes,
801+ obj.last_modified,
802+ )
803+ .await?;
804+ stats.absorb(action);
805+ }
806+ Ok(stats)
807+}
808+
809+/// WebDAV 同步:逐层走目录,把文件摄进来。
810+///
811+/// `external_key` 用 `webdav://host/path`——同一台网盘换了挂载点仍是同一份
812+/// 文件,而不同网盘上的同名路径是两份。
813+async fn sync_webdav(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
814+ let base = source.config["base_url"]
815+ .as_str()
816+ .map(str::trim)
817+ .filter(|s| !s.is_empty())
818+ .ok_or_else(|| anyhow::anyhow!("webdav source is missing config.base_url"))?;
819+ let root = source.config["path"].as_str().map(str::trim).unwrap_or("/");
820+ let user = source.config["username"].as_str().map(str::trim);
821+ let pass = source.config["password"].as_str().map(str::trim);
822+ let auth = match (user, pass) {
823+ (Some(u), Some(p)) if !u.is_empty() => Some((u, p)),
824+ _ => None,
825+ };
826+
827+ let http = reqwest::Client::builder()
828+ .timeout(std::time::Duration::from_secs(60))
829+ .build()?;
830+ let (files, truncated) = crate::webdav::fetch(&http, base, root, auth).await?;
831+ if truncated {
832+ tracing::warn!(base, root, "文件数到达单次上限,其余留给下一次同步");
833+ }
834+
835+ let mut stats = SyncStats::default();
836+ for f in files {
837+ // 不猜 mime,理由同对象存储:解析先看魔数
838+ let action = ingest_item(
839+ state,
840+ source.kb_id,
841+ source.id,
842+ &f.external_key,
843+ &f.filename,
844+ "application/octet-stream",
845+ &f.bytes,
846+ f.last_modified,
847+ )
848+ .await?;
849+ stats.absorb(action);
850+ }
851+ Ok(stats)
852+}
853+
854+/// Notion 同步:把 integration 能看见的页面摄进来。
855+///
856+/// `doc_time` 取 `last_edited_time`——**这是页面自己的编辑时刻**,比对象存储
857+/// 那边的写入时刻实在:一份 2019 年的合同今天传进 S3 会落在今天,而 Notion
858+/// 页面的编辑时刻就是它内容变化的时刻。
859+async fn sync_notion(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
860+ let token = source.config["token"]
861+ .as_str()
862+ .map(str::trim)
863+ .filter(|s| !s.is_empty())
864+ .ok_or_else(|| anyhow::anyhow!("notion source is missing config.token"))?;
865+ let query = source.config["query"]
866+ .as_str()
867+ .map(str::trim)
868+ .filter(|s| !s.is_empty());
869+
870+ let (pages, truncated) = crate::notion::fetch(token, query).await?;
871+ if truncated {
872+ tracing::warn!("页面数到达单次上限,其余留给下一次同步");
873+ }
874+
875+ let mut stats = SyncStats::default();
876+ for p in pages {
877+ let action = ingest_item(
878+ state,
879+ source.kb_id,
880+ source.id,
881+ &p.external_key,
882+ &p.filename,
883+ "text/markdown",
884+ p.text.as_bytes(),
885+ p.last_edited,
886+ )
887+ .await?;
888+ stats.absorb(action);
889+ }
890+ Ok(stats)
891+}
892+
749893 /// 标题无扩展名时按 mime 补一个,接入解析矩阵的分派。
750894 fn ensure_extension(title: &str, mime: &str) -> String {
751895 let has_ext = title
modified crates/utopia-server/src/main.rs +22 −3
@@ -14,6 +14,8 @@
1414 mod live;
1515 mod llm_util;
1616 mod mappings;
17+mod notion;
18+mod object_storage;
1719 mod ontology_index;
1820 mod ontology_packs;
1921 mod owl_import;
@@ -24,6 +26,7 @@
2426 mod retrieval;
2527 mod state;
2628 mod type_resolution;
29+mod webdav;
2730
2831 use state::AppState;
2932 use std::sync::Arc;
@@ -32,6 +35,14 @@
3235 use utopia_search::SearchIndex;
3336 use uuid::Uuid;
3437
38+/// 记忆那条路带着「谁说的」(0015);别的任务没有这个字段,读到 None 本就该如此
39+fn payload_proposed_by(payload: &serde_json::Value) -> Option<Uuid> {
40+ payload
41+ .get("proposed_by")
42+ .and_then(|v| v.as_str())
43+ .and_then(|s| s.parse().ok())
44+}
45+
3546 fn payload_document_id(payload: &serde_json::Value) -> anyhow::Result<Uuid> {
3647 payload
3748 .get("document_id")
@@ -120,7 +131,15 @@
120131 async move {
121132 // 任务失败时看一眼是不是模型端点连不上——那是系统级故障,
122133 // 而现在它只会留在 jobs.last_error 里,没有任何界面看得到
123- let result = dispatch(&st, &job).await;
134+ //
135+ // 没救的失败在这里挂上标记,队列据此不再退避重试(#195):
136+ // 判据在这一侧,因为 `utopia-store` 看不见 LLM 的错误类型
137+ let result = dispatch(&st, &job)
138+ .await
139+ .map_err(|e| match alerting::hopeless(&e) {
140+ true => e.context(utopia_core::Terminal),
141+ false => e,
142+ });
124143 if let Err(e) = &result {
125144 alerting::observe_job_failure(&st, &job, e).await;
126145 }
@@ -294,7 +313,7 @@
294313 }
295314 "memory_ingest" => {
296315 let id = payload_document_id(&job.payload)?;
297- pipeline::memory_ingest(st, id).await
316+ pipeline::memory_ingest(st, id, payload_proposed_by(&job.payload)).await
298317 }
299318 "explore_mappings" => {
300319 let kb_id: Uuid = job
@@ -341,7 +360,7 @@
341360 }
342361 "extract_document" => {
343362 let id = payload_document_id(&job.payload)?;
344- extraction::extract_document(st, id).await
363+ extraction::extract_document(st, id, payload_proposed_by(&job.payload)).await
345364 }
346365 "bootstrap_ontology" => {
347366 let kb_id: Uuid = job
added crates/utopia-server/src/notion.rs +350 −0
@@ -0,0 +1,350 @@
1+//! Notion 来源:把 integration 能看见的页面同步进来。
2+//!
3+//! 按 [0013](../../docs/decisions/0013-a-source-should-hand-over-its-history.md)
4+//! 的四条判据,它比对象存储强一档:
5+//!
6+//! | 判据 | Notion |
7+//! |---|---|
8+//! | 真实时间戳 | `last_edited_time`,**是文档自己的编辑时刻**,不是我们抓它的时刻 |
9+//! | 会不会自我推翻 | 页面被反复改写正是它的常态 |
10+//! | 稳定身份 | 页面 UUID,改标题、挪位置都不变 |
11+//! | 企业知识住不住在那儿 | 制度、会议纪要、决策记录——正是这套系统要的东西 |
12+//!
13+//! **但它只交出现状,不交出历史。** Notion 的版本历史不在公开 API 里,
14+//! 所以跟工单系统不同:一次同步只能看见此刻,之前的编辑全靠一次次同步慢慢攒。
15+//! 这跟 `url` / `rss` 是同一个形状,而工单那两个能一次把变更史拿全。
16+//!
17+//! ## 两个容易踩的
18+//!
19+//! **`Notion-Version` 头是必填的**,而且值是日期。少了它接口直接 400,
20+//! 而错误信息只说 "missing version",不会告诉你该填哪个。
21+//!
22+//! **限流是每秒三次**(官方说法是「平均三次」)。所以取页面内容时是顺序而不是
23+//! 并发——并发上去只会换来一串 429,而我们的重试退避是为抽取那条路设计的,
24+//! 不该被摄入路径借用。
25+
26+use anyhow::Context as _;
27+use chrono::{DateTime, Utc};
28+
29+/// 请求头里的 API 版本。**写死而不是留给配置**:响应的形状跟着它变,
30+/// 让用户填一个我们没适配过的版本,换来的是解析静默失配。
31+const NOTION_VERSION: &str = "2026-03-11";
32+
33+/// 一次同步最多取多少页。理由同别的来源:摄入不可逆,而一个 workspace
34+/// 可以有几万页。
35+const MAX_PAGES_PER_SYNC: usize = 500;
36+
37+/// 每页最多取多少个 block。再深的页面截断,比让一次同步卡在一页上好。
38+const MAX_BLOCKS_PER_PAGE: usize = 500;
39+
40+/// 一个待摄入的页面。
41+pub struct NotionPage {
42+ /// `notion://{page_id}`——页面 UUID 是它最稳的身份
43+ pub external_key: String,
44+ pub filename: String,
45+ pub text: String,
46+ pub last_edited: Option<DateTime<Utc>>,
47+}
48+
49+fn client(token: &str) -> anyhow::Result<reqwest::Client> {
50+ let mut h = reqwest::header::HeaderMap::new();
51+ h.insert("Notion-Version", NOTION_VERSION.parse()?);
52+ h.insert(
53+ reqwest::header::AUTHORIZATION,
54+ format!("Bearer {token}").parse()?,
55+ );
56+ Ok(reqwest::Client::builder()
57+ .default_headers(h)
58+ .timeout(std::time::Duration::from_secs(60))
59+ .build()?)
60+}
61+
62+/// 取 integration 能看见的所有页面。
63+///
64+/// **只搜页面,不搜 data source。** 后者是表格的容器,它自己没有正文;
65+/// 表格里的每一行是一个页面,会在同一次搜索里出现。
66+pub async fn fetch(token: &str, query: Option<&str>) -> anyhow::Result<(Vec<NotionPage>, bool)> {
67+ let http = client(token)?;
68+ let mut out = Vec::new();
69+ let mut cursor: Option<String> = None;
70+ let mut truncated = false;
71+
72+ loop {
73+ let mut body = serde_json::json!({
74+ "filter": { "property": "object", "value": "page" },
75+ "page_size": 100,
76+ });
77+ if let Some(q) = query {
78+ body["query"] = serde_json::Value::String(q.to_string());
79+ }
80+ if let Some(c) = &cursor {
81+ body["start_cursor"] = serde_json::Value::String(c.clone());
82+ }
83+
84+ let resp = http
85+ .post("https://api.notion.com/v1/search")
86+ .json(&body)
87+ .send()
88+ .await
89+ .context("notion search")?;
90+ let status = resp.status();
91+ let v: serde_json::Value = resp.json().await.context("notion search 响应")?;
92+ if !status.is_success() {
93+ anyhow::bail!(
94+ "notion search 回了 {status}: {}",
95+ v["message"].as_str().unwrap_or("unknown")
96+ );
97+ }
98+
99+ for p in v["results"].as_array().unwrap_or(&vec![]).clone() {
100+ // 回收站里的和归档的都不要——它们在界面上已经不算数了
101+ if p["in_trash"].as_bool() == Some(true) || p["is_archived"].as_bool() == Some(true) {
102+ continue;
103+ }
104+ if out.len() >= MAX_PAGES_PER_SYNC {
105+ truncated = true;
106+ break;
107+ }
108+ let Some(id) = p["id"].as_str() else { continue };
109+ let title = page_title(&p);
110+ let text = page_text(&http, id).await.unwrap_or_else(|e| {
111+ tracing::warn!(%id, error = %e, "页面正文取不回来,只留标题");
112+ String::new()
113+ });
114+
115+ out.push(NotionPage {
116+ external_key: format!("notion://{id}"),
117+ filename: format!("{}.md", slug(&title)),
118+ text: format!("# {title}\n\n{text}"),
119+ last_edited: p["last_edited_time"]
120+ .as_str()
121+ .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
122+ .map(|d| d.with_timezone(&Utc)),
123+ });
124+ }
125+
126+ if truncated || v["has_more"].as_bool() != Some(true) {
127+ break;
128+ }
129+ cursor = v["next_cursor"].as_str().map(str::to_string);
130+ if cursor.is_none() {
131+ break;
132+ }
133+ }
134+ Ok((out, truncated))
135+}
136+
137+/// 页面标题。
138+///
139+/// **标题藏在 `properties` 里那个 `type == "title"` 的属性下,而它的名字不固定**:
140+/// 数据库里的页面可能叫 `Name`、`名称`、`任务`,普通页面叫 `title`。
141+/// 按名字找会在别人的 workspace 上找不到,所以按类型找。
142+fn page_title(page: &serde_json::Value) -> String {
143+ let props = page["properties"].as_object();
144+ let t = props.and_then(|m| {
145+ m.values()
146+ .find(|v| v["type"] == "title")
147+ .and_then(|v| v["title"].as_array())
148+ });
149+ let s = t
150+ .map(|arr| {
151+ arr.iter()
152+ .filter_map(|r| r["plain_text"].as_str())
153+ .collect::<String>()
154+ })
155+ .unwrap_or_default();
156+ if s.trim().is_empty() {
157+ "untitled".into()
158+ } else {
159+ s
160+ }
161+}
162+
163+/// 取一页的正文,逐层展开 block。
164+async fn page_text(http: &reqwest::Client, page_id: &str) -> anyhow::Result<String> {
165+ let mut out = String::new();
166+ let mut n = 0usize;
167+ let mut cursor: Option<String> = None;
168+
169+ loop {
170+ let mut url = format!("https://api.notion.com/v1/blocks/{page_id}/children?page_size=100");
171+ if let Some(c) = &cursor {
172+ url.push_str(&format!("&start_cursor={c}"));
173+ }
174+ let resp = http.get(&url).send().await?;
175+ if !resp.status().is_success() {
176+ anyhow::bail!("blocks 回了 {}", resp.status());
177+ }
178+ let v: serde_json::Value = resp.json().await?;
179+
180+ for b in v["results"].as_array().unwrap_or(&vec![]) {
181+ if n >= MAX_BLOCKS_PER_PAGE {
182+ return Ok(out);
183+ }
184+ n += 1;
185+ if let Some(line) = render_block(b) {
186+ out.push_str(&line);
187+ out.push('\n');
188+ }
189+ }
190+ if v["has_more"].as_bool() != Some(true) {
191+ break;
192+ }
193+ cursor = v["next_cursor"].as_str().map(str::to_string);
194+ if cursor.is_none() {
195+ break;
196+ }
197+ }
198+ Ok(out)
199+}
200+
201+/// 把一个 block 渲染成一行文本。
202+///
203+/// **认不出的类型返回它的纯文本而不是丢掉。** Notion 的 block 类型一直在加,
204+/// 硬编码一张白名单意味着新类型静默消失;而所有带文字的 block 都把文字放在
205+/// `{type}.rich_text` 下,这个形状很稳。
206+fn render_block(b: &serde_json::Value) -> Option<String> {
207+ let t = b["type"].as_str()?;
208+ let inner = &b[t];
209+ let text = rich_text(&inner["rich_text"]);
210+
211+ Some(match t {
212+ "heading_1" => format!("## {text}"),
213+ "heading_2" => format!("### {text}"),
214+ "heading_3" => format!("#### {text}"),
215+ "bulleted_list_item" => format!("- {text}"),
216+ "numbered_list_item" => format!("1. {text}"),
217+ "to_do" => {
218+ let done = inner["checked"].as_bool() == Some(true);
219+ format!("- [{}] {text}", if done { "x" } else { " " })
220+ }
221+ "quote" => format!("> {text}"),
222+ "code" => {
223+ let lang = inner["language"].as_str().unwrap_or("");
224+ format!("```{lang}\n{text}\n```")
225+ }
226+ // 分割线与图片没有 rich_text,但它们在正文里也没有信息量
227+ "divider" | "image" | "video" | "file" => return None,
228+ // child_page 的标题在 `title` 而不是 rich_text
229+ "child_page" => format!("- {}", inner["title"].as_str().unwrap_or("")),
230+ _ if text.trim().is_empty() => return None,
231+ _ => text,
232+ })
233+}
234+
235+/// rich_text 数组拼成纯文本。
236+fn rich_text(v: &serde_json::Value) -> String {
237+ v.as_array()
238+ .map(|arr| {
239+ arr.iter()
240+ .filter_map(|r| r["plain_text"].as_str())
241+ .collect::<String>()
242+ })
243+ .unwrap_or_default()
244+}
245+
246+/// 标题变成能当文件名的东西。
247+fn slug(title: &str) -> String {
248+ let s: String = title
249+ .chars()
250+ .map(|c| if c.is_alphanumeric() { c } else { '-' })
251+ .collect();
252+ let s = s.trim_matches('-').to_string();
253+ if s.is_empty() {
254+ "untitled".into()
255+ } else {
256+ s.chars().take(60).collect()
257+ }
258+}
259+
260+#[cfg(test)]
261+mod tests {
262+ use super::*;
263+
264+ /// **标题属性的名字是任意的。** 数据库里的页面可能把它叫 `Name`、`名称`、
265+ /// `任务`;按名字找会在别人的 workspace 上返回 untitled,而那看起来
266+ /// 像是「页面没有标题」而不是「我们找错了地方」。
267+ #[test]
268+ fn a_title_is_found_by_type_not_by_name() {
269+ for key in ["title", "Name", "名称", "任务"] {
270+ let page = serde_json::json!({
271+ "properties": {
272+ key: { "type": "title", "title": [{ "plain_text": "季度复盘" }] },
273+ "Status": { "type": "select", "select": { "name": "Done" } }
274+ }
275+ });
276+ assert_eq!(page_title(&page), "季度复盘", "属性名 {key} 时找不到标题");
277+ }
278+ }
279+
280+ /// 富文本是分段的——加粗、链接都会把一句话切开。拼不全就会丢字。
281+ #[test]
282+ fn rich_text_segments_join_back_into_one_line() {
283+ let v = serde_json::json!([
284+ { "plain_text": "把总部搬到" },
285+ { "plain_text": "深圳" },
286+ { "plain_text": "了" }
287+ ]);
288+ assert_eq!(rich_text(&v), "把总部搬到深圳了");
289+ }
290+
291+ /// **认不出的 block 类型不能丢。** Notion 一直在加类型,而带文字的
292+ /// block 都把文字放在 `{type}.rich_text` 下——按白名单渲染会让新类型
293+ /// 静默消失。
294+ #[test]
295+ fn an_unknown_block_keeps_its_text() {
296+ let b = serde_json::json!({
297+ "type": "some_new_block_type_2027",
298+ "some_new_block_type_2027": { "rich_text": [{ "plain_text": "还是有内容的" }] }
299+ });
300+ assert_eq!(render_block(&b).as_deref(), Some("还是有内容的"));
301+ }
302+
303+ /// 没有文字的装饰性 block 该消失,否则正文里全是空行。
304+ #[test]
305+ fn a_divider_renders_to_nothing() {
306+ let b = serde_json::json!({ "type": "divider", "divider": {} });
307+ assert!(render_block(&b).is_none());
308+ }
309+
310+ /// 文件名不能带路径分隔符或换行。
311+ #[test]
312+ fn a_slug_is_safe_as_a_filename() {
313+ assert_eq!(slug("2026 Q3 / 复盘"), "2026-Q3---复盘");
314+ assert_eq!(slug("///"), "untitled");
315+ assert!(slug(&"x".repeat(200)).chars().count() <= 60);
316+ }
317+
318+ /// 真连一个 Notion workspace。**没有模拟器**——Notion 是闭源 SaaS,
319+ /// 开源的替代品(AppFlowy、AFFiNE)不说这套 API。所以这条只有在
320+ /// 有人给出真 token 时才跑,CI 上永远跳过。
321+ ///
322+ /// ```text
323+ /// # 设置 → 我的连接 → 新建内部集成,然后把一个页面分享给它
324+ /// UTOPIA_NOTION_TEST_TOKEN=ntn_xxx cargo test -p utopia-server notion
325+ /// ```
326+ #[tokio::test]
327+ async fn it_reads_from_a_real_workspace() -> anyhow::Result<()> {
328+ let Ok(token) = std::env::var("UTOPIA_NOTION_TEST_TOKEN") else {
329+ eprintln!("跳过:未设 UTOPIA_NOTION_TEST_TOKEN");
330+ return Ok(());
331+ };
332+ let (pages, _) = fetch(&token, None).await?;
333+ assert!(
334+ !pages.is_empty(),
335+ "一页都没有——integration 可能没有被分享任何页面"
336+ );
337+ let p = &pages[0];
338+ assert!(
339+ p.external_key.starts_with("notion://"),
340+ "{}",
341+ p.external_key
342+ );
343+ assert!(p.text.starts_with("# "), "正文该以标题开头");
344+ assert!(
345+ p.last_edited.is_some(),
346+ "last_edited_time 是 doc_time 的来源"
347+ );
348+ Ok(())
349+ }
350+}
added crates/utopia-server/src/object_storage.rs +420 −0
@@ -0,0 +1,420 @@
1+//! 对象存储来源:S3(及 MinIO、Ceph RGW、R2 等说同一套协议的)、Azure Blob、
2+//! Google Cloud Storage。三家共用这一个模块——`object_store` 把差异收在
3+//! builder 里,列与取的那段代码一个字都不用改。
4+//!
5+//! 按 [0013](../../docs/decisions/0013-a-source-should-hand-over-its-history.md)
6+//! 的四条判据看,它跟工单系统不是一类:
7+//!
8+//! | 判据 | 对象存储 |
9+//! |---|---|
10+//! | 真实时间戳 | `LastModified`,但它是**写入时刻**不是文档自身的时间 |
11+//! | 会不会自我推翻 | 同 key 覆写就是一次改口,但要靠两次同步之间的差异看出来 |
12+//! | 稳定身份 | `bucket/key`,最干净的一条 |
13+//! | 企业知识住不住在那儿 | **最强的一条**——文档堆、归档、数据湖落地区都在这儿 |
14+//!
15+//! 所以它的价值在第四条:**够得着**。第二条只有部分——工单系统能一次交出
16+//! 整段变更史,而对象存储要么开了版本控制(本版不读,见下),要么只能靠
17+//! 一次次同步慢慢攒。这跟 `url` / `rss` 是同一档,不比它们低。
18+//!
19+//! **版本历史本版不做。** `ListObjectVersions` 能一次拿到 0013 想要的那段历史,
20+//! 但多数桶没开版本控制,开了的桶里也大多是写一次不再动的对象——把每个版本
21+//! 都摄进来,代价与收益不成比例。等有人真的需要(一份季度更新的制度文件,
22+//! 想看它改了什么)再按开关加。
23+//!
24+//! **为什么是 `object_store` 而不是 `aws-sdk-s3` / `rust-s3`**:实测传递依赖
25+//! `+7` 对 `+43` / `+42`——它复用了树里已有的 `reqwest`、`ring`、`quick-xml`。
26+//! 而且同一套 API 还覆盖 Azure Blob 与 GCS,路线图上「更多数据源」与
27+//! 「数据湖仓」两条都在这条线上,换后端只是换一个 builder。
28+
29+use anyhow::Context as _;
30+use chrono::{DateTime, Utc};
31+use futures_util::StreamExt as _;
32+use object_store::aws::AmazonS3Builder;
33+use object_store::azure::MicrosoftAzureBuilder;
34+use object_store::gcp::GoogleCloudStorageBuilder;
35+// `get` 住在 `ObjectStoreExt` 上,不在 `ObjectStore` 本体——后者只有
36+// `get_opts`。少这一行的报错是「&dyn ObjectStore 没有 get 方法」,
37+// 而 trait 名字里看不出来。
38+use object_store::{path::Path as StorePath, ObjectStore, ObjectStoreExt as _};
39+
40+/// 一次同步最多摄入多少个对象。
41+///
42+/// **不是性能考虑,是「别把一个桶整个吸进来」。** 桶里放上百万个对象是常态,
43+/// 而摄入是不可逆的:每个对象要抽取、要向量化、要进图。配错一个前缀就能
44+/// 烧掉一整天的额度,而且清理起来比配置麻烦得多。
45+///
46+/// 到顶时报进同步统计,让人看得见「还有」,而不是悄悄截断。
47+const MAX_OBJECTS_PER_SYNC: usize = 2_000;
48+
49+/// 单个对象的大小上限。跟上传路径同一个数量级——超过这个尺寸的多半不是
50+/// 文档而是数据文件(备份、镜像、视频),抽取器拿它没有用。
51+const MAX_OBJECT_BYTES: u64 = 32 * 1024 * 1024;
52+
53+/// 一个待摄入的对象。
54+pub struct RemoteObject {
55+ /// `s3://bucket/key`——`ingest_item` 的 external_key 约定是 URI 形态
56+ pub external_key: String,
57+ /// 落进文档的文件名,取 key 的最后一段
58+ pub filename: String,
59+ pub bytes: Vec<u8>,
60+ pub last_modified: Option<DateTime<Utc>>,
61+}
62+
63+/// 从来源配置建一个客户端。三家云共用这一个入口,按 `kind` 分派。
64+///
65+/// **三家的「桶」都叫 `bucket`**,尽管 Azure 管它叫容器、GCS 管它叫存储桶。
66+/// 配置项跟着产品术语走会让表单和文档各说各话,而这一层要的只是「装东西的
67+/// 那个东西叫什么」。凭据字段按各家的原名(`access_key_id` /
68+/// `account_key` / `service_account_key`),那些是用户从控制台复制过来的,
69+/// 改名只会让人对不上。
70+///
71+/// **`endpoint` 在则走自建**(MinIO、Ceph、R2、Azurite),此时对 S3 强制
72+/// path-style:虚拟主机式寻址要求 `bucket.host` 这样的域名解析得开,而自建
73+/// 部署通常只有一个裸 IP。不强制的话症状是「桶不存在」,而桶明明就在那儿。
74+///
75+/// 允许 http 也是为它:内网的 MinIO 与本地的模拟器常常不挂 TLS。
76+/// **这是配置说了算的降级**,不是默认——不给 endpoint 就仍然只走 https。
77+pub fn client(kind: &str, config: &serde_json::Value) -> anyhow::Result<Box<dyn ObjectStore>> {
78+ let s = |k: &str| {
79+ config[k]
80+ .as_str()
81+ .map(str::trim)
82+ .filter(|v| !v.is_empty())
83+ .map(str::to_string)
84+ };
85+ let bucket =
86+ s("bucket").ok_or_else(|| anyhow::anyhow!("{kind} source is missing config.bucket"))?;
87+ let endpoint = s("endpoint");
88+ let insecure = endpoint
89+ .as_deref()
90+ .is_some_and(|e| e.starts_with("http://"));
91+
92+ match kind {
93+ "azure_blob" => {
94+ let mut b = MicrosoftAzureBuilder::new().with_container_name(&bucket);
95+ if let Some(account) = s("account_name") {
96+ b = b.with_account(account);
97+ }
98+ if let Some(key) = s("account_key") {
99+ b = b.with_access_key(key);
100+ }
101+ if let Some(e) = endpoint {
102+ b = b.with_endpoint(e).with_allow_http(insecure);
103+ }
104+ Ok(Box::new(b.build().context("azure blob client")?))
105+ }
106+ "gcs" => {
107+ let mut b = GoogleCloudStorageBuilder::new().with_bucket_name(&bucket);
108+ // 服务账号 JSON 整份贴进来,不是路径:来源配置是一行 JSONB,
109+ // 而服务器上未必有那个文件
110+ let key = s("service_account_key");
111+ if let Some(json) = key.clone() {
112+ b = b.with_service_account_key(json);
113+ }
114+ if let Some(e) = endpoint {
115+ // **`with_base_url` 而不是 `with_url`。** 后者是用来解析
116+ // `gs://bucket/path` 这种存储位置的,喂一个 http 端点给它,
117+ // 报错是「Unknown url scheme cannot be parsed」——名字看不出区别
118+ b = b.with_base_url(&e);
119+ // 自建端点通常没有 Google 的凭据体系(模拟器、S3 网关)。
120+ // 没给服务账号就跳过签名,否则 builder 会去找默认凭据然后失败
121+ if key.is_none() {
122+ b = b.with_skip_signature(true);
123+ }
124+ }
125+ Ok(Box::new(b.build().context("gcs client")?))
126+ }
127+ // s3 与一切说同一套协议的
128+ _ => {
129+ let mut b = AmazonS3Builder::new().with_bucket_name(&bucket);
130+ if let Some(region) = s("region") {
131+ b = b.with_region(region);
132+ }
133+ if let (Some(key), Some(secret)) = (s("access_key_id"), s("secret_access_key")) {
134+ b = b.with_access_key_id(key).with_secret_access_key(secret);
135+ }
136+ if let Some(e) = endpoint {
137+ b = b
138+ .with_endpoint(e)
139+ .with_virtual_hosted_style_request(false)
140+ .with_allow_http(insecure);
141+ }
142+ Ok(Box::new(b.build().context("object storage client")?))
143+ }
144+ }
145+}
146+
147+/// 各家的 URI scheme,用作 external_key 的前缀。
148+///
149+/// 写死而不是拿 kind 直接拼:GCS 的通用写法是 gs 而来源类型叫 gcs,
150+/// Azure 的容器 URI 也不叫 azure_blob。这里要的是别人认得出的那个形态。
151+fn uri_scheme(kind: &str) -> &'static str {
152+ match kind {
153+ "azure_blob" => "azure",
154+ "gcs" => "gs",
155+ _ => "s3",
156+ }
157+}
158+
159+/// 列出前缀下的对象并逐个取回。
160+///
161+/// **零字节的一律跳过,判据是大小不是名字。** 直觉的写法是看 key 以不以 `/`
162+/// 结尾——控制台和 `aws s3 sync` 就是这样造「文件夹」的。但 `object_store`
163+/// 的 `Path` 会**把尾斜杠规范化掉**,`docs/` 到手里就成了 `docs`,那个判断
164+/// 永远不成立;接着它去 GET `docs`,而桶里真实的 key 是 `docs/`,
165+/// 于是 404 把整次同步带走。实测在 MinIO 上就是这样炸的。
166+///
167+/// 按大小判还更宽:零字节的对象无论叫什么都不是文档,`ingest_item` 拿到
168+/// 空字节也只会返回 `Unchanged`。
169+///
170+/// 格式不在这里判。`utopia_ingest` 的抽取按扩展名加 mime 分派,认不出的
171+/// 一律按文本解码——在这里再维护一张白名单,就是同一件事写两遍,
172+/// 而两份清单迟早分叉。
173+pub async fn fetch(
174+ kind: &str,
175+ store: &dyn ObjectStore,
176+ bucket: &str,
177+ prefix: Option<&str>,
178+) -> anyhow::Result<(Vec<RemoteObject>, bool)> {
179+ // **三家各用各的 scheme。** 身份要唯一:同名的桶在 S3 与 GCS 上是两个
180+ // 不同的东西,共用一个前缀会让两个来源的文档互相认领
181+ let scheme = uri_scheme(kind);
182+ let p = prefix.map(StorePath::from);
183+ let mut listing = store.list(p.as_ref());
184+ let mut out = Vec::new();
185+ let mut truncated = false;
186+ let mut unreadable = 0usize;
187+
188+ while let Some(meta) = listing.next().await {
189+ let meta = meta.context("listing objects")?;
190+ let key = meta.location.as_ref().to_string();
191+
192+ if meta.size == 0 {
193+ continue;
194+ }
195+ if meta.size > MAX_OBJECT_BYTES {
196+ tracing::info!(%key, size = meta.size, "对象太大,跳过");
197+ continue;
198+ }
199+ if out.len() >= MAX_OBJECTS_PER_SYNC {
200+ truncated = true;
201+ break;
202+ }
203+
204+ // **一个对象取不回来不该带走整次同步。** 列表与取回之间隔着时间,
205+ // 中途被删、被换权限都是正常的;桶越大越常见。记下来在收尾时一并报,
206+ // 而不是让第 900 个对象的一次 404 把前 899 个的成果一起丢掉。
207+ let got = async {
208+ let r = store.get(&meta.location).await?;
209+ r.bytes().await
210+ }
211+ .await;
212+ let bytes = match got {
213+ Ok(b) => b,
214+ Err(e) => {
215+ unreadable += 1;
216+ tracing::warn!(%key, error = %e, "对象取不回来,跳过");
217+ continue;
218+ }
219+ };
220+
221+ out.push(RemoteObject {
222+ external_key: format!("{scheme}://{bucket}/{key}"),
223+ filename: key.rsplit('/').next().unwrap_or(&key).to_string(),
224+ bytes: bytes.to_vec(),
225+ last_modified: Some(meta.last_modified),
226+ });
227+ }
228+ if unreadable > 0 {
229+ tracing::warn!(unreadable, bucket, "有对象没能取回");
230+ }
231+ Ok((out, truncated))
232+}
233+
234+#[cfg(test)]
235+mod tests {
236+ use super::*;
237+
238+ /// 自建端点必须走 path-style,否则请求会打到 `bucket.host` 上,
239+ /// 而自建部署一般没有那条 DNS 记录。症状是「桶不存在」而桶就在那儿。
240+ #[test]
241+ fn a_self_hosted_endpoint_builds() {
242+ let cfg = serde_json::json!({
243+ "bucket": "docs",
244+ "endpoint": "http://127.0.0.1:9000",
245+ "region": "us-east-1",
246+ "access_key_id": "minioadmin",
247+ "secret_access_key": "minioadmin",
248+ });
249+ assert!(client("s3", &cfg).is_ok());
250+ }
251+
252+ /// 不给 bucket 要报得出是缺哪一项——照 jira / github 两个来源的措辞。
253+ #[test]
254+ fn a_missing_bucket_says_so() {
255+ let e = client("s3", &serde_json::json!({ "region": "us-east-1" })).unwrap_err();
256+ assert!(e.to_string().contains("config.bucket"), "{e}");
257+ }
258+
259+ /// 公有云那条路:不给 endpoint 就不该被强制成 path-style,
260+ /// 也不该允许明文 http。
261+ #[test]
262+ fn a_cloud_bucket_needs_no_endpoint() {
263+ let cfg = serde_json::json!({
264+ "bucket": "docs",
265+ "region": "ap-southeast-1",
266+ "access_key_id": "AKIA...",
267+ "secret_access_key": "...",
268+ });
269+ assert!(client("s3", &cfg).is_ok());
270+ }
271+
272+ /// 真连一个 S3 兼容端点,只测**读**这一侧:列出来、取回内容、身份对不对。
273+ ///
274+ /// **没有 `UTOPIA_S3_TEST_ENDPOINT` 时跳过而不是失败**——跟连库的测试
275+ /// 同一个约定(见 CONTRIBUTING)。上面那三条只证明 builder 拼得出来,
276+ /// 而这条要守的是**线上协议真的说得通**:path-style 有没有生效、
277+ /// 明文 http 放没放行、`s3://` 身份拼得对不对、`LastModified` 回不回来。
278+ /// 没有一条是构造 client 时能发现的。
279+ ///
280+ /// **数据由外部布置,测试不写只读。** 第一版让测试自己 `put`,结果被
281+ /// `object_store` 的 `Path` 咬了一口:它会把 `docs/` 规范化成 `docs`,
282+ /// 于是「目录占位」写成了一个名叫 `docs` 的普通对象,而 MinIO 不允许
283+ /// 对象 `docs` 与前缀 `docs/` 并存——整个前缀被顶掉,列表回来是空的。
284+ /// 真实的占位对象只能由别的客户端造,那就让它由别的客户端造。
285+ ///
286+ /// 跑法(先起 MinIO,再用 curl 布数据;curl 自带 SigV4):
287+ /// ```text
288+ /// MINIO_ROOT_USER=u MINIO_ROOT_PASSWORD=p123456 \
289+ /// minio server ./data --address 127.0.0.1:19000 &
290+ /// S3="curl -s --aws-sigv4 aws:amz:us-east-1:s3 -u u:p123456"
291+ /// B=http://127.0.0.1:19000/utopia-conn-test
292+ /// $S3 -X PUT $B # 建桶
293+ /// $S3 -X PUT --data-raw hello "$B/docs/a.txt"
294+ /// $S3 -X PUT --data-raw '# world' "$B/docs/b.md"
295+ /// $S3 -X PUT --data-raw '' "$B/docs/" # 目录占位
296+ /// UTOPIA_S3_TEST_ENDPOINT=http://127.0.0.1:19000 \
297+ /// UTOPIA_S3_TEST_KEY=u UTOPIA_S3_TEST_SECRET=p123456 \
298+ /// cargo test -p utopia-server object_storage
299+ /// ```
300+ #[tokio::test]
301+ async fn it_reads_from_a_real_s3_endpoint() -> anyhow::Result<()> {
302+ let Ok(endpoint) = std::env::var("UTOPIA_S3_TEST_ENDPOINT") else {
303+ eprintln!("跳过:未设 UTOPIA_S3_TEST_ENDPOINT");
304+ return Ok(());
305+ };
306+ let bucket = "utopia-conn-test";
307+ let cfg = serde_json::json!({
308+ "bucket": bucket,
309+ "endpoint": endpoint,
310+ "region": "us-east-1",
311+ "access_key_id": std::env::var("UTOPIA_S3_TEST_KEY").unwrap_or("minioadmin".into()),
312+ "secret_access_key": std::env::var("UTOPIA_S3_TEST_SECRET").unwrap_or("minioadmin".into()),
313+ });
314+ let store = client("s3", &cfg)?;
315+
316+ let (objs, truncated) = fetch("s3", store.as_ref(), bucket, Some("docs")).await?;
317+ assert!(!truncated, "三个对象不该触发上限");
318+
319+ let keys: Vec<&str> = objs.iter().map(|o| o.external_key.as_str()).collect();
320+ for want in [
321+ "s3://utopia-conn-test/docs/a.txt",
322+ "s3://utopia-conn-test/docs/b.md",
323+ ] {
324+ assert!(keys.contains(&want), "少了 {want}:{keys:?}");
325+ }
326+
327+ // **这条守的是一个真炸过的 bug。** 桶里有一个 `docs/` 目录占位对象,
328+ // 而 `object_store` 把尾斜杠规范化掉了,于是它以 `docs` 的身份进到
329+ // 循环里,GET 回来 404,整次同步失败。三条构造 client 的单元测试
330+ // 一条都发现不了——只有真连一个装过「文件夹」的桶才看得见。
331+ assert_eq!(objs.len(), 2, "目录占位对象没被滤掉:{keys:?}");
332+
333+ let a = objs.iter().find(|o| o.filename == "a.txt").expect("a.txt");
334+ assert_eq!(a.bytes, b"hello", "取回的内容不对");
335+ assert!(
336+ a.last_modified.is_some(),
337+ "LastModified 是 doc_time 的唯一来源"
338+ );
339+ Ok(())
340+ }
341+
342+ /// Azure Blob 真连一次。**跟 S3 那条是两套线上协议**——签名算法、列表
343+ /// 响应的形状、容器与桶的语义都不同,共用一个 builder 抽象不代表
344+ /// 共用一条能跑通的路径。
345+ ///
346+ /// 用 Azurite(官方模拟器)验,没有 `UTOPIA_AZURE_TEST_ENDPOINT` 就跳过:
347+ /// ```text
348+ /// docker run -d -p 10000:10000 mcr.microsoft.com/azure-storage/azurite \\
349+ /// azurite-blob --blobHost 0.0.0.0 --skipApiVersionCheck
350+ /// # 用 rclone 布数据(rclone 原生支持 Azurite 的开发账号)
351+ /// UTOPIA_AZURE_TEST_ENDPOINT=http://127.0.0.1:10000/devstoreaccount1 \\
352+ /// cargo test -p utopia-server object_storage
353+ /// ```
354+ #[tokio::test]
355+ async fn it_reads_from_azure_blob() -> anyhow::Result<()> {
356+ let Ok(endpoint) = std::env::var("UTOPIA_AZURE_TEST_ENDPOINT") else {
357+ eprintln!("跳过:未设 UTOPIA_AZURE_TEST_ENDPOINT");
358+ return Ok(());
359+ };
360+ let cfg = serde_json::json!({
361+ "bucket": "utopia-conn-test",
362+ "endpoint": endpoint,
363+ "account_name": "devstoreaccount1",
364+ // Azurite 的固定开发密钥。公开常量,不是凭据
365+ "account_key": "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",
366+ });
367+ let store = client("azure_blob", &cfg)?;
368+ let (objs, _) = fetch(
369+ "azure_blob",
370+ store.as_ref(),
371+ "utopia-conn-test",
372+ Some("docs"),
373+ )
374+ .await?;
375+
376+ let a = objs.iter().find(|o| o.filename == "a.txt").expect("a.txt");
377+ assert_eq!(a.bytes, b"hello from azure");
378+ // **身份要带各家自己的 scheme**:同名的桶在两家云上是两个东西
379+ assert_eq!(a.external_key, "azure://utopia-conn-test/docs/a.txt");
380+ assert!(a.last_modified.is_some());
381+ Ok(())
382+ }
383+
384+ /// GCS 真连一次。**没有可用的模拟器,所以这条在 CI 上永远跳过。**
385+ ///
386+ /// 试过 `fsouza/fake-gcs-server`,不行:它只实现 JSON API
387+ /// (`/storage/v1/b/...`),而 `object_store` 的 GCS 后端列对象走的是
388+ /// **XML API**(`/bucket?list-type=2`),那个路径上它回 404。
389+ /// 换句话说,最常见的那个 GCS 模拟器测不了我们实际用的那条协议路径。
390+ ///
391+ /// 所以 GCS 这条路径**只有构造测试覆盖**,跟 S3 与 Azure 不是一个成色。
392+ /// 有真桶的人跑一次就能补上:
393+ /// ```text
394+ /// UTOPIA_GCS_TEST_ENDPOINT=https://storage.googleapis.com \\
395+ /// UTOPIA_GCS_TEST_BUCKET=your-bucket \\
396+ /// UTOPIA_GCS_TEST_KEY="$(cat service-account.json)" \\
397+ /// cargo test -p utopia-server object_storage
398+ /// ```
399+ #[tokio::test]
400+ async fn it_reads_from_gcs() -> anyhow::Result<()> {
401+ let (Ok(endpoint), Ok(bucket)) = (
402+ std::env::var("UTOPIA_GCS_TEST_ENDPOINT"),
403+ std::env::var("UTOPIA_GCS_TEST_BUCKET"),
404+ ) else {
405+ eprintln!("跳过:未设 UTOPIA_GCS_TEST_ENDPOINT / _BUCKET");
406+ return Ok(());
407+ };
408+ let mut cfg = serde_json::json!({ "bucket": bucket, "endpoint": endpoint });
409+ if let Ok(k) = std::env::var("UTOPIA_GCS_TEST_KEY") {
410+ cfg["service_account_key"] = serde_json::Value::String(k);
411+ }
412+ let store = client("gcs", &cfg)?;
413+ let (objs, _) = fetch("gcs", store.as_ref(), &bucket, Some("docs")).await?;
414+
415+ let a = objs.iter().find(|o| o.filename == "a.txt").expect("a.txt");
416+ assert_eq!(a.external_key, format!("gs://{bucket}/docs/a.txt"));
417+ assert!(a.last_modified.is_some());
418+ Ok(())
419+ }
420+}
modified crates/utopia-server/src/pipeline.rs +8 −2
@@ -93,7 +93,13 @@
9393 /// 记忆摄入(episodes 快速路径的后半程):新 episode chunk 补 embedding、
9494 /// 重建全文索引、触发增量抽取(extracted_at 为空的新 chunk 才会被抽)。
9595 /// 免解析免分块——episode 落库时已是 chunk。
96-pub async fn memory_ingest(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
96+///
97+/// `proposed_by`:说这句话的人。一路传到抽取,落在 `pending_facts.proposed_by`(0015)
98+pub async fn memory_ingest(
99+ state: &AppState,
100+ document_id: Uuid,
101+ proposed_by: Option<Uuid>,
102+) -> anyhow::Result<()> {
97103 let doc = utopia_store::documents::get(&state.pool, document_id).await?;
98104 let kb_row = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
99105 let settings = utopia_store::settings::get(&state.pool, kb_row.workspace_id).await?;
@@ -132,7 +138,7 @@
132138 utopia_store::jobs::enqueue(
133139 &state.pool,
134140 "extract_document",
135- serde_json::json!({ "document_id": document_id }),
141+ serde_json::json!({ "document_id": document_id, "proposed_by": proposed_by }),
136142 )
137143 .await?;
138144 }
modified crates/utopia-server/src/state.rs +10 −0
@@ -82,6 +82,16 @@
8282 });
8383 }
8484
85+ /// 一句记忆抽出了等人点头的事实(0015)。对话里那张确认卡按这个刷新——
86+ /// 抽取是异步的,卡片只能在任务完成时长出来,而不是在助手回话的那一刻
87+ pub fn emit_pending(&self, kb_id: Uuid) {
88+ let _ = self.events.send(AppEvent {
89+ kb_id: Some(kb_id),
90+ kind: "pending",
91+ document_id: None,
92+ });
93+ }
94+
8595 /// 图变了。推理往图里加过边之后要发一次——它不经过文档管道,
8696 /// 而 `document` 那条事件是文档管道专用的
8797 pub fn emit_graph(&self, kb_id: Uuid) {
added crates/utopia-server/src/webdav.rs +396 −0
@@ -0,0 +1,396 @@
1+//! WebDAV 来源:Nextcloud、ownCloud、坚果云、群晖、Apache mod_dav、
2+//! rclone serve webdav,以及一切说这套协议的网盘。
3+//!
4+//! 按 [0013](../../docs/decisions/0013-a-source-should-hand-over-its-history.md)
5+//! 的四条判据,它跟对象存储是同一档:有 `getlastmodified`、身份是路径、
6+//! 企业里确实有一堆文档住在网盘上;而「会不会自我推翻」只能靠两次同步的
7+//! 差异看出来——WebDAV 的版本控制扩展(RFC 3253)几乎没有服务端实现。
8+//!
9+//! **不引 WebDAV 客户端库。** 这套协议要的东西很窄:一个 `PROPFIND` 拿列表、
10+//! 一个 `GET` 取内容,响应是 XML。`reqwest` 与 `quick-xml` 都已经在树里,
11+//! 加起来零新增依赖;而现有的 dav 客户端 crate 要么裹着自己的 HTTP 栈,
12+//! 要么把整套 RFC 4918(锁、属性写、版本)都拖进来,而那些我们一条都不用。
13+
14+use anyhow::Context as _;
15+use chrono::{DateTime, Utc};
16+use quick_xml::events::Event;
17+use quick_xml::Reader;
18+
19+/// 一次同步最多摄入多少个文件。理由与对象存储那边相同:网盘也能装下
20+/// 十万个文件,而摄入不可逆。
21+const MAX_FILES_PER_SYNC: usize = 2_000;
22+
23+/// 单个文件的大小上限。
24+const MAX_FILE_BYTES: u64 = 32 * 1024 * 1024;
25+
26+/// 目录递归的层数上限。**不是怕深,是怕环**:有些服务端会把符号链接
27+/// 或共享目录暴露成可以自己指向自己的路径,`Depth: infinity` 在那种目录上
28+/// 永远回不来。逐层走并且封顶,比信任服务端安全。
29+const MAX_DEPTH: usize = 8;
30+
31+/// 一个远端文件。
32+pub struct RemoteFile {
33+ /// `webdav://host/path`——`ingest_item` 的 external_key 约定是 URI 形态
34+ pub external_key: String,
35+ pub filename: String,
36+ pub bytes: Vec<u8>,
37+ pub last_modified: Option<DateTime<Utc>>,
38+}
39+
40+/// `PROPFIND` 回来的一条。
41+#[derive(Debug, PartialEq)]
42+struct Entry {
43+ /// 服务端给的 href,已解码
44+ href: String,
45+ is_dir: bool,
46+ len: u64,
47+ modified: Option<DateTime<Utc>>,
48+}
49+
50+/// 解析 `multistatus` 响应。
51+///
52+/// **只认本地名,不认前缀。** 服务端可能用 `D:`、`d:`、`ns0:`,也可能干脆
53+/// 不加前缀——RFC 允许任意前缀绑到 `DAV:` 命名空间上。按 `d:response` 这样
54+/// 硬匹配的解析器,换一台服务端就一条都读不出来,而症状是「同步成功,
55+/// 零个文件」。
56+///
57+/// **目录判据是 `<collection/>` 存在,不是 href 以 `/` 结尾。** 后者是约定
58+/// 不是规范,而 rclone 与 Nextcloud 在这一点上就不一致。
59+fn parse_multistatus(xml: &str) -> anyhow::Result<Vec<Entry>> {
60+ let mut r = Reader::from_str(xml);
61+ r.config_mut().trim_text(true);
62+
63+ let mut out = Vec::new();
64+ let mut cur: Option<Entry> = None;
65+ let mut field = String::new();
66+ let mut buf = Vec::new();
67+
68+ loop {
69+ match r.read_event_into(&mut buf) {
70+ Ok(Event::Start(e)) => {
71+ let name = local_name(e.name().into_inner());
72+ match name.as_str() {
73+ "response" => {
74+ cur = Some(Entry {
75+ href: String::new(),
76+ is_dir: false,
77+ len: 0,
78+ modified: None,
79+ });
80+ }
81+ "collection" => {
82+ if let Some(c) = cur.as_mut() {
83+ c.is_dir = true;
84+ }
85+ }
86+ other => field = other.to_string(),
87+ }
88+ }
89+ // `<collection/>` 通常是自闭合标签,走 Empty 而不是 Start——
90+ // 少了这一条,所有目录都会被当成文件去 GET
91+ Ok(Event::Empty(e)) => {
92+ if local_name(e.name().into_inner()) == "collection" {
93+ if let Some(c) = cur.as_mut() {
94+ c.is_dir = true;
95+ }
96+ }
97+ }
98+ Ok(Event::Text(t)) => {
99+ let Some(c) = cur.as_mut() else { continue };
100+ let v = t
101+ .xml_content(quick_xml::XmlVersion::Implicit1_0)
102+ .to_string();
103+ match field.as_str() {
104+ "href" => c.href = percent_decode(&v),
105+ "getcontentlength" => c.len = v.trim().parse().unwrap_or(0),
106+ "getlastmodified" => {
107+ // RFC 1123,`Wed, 02 Sep 2026 15:04:05 GMT`
108+ c.modified = DateTime::parse_from_rfc2822(v.trim())
109+ .ok()
110+ .map(|d| d.with_timezone(&Utc));
111+ }
112+ _ => {}
113+ }
114+ }
115+ Ok(Event::End(e)) => {
116+ if local_name(e.name().into_inner()) == "response" {
117+ if let Some(c) = cur.take() {
118+ out.push(c);
119+ }
120+ }
121+ field.clear();
122+ }
123+ Ok(Event::Eof) => break,
124+ Err(e) => return Err(anyhow::anyhow!("PROPFIND 响应解析失败: {e}")),
125+ _ => {}
126+ }
127+ buf.clear();
128+ }
129+ Ok(out)
130+}
131+
132+/// 取标签的本地名,丢掉命名空间前缀并转小写。
133+///
134+/// 规范说元素名区分大小写,但实测有服务端写 `getLastModified`。
135+/// 前缀也自己切:`D:`、`d:`、`ns0:` 都合法,RFC 允许任意前缀绑到 `DAV:`。
136+fn local_name(raw: &str) -> String {
137+ raw.rsplit(':').next().unwrap_or(raw).to_ascii_lowercase()
138+}
139+
140+/// href 里的百分号转义。
141+///
142+/// 自己解而不是引 `percent-encoding`:这里只需要解码,而解码是十来行。
143+/// 非法序列原样留下——href 是拿来拼 URL 的,猜错了不如不动。
144+fn percent_decode(s: &str) -> String {
145+ let b = s.as_bytes();
146+ let mut out = Vec::with_capacity(b.len());
147+ let mut i = 0;
148+ while i < b.len() {
149+ if b[i] == b'%' && i + 2 < b.len() {
150+ let hex = std::str::from_utf8(&b[i + 1..i + 3]).ok();
151+ if let Some(v) = hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
152+ out.push(v);
153+ i += 3;
154+ continue;
155+ }
156+ }
157+ out.push(b[i]);
158+ i += 1;
159+ }
160+ String::from_utf8_lossy(&out).into_owned()
161+}
162+
163+/// 逐层走目录,取回所有文件。
164+///
165+/// **不用 `Depth: infinity`。** 规范允许服务端拒绝它(`403 Propfind-Finite-Depth`),
166+/// 而 Nextcloud 与 Apache mod_dav 默认就是拒绝的;能接受它的服务端在大目录上
167+/// 又会一次性吐出几十兆 XML。逐层加封顶,两头的问题都没有。
168+pub async fn fetch(
169+ http: &reqwest::Client,
170+ base: &str,
171+ root: &str,
172+ auth: Option<(&str, &str)>,
173+) -> anyhow::Result<(Vec<RemoteFile>, bool)> {
174+ let host = reqwest::Url::parse(base)
175+ .ok()
176+ .and_then(|u| u.host_str().map(str::to_string))
177+ .unwrap_or_else(|| "webdav".into());
178+ let base = base.trim_end_matches('/').to_string();
179+
180+ let mut out = Vec::new();
181+ let mut truncated = false;
182+ let mut queue = vec![(normalize(root), 0usize)];
183+ let mut unreadable = 0usize;
184+
185+ while let Some((dir, depth)) = queue.pop() {
186+ if depth > MAX_DEPTH {
187+ tracing::warn!(%dir, "目录太深,不再往下");
188+ continue;
189+ }
190+ let url = format!("{base}{dir}");
191+ let mut req = http
192+ .request(reqwest::Method::from_bytes(b"PROPFIND").unwrap(), &url)
193+ .header("Depth", "1")
194+ .header("Content-Type", "application/xml");
195+ if let Some((u, p)) = auth {
196+ req = req.basic_auth(u, Some(p));
197+ }
198+ let resp = req
199+ .send()
200+ .await
201+ .with_context(|| format!("PROPFIND {url}"))?;
202+ if !resp.status().is_success() {
203+ anyhow::bail!("PROPFIND {url} 回了 {}", resp.status());
204+ }
205+ let xml = resp.text().await.context("读取 PROPFIND 响应")?;
206+
207+ for e in parse_multistatus(&xml)? {
208+ let path = normalize(&strip_base(&e.href, &base));
209+ // 服务端会把被查询的目录自己也列进来,跳过它否则会无限打转
210+ if path == dir {
211+ continue;
212+ }
213+ if e.is_dir {
214+ queue.push((path, depth + 1));
215+ continue;
216+ }
217+ if e.len == 0 || e.len > MAX_FILE_BYTES {
218+ continue;
219+ }
220+ if out.len() >= MAX_FILES_PER_SYNC {
221+ truncated = true;
222+ break;
223+ }
224+
225+ // 一个文件取不回来不该带走整次同步——与对象存储那边同一个判断
226+ let mut g = http.get(format!("{base}{path}"));
227+ if let Some((u, p)) = auth {
228+ g = g.basic_auth(u, Some(p));
229+ }
230+ let got = async {
231+ let r = g.send().await?;
232+ if !r.status().is_success() {
233+ anyhow::bail!("{}", r.status());
234+ }
235+ Ok::<_, anyhow::Error>(r.bytes().await?)
236+ }
237+ .await;
238+ let bytes = match got {
239+ Ok(b) => b,
240+ Err(err) => {
241+ unreadable += 1;
242+ tracing::warn!(%path, error = %err, "文件取不回来,跳过");
243+ continue;
244+ }
245+ };
246+
247+ out.push(RemoteFile {
248+ external_key: format!("webdav://{host}{path}"),
249+ filename: path.rsplit('/').next().unwrap_or(&path).to_string(),
250+ bytes: bytes.to_vec(),
251+ last_modified: e.modified,
252+ });
253+ }
254+ if truncated {
255+ break;
256+ }
257+ }
258+ if unreadable > 0 {
259+ tracing::warn!(unreadable, "有文件没能取回");
260+ }
261+ Ok((out, truncated))
262+}
263+
264+/// 路径统一成 `/a/b` 的形状:前有斜杠、后无斜杠(根除外)。
265+fn normalize(p: &str) -> String {
266+ let t = p.trim();
267+ let t = t.strip_suffix('/').unwrap_or(t);
268+ if t.is_empty() {
269+ "/".into()
270+ } else if t.starts_with('/') {
271+ t.into()
272+ } else {
273+ format!("/{t}")
274+ }
275+}
276+
277+/// href 可能是绝对 URL 也可能只是路径——两种都合法,服务端各写各的。
278+fn strip_base(href: &str, base: &str) -> String {
279+ if let Some(rest) = href.strip_prefix(base) {
280+ return rest.to_string();
281+ }
282+ // 绝对但换了主机名(反代改写过):退回取它的 path
283+ if href.starts_with("http://") || href.starts_with("https://") {
284+ if let Ok(u) = reqwest::Url::parse(href) {
285+ return u.path().to_string();
286+ }
287+ }
288+ href.to_string()
289+}
290+
291+#[cfg(test)]
292+mod tests {
293+ use super::*;
294+
295+ /// **命名空间前缀是任意的。** 同一份响应换个前缀必须解出同样的东西,
296+ /// 否则换一台服务端就「同步成功,零个文件」——最难查的那种失败。
297+ #[test]
298+ fn any_namespace_prefix_parses_the_same() {
299+ let with_d = r#"<?xml version="1.0"?>
300+<D:multistatus xmlns:D="DAV:"><D:response>
301+ <D:href>/docs/a.txt</D:href>
302+ <D:propstat><D:prop>
303+ <D:getcontentlength>5</D:getcontentlength>
304+ <D:getlastmodified>Wed, 02 Sep 2026 15:04:05 GMT</D:getlastmodified>
305+ <D:resourcetype/>
306+ </D:prop></D:propstat>
307+</D:response></D:multistatus>"#;
308+ // 前缀换掉,命名空间声明本身不受影响(`xmlns:D="DAV:"` 里没有 `D:` 这个子串)
309+ let with_ns0 = with_d.replace("D:", "ns0:");
310+ let a = parse_multistatus(with_d).unwrap();
311+ let b = parse_multistatus(&with_ns0).unwrap();
312+ assert_eq!(a, b, "换个前缀就解不出来了");
313+ assert_eq!(a.len(), 1);
314+ assert_eq!(a[0].href, "/docs/a.txt");
315+ assert_eq!(a[0].len, 5);
316+ assert!(!a[0].is_dir);
317+ assert!(
318+ a[0].modified.is_some(),
319+ "getlastmodified 是 doc_time 的来源"
320+ );
321+ }
322+
323+ /// **目录判据是 `<collection/>`,而它通常是自闭合标签。**
324+ /// 只处理 `Event::Start` 的解析器会把每个目录都当成文件去 GET。
325+ #[test]
326+ fn a_self_closing_collection_is_still_a_directory() {
327+ let xml = r#"<multistatus xmlns="DAV:"><response>
328+ <href>/docs/</href>
329+ <propstat><prop><resourcetype><collection/></resourcetype></prop></propstat>
330+</response></multistatus>"#;
331+ let e = parse_multistatus(xml).unwrap();
332+ assert!(e[0].is_dir, "自闭合的 collection 没被认出来");
333+ }
334+
335+ /// href 是百分号转义过的,中文路径直接拼 URL 会 404。
336+ #[test]
337+ fn a_percent_encoded_href_is_decoded() {
338+ assert_eq!(
339+ percent_decode("/docs/%E4%B8%AD%E6%96%87.txt"),
340+ "/docs/中文.txt"
341+ );
342+ // 非法序列原样留着,不猜
343+ assert_eq!(percent_decode("/a%ZZb"), "/a%ZZb");
344+ }
345+
346+ /// 路径统一:前有斜杠、后无斜杠。两端不一致会让同一个目录被走两遍。
347+ #[test]
348+ fn paths_normalise_to_one_shape() {
349+ for (raw, want) in [
350+ ("docs", "/docs"),
351+ ("/docs/", "/docs"),
352+ ("/", "/"),
353+ ("", "/"),
354+ ] {
355+ assert_eq!(normalize(raw), want, "{raw}");
356+ }
357+ }
358+
359+ /// 真连一个 WebDAV 服务端。没有 `UTOPIA_DAV_TEST_URL` 就跳过。
360+ ///
361+ /// 用 rclone 起一个最省事,它和 Nextcloud 在 href 形态上不一样,
362+ /// 正好能验解析不挑服务端:
363+ /// ```text
364+ /// mkdir -p /tmp/dav/docs && echo hello > /tmp/dav/docs/a.txt
365+ /// rclone serve webdav /tmp/dav --addr 127.0.0.1:18081 --user u --pass p
366+ /// UTOPIA_DAV_TEST_URL=http://127.0.0.1:18081 UTOPIA_DAV_TEST_USER=u /// UTOPIA_DAV_TEST_PASS=p cargo test -p utopia-server webdav
367+ /// ```
368+ #[tokio::test]
369+ async fn it_reads_from_a_real_webdav_server() -> anyhow::Result<()> {
370+ let Ok(base) = std::env::var("UTOPIA_DAV_TEST_URL") else {
371+ eprintln!("跳过:未设 UTOPIA_DAV_TEST_URL");
372+ return Ok(());
373+ };
374+ let user = std::env::var("UTOPIA_DAV_TEST_USER").unwrap_or_default();
375+ let pass = std::env::var("UTOPIA_DAV_TEST_PASS").unwrap_or_default();
376+ let auth = (!user.is_empty()).then_some((user.as_str(), pass.as_str()));
377+
378+ let http = reqwest::Client::builder()
379+ .timeout(std::time::Duration::from_secs(30))
380+ .build()?;
381+ let (files, truncated) = fetch(&http, &base, "/docs", auth).await?;
382+ assert!(!truncated);
383+
384+ let a = files.iter().find(|f| f.filename == "a.txt").expect("a.txt");
385+ assert_eq!(a.bytes, b"hello from webdav");
386+ assert!(
387+ a.external_key.starts_with("webdav://"),
388+ "{}",
389+ a.external_key
390+ );
391+ assert!(a.last_modified.is_some());
392+ // 目录本身不该混进来
393+ assert!(files.iter().all(|f| !f.filename.is_empty()));
394+ Ok(())
395+ }
396+}
modified crates/utopia-store/src/graph.rs +65 −10
@@ -1119,7 +1119,7 @@
11191119 Ok(sqlx::query_as(
11201120 // **普遍程度从全量证据里数,不从积压里数。**
11211121 //
1122- // 下面那些 WHERE 把行集收窄到「还挂在兜底谓词上、还活着、宾语是实体」
1122+ // 下面那些 WHERE 把行集收窄到「还没有谓词、还活着、宾语是实体」
11231123 // ——那是**采纳要改写的东西**,`fact_count` 该这么数。但 `doc_count`
11241124 // 回答的是另一个问题:这个说法在语料里有多普遍。拿残渣去数它会系统性
11251125 // 偏低,而且越用越低——说法一旦被采纳、被谓词匹配接住、或被修正作废,
@@ -1231,10 +1231,29 @@
12311231 predicate_id: Uuid,
12321232 forms: &[String],
12331233 swap: bool,
1234-) -> AppResult<(Uuid, u32)> {
1234+) -> AppResult<Adopted> {
12351235 adopt(pool, kb_id, predicate_id, AdoptTargets::ByForm(forms), swap).await
12361236 }
12371237
1238+/// 一次采纳的账。`left_off` 必须往上传:改写了 20 条、留下 3 条,只报前半句是报喜不报忧。
1239+#[derive(Debug, Clone, Copy)]
1240+pub struct Adopted {
1241+ pub batch_id: Uuid,
1242+ /// 改写过去的条数
1243+ pub moved: u32,
1244+ /// 签名两边都对不上、**没有**挂上谓词的条数(#190)。它们照旧留在空谓词上,
1245+ /// 原文说法还在证据里——与抽取遇到同样情形的处置一致
1246+ pub left_off: u32,
1247+ /// 按签名对调了主宾的条数。
1248+ ///
1249+ /// **掰正不该静默。** 抽取那条路每掰一次就落一条 `direction_corrected`
1250+ /// 丢弃信号(#138 的原话是「绝不静默」:用可能错的声明驱动的自动动作,
1251+ /// 留痕才不属于 0001 判据 2 反对的那一类)。采纳走的是同一道判断,
1252+ /// 也该说出来自己动了几条,否则台账上只剩「改写了 N 条」,看不出其中
1253+ /// 有几条是被本体掉了个头的
1254+ pub corrected: u32,
1255+}
1256+
12381257 /// 要改写哪些事实,以及新行的宾语从哪来。
12391258 pub enum AdoptTargets<'a> {
12401259 /// 关系那一路:按表层说法去找,宾语原样搬走。
@@ -1243,8 +1262,8 @@
12431262 ///
12441263 /// **归一化必须在调用方做**:那套规则("2015" → 日期、"1,200" → 数字)
12451264 /// 住在抽取模块,store 够不着也不该够得着。更要紧的是它会**失败**——
1246- /// 一个换算不出来的值不该硬塞进一个日期属性里,那条事实宁可继续挂在
1247- /// 兜底谓词上。所以由调用方筛完再交回来。
1265+ /// 一个换算不出来的值不该硬塞进一个日期属性里,那条事实宁可继续没有
1266+ /// 谓词(原词还在证据里)。所以由调用方筛完再交回来。
12481267 WithValues(&'a [(Uuid, serde_json::Value)]),
12491268 }
12501269
@@ -1254,12 +1273,18 @@
12541273 predicate_id: Uuid,
12551274 targets: AdoptTargets<'_>,
12561275 swap: bool,
1257-) -> AppResult<(Uuid, u32)> {
1276+) -> AppResult<Adopted> {
12581277 let batch_id = Uuid::now_v7();
1278+ let nothing = Adopted {
1279+ batch_id,
1280+ moved: 0,
1281+ left_off: 0,
1282+ corrected: 0,
1283+ };
12591284 let targets: Vec<(Uuid, Uuid, Option<Uuid>, Option<serde_json::Value>)> = match targets {
12601285 AdoptTargets::ByForm(forms) => {
12611286 if forms.is_empty() {
1262- return Ok((batch_id, 0));
1287+ return Ok(nothing);
12631288 }
12641289 sqlx::query_as(
12651290 "SELECT f.id, f.subject_id, f.object_id, f.object_value
@@ -1283,7 +1308,7 @@
12831308 }
12841309 AdoptTargets::WithValues(items) => {
12851310 if items.is_empty() {
1286- return Ok((batch_id, 0));
1311+ return Ok(nothing);
12871312 }
12881313 // 主语要从库里读回来(调用方给的是 fact_id 与新值),顺带确认这些
12891314 // 事实还活着——挑选与采纳之间可能隔着一次重抽
@@ -1307,6 +1332,8 @@
13071332 };
13081333
13091334 let mut moved = 0u32;
1335+ let mut left_off = 0u32;
1336+ let mut corrected = 0u32;
13101337 for (old_id, subject_id, object_id, object_value) in targets {
13111338 // 被动形改写:主宾对调。字面值宾语的事实换不了(值不能当主语),
13121339 // 而 ByForm 那条查询本来就只取 object_id 非空的,所以这里只可能是实体宾语
@@ -1314,6 +1341,29 @@
13141341 (true, Some(o)) => (o, Some(subject_id)),
13151342 _ => (subject_id, object_id),
13161343 };
1344+ // **挂谓词之前过一遍签名**(#190)。抽取写入时按 domain 掰正方向或留空,
1345+ // 而采纳是第二条写谓词的路——从前直接把谓词挂回去,实测把违反率从 0 抬到
1346+ // 12.3%,全在包关系上。同一道判断(`ontology::judge_direction`),同样三种
1347+ // 结果:合就挂,主语不合宾语合就对调着挂,都不合就**不挂**——那条事实留在
1348+ // 空谓词上,原文说法还在证据里,与抽取遇到同样情形的处置一致
1349+ let (subject_id, object_id) = match object_id {
1350+ Some(o) => {
1351+ match crate::ontology::judge_direction(pool, predicate_id, subject_id, o).await? {
1352+ crate::ontology::Fit::Swap => {
1353+ corrected += 1;
1354+ (o, Some(subject_id))
1355+ }
1356+ crate::ontology::Fit::Neither => {
1357+ left_off += 1;
1358+ continue;
1359+ }
1360+ crate::ontology::Fit::Keep | crate::ontology::Fit::Unchecked => {
1361+ (subject_id, Some(o))
1362+ }
1363+ }
1364+ }
1365+ None => (subject_id, None),
1366+ };
13171367 let mut tx = pool.begin().await?;
13181368 // 目标断言可能已存在(同主宾已有一条真关系):那就并进去,别造重复。
13191369 //
@@ -1403,7 +1453,12 @@
14031453 tx.commit().await?;
14041454 moved += 1;
14051455 }
1406- Ok((batch_id, moved))
1456+ Ok(Adopted {
1457+ batch_id,
1458+ moved,
1459+ left_off,
1460+ corrected,
1461+ })
14071462 }
14081463
14091464 /// 撤销一次采纳:新写的行作废、旧行复活。
@@ -1457,7 +1512,7 @@
14571512 Ok(reverted)
14581513 }
14591514
1460-/// 词表外的**字面值**说法:还挂在兜底谓词上、宾语是值而不是实体的那些。
1515+/// 词表外的**字面值**说法:还没有谓词、宾语是值而不是实体的那些。
14611516 ///
14621517 /// 跟 [`proposed_predicates`] 互补,两边用 `object_id` 是否为空严格分开。
14631518 /// 混在一起提案就会把 `founding_date` 提成一条关系,而那正是这条路要修掉的。
@@ -1551,7 +1606,7 @@
15511606 kb_id: Uuid,
15521607 attribute_id: Uuid,
15531608 rewrites: &[(Uuid, serde_json::Value)],
1554-) -> AppResult<(Uuid, u32)> {
1609+) -> AppResult<Adopted> {
15551610 // 属性那一路没有对调可言:宾语是字面值,值不能当主语
15561611 adopt(
15571612 pool,
modified crates/utopia-store/src/jobs.rs +62 −19
@@ -1,5 +1,6 @@
11 //! 任务队列:Postgres `FOR UPDATE SKIP LOCKED` 消费。
2-//! worker 与 API 同进程(tokio task),失败按 30s * attempts² 退避重试。
2+//! worker 与 API 同进程(tokio task),失败按 30s * attempts² 退避重试——
3+//! 除非处理器把它标成了 `utopia_core::Terminal`,那种一次就到此为止(见 [`retry_delay`])。
34 //! 并发消费:调度循环按"运行中 < 目标数"续派,任务在独立 task 执行;
45 //! 目标数经 AtomicUsize 热读——系统设置里改并发即时生效,无需重启。
56
@@ -61,29 +62,51 @@
6162 Ok(())
6263 }
6364
64-async fn mark_failed(pool: &PgPool, job: &Job, err: &str) -> AppResult<()> {
65- if job.attempts >= job.max_attempts {
65+/// 下一次重试等多久;`None` = 到此为止。
66+///
67+/// 两个理由到此为止:**次数用完了**,或者**处理器说了这次不会因为重试而变好**
68+/// (`utopia_core::Terminal`,见 issue #195)。后者以前不存在,于是余额耗尽的
69+/// 任务照样把三次退避走完——七分钟里余额不会自己长回来,那三次只是把同一句
70+/// 错误重说三遍,还把运维该看见的「失败」推迟了七分钟。
71+///
72+/// 限流相反,它正是这套退避的服务对象:配额会自己恢复。#176 把两类分开就是
73+/// 为了让它们各走各的路,而重试策略当时没跟上。
74+///
75+/// 抽成纯函数是为了能测——决定在这里,写库只是把决定落下去。
76+fn retry_delay(attempts: i32, max_attempts: i32, terminal: bool) -> Option<i64> {
77+ if terminal || attempts >= max_attempts {
78+ return None;
79+ }
80+ Some(30i64 * i64::from(attempts) * i64::from(attempts))
81+}
82+
83+async fn mark_failed(pool: &PgPool, job: &Job, err: &anyhow::Error) -> AppResult<()> {
84+ let text = format!("{err:#}");
85+ let Some(backoff_secs) = retry_delay(
86+ job.attempts,
87+ job.max_attempts,
88+ utopia_core::is_terminal(err),
89+ ) else {
6690 sqlx::query(
6791 "UPDATE jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE id = $1",
6892 )
6993 .bind(job.id)
70- .bind(err)
71- .execute(pool)
72- .await?;
73- } else {
74- let backoff_secs = 30i64 * i64::from(job.attempts) * i64::from(job.attempts);
75- sqlx::query(
76- "UPDATE jobs SET status = 'queued', last_error = $2,
77- run_at = now() + make_interval(secs => $3::float8),
78- updated_at = now()
79- WHERE id = $1",
80- )
81- .bind(job.id)
82- .bind(err)
83- .bind(backoff_secs as f64)
94+ .bind(&text)
8495 .execute(pool)
8596 .await?;
86- }
97+ return Ok(());
98+ };
99+ sqlx::query(
100+ "UPDATE jobs SET status = 'queued', last_error = $2,
101+ run_at = now() + make_interval(secs => $3::float8),
102+ updated_at = now()
103+ WHERE id = $1",
104+ )
105+ .bind(job.id)
106+ .bind(&text)
107+ .bind(backoff_secs as f64)
108+ .execute(pool)
109+ .await?;
87110 Ok(())
88111 }
89112
@@ -137,7 +160,7 @@
137160 Ok(()) => mark_done(&pool, job.id).await,
138161 Err(e) => {
139162 tracing::warn!(job_id = job.id, kind = %job.kind, error = %e, "任务执行失败");
140- mark_failed(&pool, &job, &e.to_string()).await
163+ mark_failed(&pool, &job, &e).await
141164 }
142165 };
143166 if let Err(e) = outcome {
@@ -154,3 +177,23 @@
154177 }
155178 }
156179 }
180+
181+#[cfg(test)]
182+mod tests {
183+ use super::retry_delay;
184+
185+ /// 退避照旧:30s、120s、270s,第三次之后放弃。
186+ #[test]
187+ fn an_ordinary_failure_backs_off_and_then_gives_up() {
188+ assert_eq!(retry_delay(1, 3, false), Some(30));
189+ assert_eq!(retry_delay(2, 3, false), Some(120));
190+ assert_eq!(retry_delay(3, 3, false), None);
191+ }
192+
193+ /// 标成没救的**第一次就到此为止**——那三次退避加起来是七分钟,
194+ /// 而余额不会在七分钟里自己长回来(#195)。
195+ #[test]
196+ fn a_terminal_failure_does_not_spend_the_budget() {
197+ assert_eq!(retry_delay(1, 3, true), None);
198+ }
199+}
modified crates/utopia-store/src/lib.rs +1 −0
@@ -19,6 +19,7 @@
1919 pub mod model_limits;
2020 pub mod ontology;
2121 pub mod palette;
22+pub mod pending;
2223 pub mod reasoning;
2324 pub mod resolution;
2425 pub mod review;
modified crates/utopia-store/src/ontology.rs +36 −1
@@ -604,7 +604,7 @@
604604 // 重新顶成一个待处理信号"。那个理由针对的是**呈现**,用的手段却是
605605 // **停止计数**——两件事被绑在一起了,代价是一次点击变成永久失明:
606606 // 第一篇里出现一次的说法被忽略掉,后面二十篇都在用它,计数仍停在 1,
607- // 谁也不知道当初那个判断已经不成立,那批事实永远留在兜底谓词上。
607+ // 谁也不知道当初那个判断已经不成立,那批事实永远没有谓词。
608608 //
609609 // 用户是对**当时看得见的证据**做的判断,不是对所有时间。所以计数照记,
610610 // 抑制交给读取侧:`list_misses` 仍然只返回未忽略的,提案与自动扩本体
@@ -1768,6 +1768,41 @@
17681768 Ok((declared > 0).then_some(ok > 0))
17691769 }
17701770
1771+/// 一条 (主语, 谓词, 宾语) 对着谓词的 domain 签名该怎么落。
1772+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1773+pub enum Fit {
1774+ /// 谓词没声明 domain——没有判据,照原样落
1775+ Unchecked,
1776+ /// 主语符合
1777+ Keep,
1778+ /// 主语不符合、宾语符合:按签名对调主宾
1779+ Swap,
1780+ /// 两边都不符合:这个关系不适用于这对实体,谓词该留空
1781+ Neither,
1782+}
1783+
1784+/// **三条写谓词的路共用的那一道判断**(#190 / #196):抽取落新事实、采纳把谓词
1785+/// 挂回旧事实、合并换掉主语——从前只有抽取查,另外两条各自绕了过去。
1786+///
1787+/// 判据刻意窄(0012):只看 domain,只在**主语违反且宾语符合**时对调,两边都对不上
1788+/// 就留空谓词。参数顺序不是关于世界的断言,是这个 key 的编码约定,所以本体在这一处
1789+/// 是执法的;哪些类型能参与仍是引导,不在这里裁。
1790+pub async fn judge_direction(
1791+ pool: &PgPool,
1792+ relation_type_id: Uuid,
1793+ subject_id: Uuid,
1794+ object_id: Uuid,
1795+) -> AppResult<Fit> {
1796+ match entity_fits_domain(pool, relation_type_id, subject_id).await? {
1797+ None => Ok(Fit::Unchecked),
1798+ Some(true) => Ok(Fit::Keep),
1799+ Some(false) => match entity_fits_domain(pool, relation_type_id, object_id).await? {
1800+ Some(true) => Ok(Fit::Swap),
1801+ _ => Ok(Fit::Neither),
1802+ },
1803+ }
1804+}
1805+
17711806 /// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。
17721807 ///
17731808 /// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有——
added crates/utopia-store/src/pending.rs +350 −0
@@ -0,0 +1,350 @@
1+//! 等人点头的事实(见 `docs/decisions/0015`,表在 `migrations/0018`)。
2+//!
3+//! 一句记忆抽出来的三元组先落这里,**不进 `facts`**:不上图、不参与检索、
4+//! 不进推理。人在对话里或 Review 页看见「原句在上、三元组在下」之后点头,
5+//! 它才经与抽取相同的那条路(`insert_fact` + 证据 + 时态对账)进账本。
6+//!
7+//! **为什么另一张表而不是 `facts` 加一列**:五十多处查询按 `invalidated_at IS NULL`
8+//! 捞活事实,逐个补过滤漏一处就有一条没人点头的事实混进图里——而这张表存在的
9+//! 全部理由就是防这件事。分开之后忘了读它的后果是「看不见待确认队列」,
10+//! 方向对了。0013 的 `derived_facts` 是同一个判断。
11+//!
12+//! **只拦交互式的单条写入。** 批量摄入仍旧乐观写入 + 事后审阅——那条路不经这里。
13+
14+use sqlx::PgPool;
15+use utopia_core::models::PendingFactView;
16+use utopia_core::{AppError, AppResult};
17+use uuid::Uuid;
18+
19+use crate::graph::Validity;
20+
21+/// 抽取器交过来的一条提议。字段与 `insert_fact` / `insert_value_fact` 对齐,
22+/// 多出 `proposed_predicate`(模型原话)、`chunk_id`(那句记忆)、`proposed_by`(谁说的)。
23+pub struct Proposal<'a> {
24+ pub kb_id: Uuid,
25+ pub subject_id: Uuid,
26+ /// None = 本体里没有对应的关系(0010)。**人要看见的正是这个空**
27+ pub predicate_id: Option<Uuid>,
28+ pub object_id: Option<Uuid>,
29+ pub object_value: Option<&'a serde_json::Value>,
30+ pub proposed_predicate: Option<&'a str>,
31+ pub validity: Validity<'a>,
32+ pub confidence: f32,
33+ pub chunk_id: Uuid,
34+ pub proposed_by: Option<Uuid>,
35+}
36+
37+/// 提议的去向。三种「没提」都不是错误——重抽一句记忆会再次算出同样的三元组,
38+/// 不挡住就等于每抽一次都把人的决定抹掉一次。
39+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40+pub enum Outcome {
41+ Proposed(Uuid),
42+ /// 图上已经有一条一样的活事实——不必再问
43+ AlreadyAsserted,
44+ /// 已经在队列里等着
45+ AlreadyPending,
46+ /// 人拒绝过这个三元组(`rejected_facts`)
47+ Rejected,
48+}
49+
50+pub async fn propose(pool: &PgPool, p: Proposal<'_>) -> AppResult<Outcome> {
51+ let asserted: Option<(i32,)> = sqlx::query_as(
52+ "SELECT 1 FROM facts
53+ WHERE kb_id = $1 AND subject_id = $2
54+ AND predicate_id IS NOT DISTINCT FROM $3
55+ AND object_id IS NOT DISTINCT FROM $4
56+ AND object_value IS NOT DISTINCT FROM $5
57+ AND invalidated_at IS NULL
58+ LIMIT 1",
59+ )
60+ .bind(p.kb_id)
61+ .bind(p.subject_id)
62+ .bind(p.predicate_id)
63+ .bind(p.object_id)
64+ .bind(p.object_value)
65+ .fetch_optional(pool)
66+ .await?;
67+ if asserted.is_some() {
68+ return Ok(Outcome::AlreadyAsserted);
69+ }
70+ let pending: Option<(i32,)> = sqlx::query_as(
71+ "SELECT 1 FROM pending_facts
72+ WHERE kb_id = $1 AND subject_id = $2
73+ AND predicate_id IS NOT DISTINCT FROM $3
74+ AND object_id IS NOT DISTINCT FROM $4
75+ AND object_value IS NOT DISTINCT FROM $5
76+ LIMIT 1",
77+ )
78+ .bind(p.kb_id)
79+ .bind(p.subject_id)
80+ .bind(p.predicate_id)
81+ .bind(p.object_id)
82+ .bind(p.object_value)
83+ .fetch_optional(pool)
84+ .await?;
85+ if pending.is_some() {
86+ return Ok(Outcome::AlreadyPending);
87+ }
88+ // 拒绝记录只按 (主语, 谓词, 宾语实体) 查。**字面值事实不查**:`rejected_facts`
89+ // 没有 object_value 列,按 (主语, 谓词) 挡会把「薪水 28000 被拒」扩大成
90+ // 「薪水这个属性永远不再提」。宁可多问一次,不替人拒掉一个新值
91+ if let Some(object_id) = p.object_id {
92+ let rejected: Option<(i32,)> = sqlx::query_as(
93+ "SELECT 1 FROM rejected_facts
94+ WHERE kb_id = $1 AND subject_id = $2
95+ AND predicate_id IS NOT DISTINCT FROM $3
96+ AND object_id = $4
97+ LIMIT 1",
98+ )
99+ .bind(p.kb_id)
100+ .bind(p.subject_id)
101+ .bind(p.predicate_id)
102+ .bind(object_id)
103+ .fetch_optional(pool)
104+ .await?;
105+ if rejected.is_some() {
106+ return Ok(Outcome::Rejected);
107+ }
108+ }
109+ let id = Uuid::now_v7();
110+ sqlx::query(
111+ "INSERT INTO pending_facts
112+ (id, kb_id, subject_id, predicate_id, object_id, object_value, proposed_predicate,
113+ valid_from, valid_from_precision, valid_to, valid_to_precision,
114+ confidence, chunk_id, proposed_by)
115+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
116+ )
117+ .bind(id)
118+ .bind(p.kb_id)
119+ .bind(p.subject_id)
120+ .bind(p.predicate_id)
121+ .bind(p.object_id)
122+ .bind(p.object_value)
123+ .bind(p.proposed_predicate)
124+ .bind(p.validity.from)
125+ .bind(p.validity.from_precision)
126+ .bind(p.validity.to)
127+ .bind(p.validity.to_precision)
128+ .bind(p.confidence)
129+ .bind(p.chunk_id)
130+ .bind(p.proposed_by)
131+ .execute(pool)
132+ .await?;
133+ Ok(Outcome::Proposed(id))
134+}
135+
136+/// 给人看的一条待确认项:`utopia_core::models::PendingFactView`。
137+const VIEW_SELECT: &str = "\
138+ SELECT p.id, p.subject_id, s.canonical_name AS subject_name,
139+ p.predicate_id, r.label AS predicate_label, p.proposed_predicate,
140+ p.object_id, o.canonical_name AS object_name, p.object_value,
141+ p.valid_from, p.valid_from_precision, p.valid_to, p.valid_to_precision,
142+ p.confidence, p.chunk_id, c.text AS quote,
143+ p.proposed_by, u.display_name AS proposed_by_name, p.created_at
144+ FROM pending_facts p
145+ JOIN entities s ON s.id = p.subject_id
146+ LEFT JOIN relation_types r ON r.id = p.predicate_id
147+ LEFT JOIN entities o ON o.id = p.object_id
148+ JOIN chunks c ON c.id = p.chunk_id
149+ LEFT JOIN users u ON u.id = p.proposed_by";
150+
151+pub async fn list(
152+ pool: &PgPool,
153+ kb_id: Uuid,
154+ limit: i64,
155+ offset: i64,
156+) -> AppResult<Vec<PendingFactView>> {
157+ Ok(sqlx::query_as(&format!(
158+ "{VIEW_SELECT} WHERE p.kb_id = $1 ORDER BY p.created_at DESC LIMIT $2 OFFSET $3"
159+ ))
160+ .bind(kb_id)
161+ .bind(limit)
162+ .bind(offset)
163+ .fetch_all(pool)
164+ .await?)
165+}
166+
167+/// 一句记忆抽出的全部待确认项——对话里那张卡片按这个取。
168+pub async fn for_chunk(
169+ pool: &PgPool,
170+ kb_id: Uuid,
171+ chunk_id: Uuid,
172+) -> AppResult<Vec<PendingFactView>> {
173+ Ok(sqlx::query_as(&format!(
174+ "{VIEW_SELECT} WHERE p.kb_id = $1 AND p.chunk_id = $2 ORDER BY p.created_at"
175+ ))
176+ .bind(kb_id)
177+ .bind(chunk_id)
178+ .fetch_all(pool)
179+ .await?)
180+}
181+
182+async fn get(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<PendingFactView> {
183+ sqlx::query_as(&format!("{VIEW_SELECT} WHERE p.kb_id = $1 AND p.id = $2"))
184+ .bind(kb_id)
185+ .bind(id)
186+ .fetch_optional(pool)
187+ .await?
188+ .ok_or(AppError::NotFound)
189+}
190+
191+/// 决策台账要的自包含快照:行删了之后台账上还读得出当时确认或拒绝的是什么。
192+fn snapshot(v: &PendingFactView) -> serde_json::Value {
193+ serde_json::json!({
194+ "subject": v.subject_name,
195+ "predicate": v.predicate_label,
196+ "proposed_predicate": v.proposed_predicate,
197+ "object": v.object_name,
198+ "object_value": v.object_value,
199+ "valid_from": v.valid_from,
200+ "valid_to": v.valid_to,
201+ "confidence": v.confidence,
202+ "quote": v.quote,
203+ "proposed_by": v.proposed_by_name,
204+ })
205+}
206+
207+pub struct Confirmed {
208+ pub fact_id: Uuid,
209+ /// false = 图上已有同一条活事实,这次只补了证据
210+ pub created: bool,
211+ /// 时态对账拿不准、进了 `fact_conflicts` 的条数
212+ pub conflicts: u32,
213+ pub snapshot: serde_json::Value,
214+}
215+
216+/// 人点头:按抽取那条路进账本——落事实、挂证据、时态对账——然后从队列里拿掉。
217+///
218+/// **置信度不动。** 人的态度不用浮点数表达(0011 的教训),它在审计台账里。
219+///
220+/// 不包事务:`insert_fact` 按 (主语, 谓词, 宾语) 对活事实去重,中途断掉再点一次
221+/// 只会补证据、不会落第二条,删行在最后——幂等靡有余悸。
222+pub async fn confirm(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<Confirmed> {
223+ let v = get(pool, kb_id, id).await?;
224+ let validity = Validity {
225+ from: v.valid_from,
226+ from_precision: v.valid_from_precision.as_deref(),
227+ to: v.valid_to,
228+ to_precision: v.valid_to_precision.as_deref(),
229+ };
230+ let (fact_id, created) = match (v.object_id, v.object_value.as_ref()) {
231+ (Some(object_id), _) => {
232+ crate::graph::insert_fact(
233+ pool,
234+ kb_id,
235+ v.subject_id,
236+ v.predicate_id,
237+ object_id,
238+ validity,
239+ v.confidence,
240+ )
241+ .await?
242+ }
243+ (None, Some(value)) => {
244+ crate::graph::insert_value_fact(
245+ pool,
246+ kb_id,
247+ v.subject_id,
248+ v.predicate_id,
249+ value,
250+ validity,
251+ v.confidence,
252+ )
253+ .await?
254+ }
255+ (None, None) => {
256+ return Err(AppError::invalid(
257+ "pending_fact_has_no_object",
258+ "a pending fact must have an object entity or a literal value",
259+ ))
260+ }
261+ };
262+ // 证据指回那句记忆。引句就是整句——一条 episode 本来就只有一句
263+ crate::graph::add_evidence(
264+ pool,
265+ fact_id,
266+ v.chunk_id,
267+ Some(&v.quote),
268+ v.proposed_predicate.as_deref(),
269+ )
270+ .await?;
271+
272+ // 与抽取相同的时态对账:带唯一性约束的状态关系,新事实闭合旧事实。
273+ // 这正是记忆该有的行为——「Mira 交给 Devin 了」说完,Mira 那条就该闭合
274+ let mut conflicts = 0u32;
275+ if created {
276+ if let Some(pid) = v.predicate_id {
277+ let meta: Option<(bool, bool, String)> = sqlx::query_as(
278+ "SELECT functional, inverse_functional, temporal FROM relation_types WHERE id = $1",
279+ )
280+ .bind(pid)
281+ .fetch_optional(pool)
282+ .await?;
283+ if let Some((functional, inverse_functional, temporal)) = meta {
284+ if temporal == "state" {
285+ let mut directions = Vec::new();
286+ if functional {
287+ directions.push(crate::temporal::Uniqueness::SubjectSide);
288+ }
289+ // 宾语侧唯一只对实体宾语有意义;字面值没有「谁被指着」
290+ if inverse_functional && v.object_id.is_some() {
291+ directions.push(crate::temporal::Uniqueness::ObjectSide);
292+ }
293+ for dir in directions {
294+ let report = crate::temporal::reconcile_new_fact(
295+ pool,
296+ kb_id,
297+ fact_id,
298+ v.subject_id,
299+ pid,
300+ v.object_id,
301+ v.object_value.as_ref(),
302+ dir,
303+ validity,
304+ v.confidence,
305+ )
306+ .await?;
307+ conflicts += report.conflicts;
308+ }
309+ }
310+ }
311+ }
312+ }
313+ sqlx::query("DELETE FROM pending_facts WHERE id = $1")
314+ .bind(id)
315+ .execute(pool)
316+ .await?;
317+ Ok(Confirmed {
318+ fact_id,
319+ created,
320+ conflicts,
321+ snapshot: snapshot(&v),
322+ })
323+}
324+
325+/// 人拒绝:记进 `rejected_facts`(下一轮重抽先查它),从队列里拿掉。
326+/// 那句记忆本身留着——人确实说过那句话,只是没抽出可用的事实。
327+pub async fn reject(
328+ pool: &PgPool,
329+ kb_id: Uuid,
330+ id: Uuid,
331+ rejected_by: Option<Uuid>,
332+) -> AppResult<serde_json::Value> {
333+ let v = get(pool, kb_id, id).await?;
334+ sqlx::query(
335+ "INSERT INTO rejected_facts (kb_id, subject_id, predicate_id, object_id, rejected_by)
336+ VALUES ($1, $2, $3, $4, $5)",
337+ )
338+ .bind(kb_id)
339+ .bind(v.subject_id)
340+ .bind(v.predicate_id)
341+ .bind(v.object_id)
342+ .bind(rejected_by)
343+ .execute(pool)
344+ .await?;
345+ sqlx::query("DELETE FROM pending_facts WHERE id = $1")
346+ .bind(id)
347+ .execute(pool)
348+ .await?;
349+ Ok(snapshot(&v))
350+}
modified crates/utopia-store/src/reasoning.rs +91 −2
@@ -19,7 +19,7 @@
1919 type RuleKind = &'static str;
2020 use utopia_core::AppResult;
2121 use utopia_reason::derive::TimedEdge;
22-use utopia_reason::{check, Axioms, Edge, Violation};
22+use utopia_reason::{check, Axioms, Edge, Kind, Violation};
2323 use uuid::Uuid;
2424
2525 /// 一次检查的产出,给调用方写审计与告诉用户。
@@ -148,11 +148,100 @@
148148 Ok(map)
149149 }
150150
151+/// 主语不在谓词声明的 domain 里、或宾语不在 range 里的活事实(#190 / #196)。
152+///
153+/// 这是签名检查在**账本层**的那一半:抽取与采纳在写入时按 `ontology::judge_direction`
154+/// 掰正或留空,但合并会换掉主语、本体会事后改 domain,写入时的守卫挡不住写入之后
155+/// 的改动。所以这里对着库量一遍,任何一条路写反了都在 Review 里看得见。
156+///
157+/// **没有类型的实体不算**:它没有类型可比,「不知道」不是「不符合」——按 0009,
158+/// 未分类是一种诚实的状态,不该因此被报成矛盾。声明了 domain / range 的谓词才查,
159+/// 与其它四类同一条纪律:没有公理就没有判据。
160+///
161+/// `only` 给了就只看这些事实(合并之后对搬动过的那几条立刻查);None 是全量。
162+pub async fn signature_breaks(
163+ pool: &PgPool,
164+ kb_id: Uuid,
165+ only: Option<&[Uuid]>,
166+) -> AppResult<Vec<Uuid>> {
167+ let rows: Vec<(Uuid,)> = sqlx::query_as(
168+ "WITH RECURSIVE anc(type_id, anc_id) AS (
169+ SELECT id, id FROM entity_types WHERE kb_id = $1
170+ UNION
171+ SELECT a.type_id, p.parent_id
172+ FROM anc a JOIN entity_type_parents p ON p.child_id = a.anc_id
173+ )
174+ SELECT f.id
175+ FROM facts f
176+ JOIN relation_types r ON r.id = f.predicate_id
177+ JOIN entities s ON s.id = f.subject_id
178+ JOIN entities o ON o.id = f.object_id
179+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
180+ AND ($2::uuid[] IS NULL OR f.id = ANY($2))
181+ AND (
182+ (s.type_id IS NOT NULL
183+ AND EXISTS (SELECT 1 FROM relation_type_domains d WHERE d.relation_type_id = r.id)
184+ AND NOT EXISTS (SELECT 1 FROM relation_type_domains d
185+ JOIN anc a ON a.anc_id = d.entity_type_id
186+ WHERE d.relation_type_id = r.id AND a.type_id = s.type_id))
187+ OR
188+ (o.type_id IS NOT NULL
189+ AND EXISTS (SELECT 1 FROM relation_type_ranges g WHERE g.relation_type_id = r.id)
190+ AND NOT EXISTS (SELECT 1 FROM relation_type_ranges g
191+ JOIN anc a ON a.anc_id = g.entity_type_id
192+ WHERE g.relation_type_id = r.id AND a.type_id = o.type_id))
193+ )
194+ ORDER BY f.recorded_at",
195+ )
196+ .bind(kb_id)
197+ .bind(only)
198+ .fetch_all(pool)
199+ .await?;
200+ Ok(rows.into_iter().map(|(id,)| id).collect())
201+}
202+
203+/// 把签名违规落进 `axiom_violations`(kind = `signature`,left 与 right 同一条事实)。
204+/// 幂等:同一条事实重复报不重复入库。返回新插入的条数。
205+pub async fn record_signature_breaks(
206+ pool: &PgPool,
207+ kb_id: Uuid,
208+ facts: &[Uuid],
209+) -> AppResult<usize> {
210+ let mut inserted = 0usize;
211+ for fact in facts {
212+ let id: Option<(Uuid,)> = sqlx::query_as(
213+ "INSERT INTO axiom_violations (id, kb_id, kind, left_fact, right_fact)
214+ VALUES ($1, $2, 'signature', $3, $3)
215+ ON CONFLICT (kb_id, kind, left_fact, right_fact) DO NOTHING
216+ RETURNING id",
217+ )
218+ .bind(Uuid::now_v7())
219+ .bind(kb_id)
220+ .bind(fact)
221+ .fetch_optional(pool)
222+ .await?;
223+ if id.is_some() {
224+ inserted += 1;
225+ }
226+ }
227+ Ok(inserted)
228+}
229+
151230 /// 跑一遍检查,把结果落库。
152231 pub async fn run(pool: &PgPool, kb_id: Uuid) -> AppResult<Report> {
153232 let edges = edges(pool, kb_id).await?;
154233 let axioms = axioms(pool, kb_id).await?;
155- let violations = check(&edges, &axioms);
234+ let mut violations = check(&edges, &axioms);
235+ // 第五类不在纯逻辑引擎里:它要看实体的类型与谓词的 domain / range,那是库里的
236+ // 东西。算出来后与其它四类走同一条落库与清陈规矩
237+ for fact in signature_breaks(pool, kb_id, None).await? {
238+ violations.push(Violation {
239+ kind: Kind::Signature,
240+ left: fact,
241+ right: fact,
242+ path: Vec::new(),
243+ });
244+ }
156245
157246 let mut report = Report {
158247 edges: edges.len(),
modified crates/utopia-store/src/resolution.rs +16 −1
@@ -1,4 +1,4 @@
1-//! 实体消解 v2:同名≠同人(设计见 DESIGN.md §4 实体消解 v2)。
1+//! 实体消解 v2:同名≠同人(流程图与三次实测修洞见 `docs/pipeline.md` 第二节)。
22 //!
33 //! 漏斗:名字候选召回(免费,含泛用后缀词干互推)→ 画像向量相似度分层(毫秒,复用摄入阶段的 chunk embedding)
44 //! → 灰区新建实体 + 疑似重复审核项(宁分勿合),LLM 攒批裁决在独立后台任务里跑,
@@ -1308,6 +1308,21 @@
13081308 .chain(moved_object.iter())
13091309 .copied()
13101310 .collect();
1311+
1312+ // **合并是第三条改写事实的路**(#196):换掉主语或宾语,就可能把一条合法事实
1313+ // 变成签名违规——抽取写入时掰正过的方向,合并一次就能再反回去。这里不掰、不改,
1314+ // 只报:对搬动过的事实查一遍 domain / range,违反的进 `axiom_violations`
1315+ //(kind = signature),与其它公理违规同一个队列、同样三个出路。
1316+ // 放在事务之后:目标实体的类型在事务里刚调和过,提交了才看得见
1317+ match crate::reasoning::signature_breaks(pool, kb_id, Some(&moved_all)).await {
1318+ Ok(broken) if !broken.is_empty() => {
1319+ if let Err(e) = crate::reasoning::record_signature_breaks(pool, kb_id, &broken).await {
1320+ tracing::warn!(%kb_id, error = %e, "合并后的签名违规没能入库");
1321+ }
1322+ }
1323+ Ok(_) => {}
1324+ Err(e) => tracing::warn!(%kb_id, error = %e, "合并后的签名检查失败"),
1325+ }
13111326 let report = crate::temporal::reconcile_moved_facts(pool, kb_id, &moved_all).await?;
13121327 if !report.corrected.is_empty() {
13131328 sqlx::query("UPDATE entity_merges SET temporal_corrections = $2 WHERE id = $1")
modified crates/utopia-store/src/review.rs +1 −0
@@ -22,6 +22,7 @@
2222 pub async fn counts(pool: &PgPool, kb_id: Uuid) -> AppResult<ReviewCounts> {
2323 Ok(sqlx::query_as(
2424 "SELECT
25+ (SELECT count(*) FROM pending_facts WHERE kb_id = $1) AS pending,
2526 (SELECT count(*) FROM resolution_reviews
2627 WHERE kb_id = $1 AND status = 'pending') AS duplicates,
2728 (SELECT count(*) FROM fact_conflicts
added crates/utopia-store/tests/a_fact_awaits_a_nod.rs +204 −0
@@ -0,0 +1,204 @@
1+//! 记忆抽出的事实先等人点头(`docs/decisions/0015`,表在迁移 0018)——打在真库上。
2+//!
3+//! 守的是那次实测的反面:对话里说「Acme 把总部搬到了深圳」,图上**不能**立刻多出
4+//! 一条活边。提议只进 `pending_facts`;人点头之后它才按抽取那条路进账本(事实 +
5+//! 证据指回那句话 + 时态对账);摇头之后同一个三元组不再被提。
6+
7+use sqlx::PgPool;
8+use uuid::Uuid;
9+
10+struct Fixture {
11+ /// 夹具建的 org,收尾时从它删起(级联)
12+ org: Uuid,
13+ kb: Uuid,
14+ acme: Uuid,
15+ shenzhen: Uuid,
16+ shanghai: Uuid,
17+ hq: Uuid,
18+ chunk: Uuid,
19+}
20+
21+async fn fixture(pool: &PgPool) -> anyhow::Result<Fixture> {
22+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
23+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'nod-test')")
24+ .bind(org)
25+ .execute(pool)
26+ .await?;
27+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'nod-test')")
28+ .bind(ws)
29+ .bind(org)
30+ .execute(pool)
31+ .await?;
32+ sqlx::query("INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'nod-test')")
33+ .bind(kb)
34+ .bind(ws)
35+ .execute(pool)
36+ .await?;
37+ // 总部只有一个:functional 让时态对账有事可做
38+ let hq = Uuid::now_v7();
39+ sqlx::query(
40+ "INSERT INTO relation_types (id, kb_id, key, label, functional)
41+ VALUES ($1, $2, 'headquartered_in', 'headquartered in', TRUE)",
42+ )
43+ .bind(hq)
44+ .bind(kb)
45+ .execute(pool)
46+ .await?;
47+ let (acme, shenzhen, shanghai) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
48+ for (id, name) in [
49+ (acme, "Acme"),
50+ (shenzhen, "Shenzhen"),
51+ (shanghai, "Shanghai"),
52+ ] {
53+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, $3)")
54+ .bind(id)
55+ .bind(kb)
56+ .bind(name)
57+ .execute(pool)
58+ .await?;
59+ }
60+ // 那句记忆,走产品自己的路落成 chunk
61+ let (_doc, chunk) = utopia_store::memory::append_episode(
62+ pool,
63+ kb,
64+ "Acme moved its headquarters to Shenzhen on 2026-03-15.",
65+ chrono::Utc::now(),
66+ )
67+ .await?;
68+ Ok(Fixture {
69+ org,
70+ kb,
71+ acme,
72+ shenzhen,
73+ shanghai,
74+ hq,
75+ chunk,
76+ })
77+}
78+
79+fn day(s: &str) -> chrono::DateTime<chrono::Utc> {
80+ chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
81+ .unwrap()
82+ .and_hms_opt(0, 0, 0)
83+ .unwrap()
84+ .and_utc()
85+}
86+
87+async fn live_facts(pool: &PgPool, kb: Uuid) -> anyhow::Result<i64> {
88+ let (n,): (i64,) =
89+ sqlx::query_as("SELECT count(*) FROM facts WHERE kb_id = $1 AND invalidated_at IS NULL")
90+ .bind(kb)
91+ .fetch_one(pool)
92+ .await?;
93+ Ok(n)
94+}
95+
96+#[tokio::test]
97+async fn a_remembered_fact_waits_for_a_nod() -> anyhow::Result<()> {
98+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
99+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
100+ return Ok(());
101+ };
102+ let pool = PgPool::connect(&url).await?;
103+ let f = fixture(&pool).await?;
104+
105+ let run = async {
106+ use utopia_store::pending::{self, Outcome, Proposal};
107+ let propose = |object: Uuid, from: &'static str| {
108+ pending::propose(
109+ &pool,
110+ Proposal {
111+ kb_id: f.kb,
112+ subject_id: f.acme,
113+ predicate_id: Some(f.hq),
114+ object_id: Some(object),
115+ object_value: None,
116+ proposed_predicate: Some("moved headquarters to"),
117+ validity: utopia_store::graph::Validity {
118+ from: Some(day(from)),
119+ from_precision: Some("day"),
120+ to: None,
121+ to_precision: None,
122+ },
123+ confidence: 0.9,
124+ chunk_id: f.chunk,
125+ proposed_by: None,
126+ },
127+ )
128+ };
129+
130+ // 1. 提议不上图
131+ let first = propose(f.shenzhen, "2026-03-15").await?;
132+ assert!(matches!(first, Outcome::Proposed(_)), "第一次该进队列");
133+ assert_eq!(live_facts(&pool, f.kb).await?, 0, "提议阶段图上不能有活边");
134+ let queued = pending::for_chunk(&pool, f.kb, f.chunk).await?;
135+ assert_eq!(queued.len(), 1);
136+ assert_eq!(queued[0].subject_name, "Acme");
137+ assert!(queued[0].quote.contains("Acme moved its headquarters"), "原句要跟着提议一起给人看");
138+
139+ // 2. 同一句重抽不重复提
140+ assert_eq!(propose(f.shenzhen, "2026-03-15").await?, Outcome::AlreadyPending);
141+
142+ // 3. 点头:进账本,证据指回那句话,队列清空
143+ let Outcome::Proposed(id) = first else { unreachable!() };
144+ let done = pending::confirm(&pool, f.kb, id).await?;
145+ assert!(done.created, "确认该落一条新事实");
146+ assert_eq!(live_facts(&pool, f.kb).await?, 1);
147+ let (ev_chunk, ev_proposed): (Uuid, Option<String>) = sqlx::query_as(
148+ "SELECT chunk_id, proposed_predicate FROM fact_evidence WHERE fact_id = $1",
149+ )
150+ .bind(done.fact_id)
151+ .fetch_one(&pool)
152+ .await?;
153+ assert_eq!(ev_chunk, f.chunk, "证据要指回那句记忆");
154+ assert_eq!(ev_proposed.as_deref(), Some("moved headquarters to"));
155+ assert!(pending::for_chunk(&pool, f.kb, f.chunk).await?.is_empty());
156+
157+ // 4. 图上已有的不再问
158+ assert_eq!(propose(f.shenzhen, "2026-03-15").await?, Outcome::AlreadyAsserted);
159+
160+ // 5. 摇头有记忆:拒过的三元组下一轮不再被提
161+ let Outcome::Proposed(bad) = propose(f.shanghai, "2020-01-01").await? else {
162+ panic!("换一个宾语该是新提议");
163+ };
164+ pending::reject(&pool, f.kb, bad, None).await?;
165+ assert_eq!(propose(f.shanghai, "2020-01-01").await?, Outcome::Rejected);
166+ assert_eq!(live_facts(&pool, f.kb).await?, 1, "拒绝不碰图");
167+
168+ // 6. 点头走的是抽取那条路:functional 关系的新值闭合旧值。
169+ // 拒绝记录按 (主语, 谓词, 宾语) 查,同一个宾语换日期照样被挡——
170+ // 所以换一个宾语实体来演接任
171+ let beijing = Uuid::now_v7();
172+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Beijing')")
173+ .bind(beijing)
174+ .bind(f.kb)
175+ .execute(&pool)
176+ .await?;
177+ let Outcome::Proposed(next) = propose(beijing, "2027-01-01").await? else {
178+ panic!("接任该是新提议");
179+ };
180+ let moved = pending::confirm(&pool, f.kb, next).await?;
181+ assert!(moved.created);
182+ assert_eq!(moved.conflicts, 0, "先后清楚、置信够高,该自动闭合而不是进冲突");
183+ let (closed,): (i64,) = sqlx::query_as(
184+ "SELECT count(*) FROM facts
185+ WHERE kb_id = $1 AND object_id = $2 AND invalidated_at IS NULL AND valid_to IS NOT NULL",
186+ )
187+ .bind(f.kb)
188+ .bind(f.shenzhen)
189+ .fetch_one(&pool)
190+ .await?;
191+ assert_eq!(closed, 1, "深圳那条该被闭合成有终点的区间");
192+ Ok::<_, anyhow::Error>(())
193+ }
194+ .await;
195+
196+ // 删掉夹具自己建的 org,级联带走工作区、知识库与其余一切。
197+ // 从前只删知识库,每跑一次就在库里多留一对空的 org / workspace——
198+ // 「生产代码里没有删 org 这个动作」是对的,但夹具不是生产代码,自己建的自己收
199+ sqlx::query("DELETE FROM organizations WHERE id = $1")
200+ .bind(f.org)
201+ .execute(&pool)
202+ .await?;
203+ run
204+}
added crates/utopia-store/tests/a_signature_holds_on_every_path.rs +303 −0
@@ -0,0 +1,303 @@
1+//! 关系的签名(domain / range)在**三条写路径**上都得算数(#190 / #196)。
2+//!
3+//! 抽取写入时按 #138 掰正方向或留空谓词,但写谓词的路不止一条:**采纳**把谓词挂回
4+//! 旧事实,**合并**换掉主语的类型。守卫只装在抽取上,另外两条各自绕过去——实测采纳
5+//! 把违反率从 0 抬到 12.3%。这里守三件事:
6+//!
7+//! 1. 采纳走同一道判断:主语不合宾语合 → 对调着挂;两边都不合 → 不挂,事实留在空谓词上。
8+//! 2. 合并之后,被换了主语的事实若违反签名 → `axiom_violations` 里多一条 `signature`。
9+//! 3. 一致性检查(R0)也能量出签名违规,事实撤了它就被清掉。
10+//!
11+//! 没有 `UTOPIA_DATABASE_URL` 时跳过而不是失败。自建自拆,绝不碰已有的库。
12+
13+use sqlx::PgPool;
14+use utopia_store::graph::Adopted;
15+use uuid::Uuid;
16+
17+struct Fixture {
18+ org: Uuid,
19+ kb: Uuid,
20+ company: Uuid,
21+ person: Uuid,
22+ /// schema.org 的 `employee (organization → person)`
23+ employee: Uuid,
24+ acme: Uuid,
25+ alice: Uuid,
26+ bob: Uuid,
27+ doc: Uuid,
28+ chunk: Uuid,
29+}
30+
31+async fn seed(pool: &PgPool) -> anyhow::Result<Fixture> {
32+ let (org, ws, kb) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
33+ let (company, person, employee) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
34+ let (acme, alice, bob) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
35+ let (src, doc, chunk) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
36+
37+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'signature-test')")
38+ .bind(org)
39+ .execute(pool)
40+ .await?;
41+ sqlx::query("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, 'signature-test')")
42+ .bind(ws)
43+ .bind(org)
44+ .execute(pool)
45+ .await?;
46+ sqlx::query(
47+ "INSERT INTO knowledge_bases (id, workspace_id, name) VALUES ($1, $2, 'signature-test')",
48+ )
49+ .bind(kb)
50+ .bind(ws)
51+ .execute(pool)
52+ .await?;
53+ for (id, key, label) in [
54+ (company, "company", "Company"),
55+ (person, "person", "Person"),
56+ ] {
57+ sqlx::query("INSERT INTO entity_types (id, kb_id, key, label) VALUES ($1, $2, $3, $4)")
58+ .bind(id)
59+ .bind(kb)
60+ .bind(key)
61+ .bind(label)
62+ .execute(pool)
63+ .await?;
64+ }
65+ sqlx::query(
66+ "INSERT INTO relation_types (id, kb_id, key, label) VALUES ($1, $2, 'employee', 'employee')",
67+ )
68+ .bind(employee)
69+ .bind(kb)
70+ .execute(pool)
71+ .await?;
72+ sqlx::query(
73+ "INSERT INTO relation_type_domains (relation_type_id, entity_type_id) VALUES ($1, $2)",
74+ )
75+ .bind(employee)
76+ .bind(company)
77+ .execute(pool)
78+ .await?;
79+ sqlx::query(
80+ "INSERT INTO relation_type_ranges (relation_type_id, entity_type_id) VALUES ($1, $2)",
81+ )
82+ .bind(employee)
83+ .bind(person)
84+ .execute(pool)
85+ .await?;
86+ for (id, ty, name) in [
87+ (acme, company, "Acme"),
88+ (alice, person, "Alice"),
89+ (bob, person, "Bob"),
90+ ] {
91+ sqlx::query(
92+ "INSERT INTO entities (id, kb_id, type_id, canonical_name) VALUES ($1, $2, $3, $4)",
93+ )
94+ .bind(id)
95+ .bind(kb)
96+ .bind(ty)
97+ .bind(name)
98+ .execute(pool)
99+ .await?;
100+ }
101+ sqlx::query("INSERT INTO sources (id, kb_id, name) VALUES ($1, $2, 'signature-test')")
102+ .bind(src)
103+ .bind(kb)
104+ .execute(pool)
105+ .await?;
106+ sqlx::query(
107+ "INSERT INTO documents (id, kb_id, source_id, filename, sha256, status)
108+ VALUES ($1, $2, $3, 'note.md', 'signature', 'ready')",
109+ )
110+ .bind(doc)
111+ .bind(kb)
112+ .bind(src)
113+ .execute(pool)
114+ .await?;
115+ sqlx::query(
116+ "INSERT INTO chunks (id, kb_id, document_id, seq, text)
117+ VALUES ($1, $2, $3, 0, 'Alice is an employee of Acme. Bob is an employee of Alice.')",
118+ )
119+ .bind(chunk)
120+ .bind(kb)
121+ .bind(doc)
122+ .execute(pool)
123+ .await?;
124+ Ok(Fixture {
125+ org,
126+ kb,
127+ company,
128+ person,
129+ employee,
130+ acme,
131+ alice,
132+ bob,
133+ doc,
134+ chunk,
135+ })
136+}
137+
138+/// 一条没有谓词、证据里留着原文说法 `employee` 的事实——采纳要改写的正是这种
139+async fn surfaced_fact(
140+ pool: &PgPool,
141+ f: &Fixture,
142+ subject: Uuid,
143+ object: Uuid,
144+) -> anyhow::Result<Uuid> {
145+ let id = Uuid::now_v7();
146+ sqlx::query(
147+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
148+ VALUES ($1, $2, $3, NULL, $4, 0.9)",
149+ )
150+ .bind(id)
151+ .bind(f.kb)
152+ .bind(subject)
153+ .bind(object)
154+ .execute(pool)
155+ .await?;
156+ sqlx::query(
157+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, proposed_predicate, document_id, doc_version)
158+ VALUES ($1, $2, 'employee of', 'employee', $3, 1)",
159+ )
160+ .bind(id)
161+ .bind(f.chunk)
162+ .bind(f.doc)
163+ .execute(pool)
164+ .await?;
165+ Ok(id)
166+}
167+
168+async fn live_employee_edges(pool: &PgPool, f: &Fixture) -> anyhow::Result<Vec<(Uuid, Uuid)>> {
169+ Ok(sqlx::query_as(
170+ "SELECT subject_id, object_id FROM facts
171+ WHERE kb_id = $1 AND predicate_id = $2 AND invalidated_at IS NULL
172+ ORDER BY recorded_at",
173+ )
174+ .bind(f.kb)
175+ .bind(f.employee)
176+ .fetch_all(pool)
177+ .await?)
178+}
179+
180+async fn open_signature_breaks(pool: &PgPool, kb: Uuid) -> anyhow::Result<Vec<Uuid>> {
181+ Ok(sqlx::query_as::<_, (Uuid,)>(
182+ "SELECT left_fact FROM axiom_violations
183+ WHERE kb_id = $1 AND kind = 'signature' AND status = 'open'",
184+ )
185+ .bind(kb)
186+ .fetch_all(pool)
187+ .await?
188+ .into_iter()
189+ .map(|(id,)| id)
190+ .collect())
191+}
192+
193+#[tokio::test]
194+async fn adoption_and_merge_respect_the_signature() -> anyhow::Result<()> {
195+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
196+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
197+ return Ok(());
198+ };
199+ let pool = PgPool::connect(&url).await?;
200+ let f = seed(&pool).await?;
201+
202+ let run = async {
203+ // 模型写的是 "Alice is an employee of Acme" —— 主语 person 违反 domain、宾语 company 符合
204+ let reversed = surfaced_fact(&pool, &f, f.alice, f.acme).await?;
205+ // "Bob is an employee of Alice" —— 两边都是 person,这个关系压根不适用
206+ let hopeless = surfaced_fact(&pool, &f, f.bob, f.alice).await?;
207+
208+ // 1. 采纳:一条对调着挂上,一条不挂
209+ let Adopted {
210+ moved, left_off, ..
211+ } = utopia_store::graph::adopt_proposed_predicates(
212+ &pool,
213+ f.kb,
214+ f.employee,
215+ &["employee".to_string()],
216+ false,
217+ )
218+ .await?;
219+ assert_eq!(moved, 1, "the reversed one is adoptable once swapped");
220+ assert_eq!(left_off, 1, "the hopeless one must be left without a predicate");
221+ assert_eq!(
222+ live_employee_edges(&pool, &f).await?,
223+ vec![(f.acme, f.alice)],
224+ "adoption must write the edge in the ontology's direction: Acme employee Alice"
225+ );
226+ let (still_bare,): (bool,) =
227+ sqlx::query_as("SELECT predicate_id IS NULL AND invalidated_at IS NULL FROM facts WHERE id = $1")
228+ .bind(hopeless)
229+ .fetch_one(&pool)
230+ .await?;
231+ assert!(still_bare, "a fact that fits neither way stays live and predicate-less");
232+ let (old_gone,): (bool,) =
233+ sqlx::query_as("SELECT invalidated_at IS NOT NULL FROM facts WHERE id = $1")
234+ .bind(reversed)
235+ .fetch_one(&pool)
236+ .await?;
237+ assert!(old_gone, "the reversed row was superseded, not left beside the corrected one");
238+ assert!(open_signature_breaks(&pool, f.kb).await?.is_empty());
239+
240+ // 2. 合并:把 Acme 并进 Bob(person),Acme employee Alice 的主语变成 person
241+ utopia_store::resolution::merge_entities(&pool, f.kb, f.acme, f.bob, None, "test")
242+ .await?;
243+ let edges = live_employee_edges(&pool, &f).await?;
244+ assert_eq!(edges, vec![(f.bob, f.alice)], "the merge moved the subject onto Bob");
245+ let (moved_fact,): (Uuid,) = sqlx::query_as(
246+ "SELECT id FROM facts WHERE kb_id = $1 AND predicate_id = $2 AND invalidated_at IS NULL",
247+ )
248+ .bind(f.kb)
249+ .bind(f.employee)
250+ .fetch_one(&pool)
251+ .await?;
252+ assert_eq!(
253+ open_signature_breaks(&pool, f.kb).await?,
254+ vec![moved_fact],
255+ "a merge that breaks the signature must show up as an open violation"
256+ );
257+
258+ // 3. 一致性检查量得出它,撤了事实就清掉
259+ let report = utopia_store::reasoning::run(&pool, f.kb).await?;
260+ assert_eq!(report.found, 1);
261+ assert_eq!(report.inserted, 0, "already recorded by the merge; the check must not duplicate it");
262+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
263+ .bind(moved_fact)
264+ .execute(&pool)
265+ .await?;
266+ let report = utopia_store::reasoning::run(&pool, f.kb).await?;
267+ assert_eq!(report.found, 0);
268+ assert_eq!(report.cleared, 1, "a retracted fact takes its violation with it");
269+ assert!(open_signature_breaks(&pool, f.kb).await?.is_empty());
270+
271+ // 未分类的实体不算违反:类型是 NULL 的主语没有东西可比
272+ let untyped = Uuid::now_v7();
273+ sqlx::query("INSERT INTO entities (id, kb_id, canonical_name) VALUES ($1, $2, 'Nobody')")
274+ .bind(untyped)
275+ .bind(f.kb)
276+ .execute(&pool)
277+ .await?;
278+ sqlx::query(
279+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, confidence)
280+ VALUES ($1, $2, $3, $4, $5, 0.9)",
281+ )
282+ .bind(Uuid::now_v7())
283+ .bind(f.kb)
284+ .bind(untyped)
285+ .bind(f.employee)
286+ .bind(f.alice)
287+ .execute(&pool)
288+ .await?;
289+ assert!(
290+ utopia_store::reasoning::signature_breaks(&pool, f.kb, None).await?.is_empty(),
291+ "an untyped subject is unknown, not wrong"
292+ );
293+ let _ = (f.company, f.person);
294+ anyhow::Ok(())
295+ }
296+ .await;
297+
298+ let _ = sqlx::query("DELETE FROM organizations WHERE id = $1")
299+ .bind(f.org)
300+ .execute(&pool)
301+ .await;
302+ run
303+}
modified crates/utopia-store/tests/adopt_swap.rs +3 −2
@@ -97,14 +97,15 @@
9797 .await?;
9898
9999 let run = async {
100- let (_, moved) = utopia_store::graph::adopt_proposed_predicates(
100+ let moved = utopia_store::graph::adopt_proposed_predicates(
101101 &pool,
102102 kb,
103103 produces,
104104 &["produced_by".to_string()],
105105 true,
106106 )
107- .await?;
107+ .await?
108+ .moved;
108109 assert_eq!(moved, 1);
109110 // 改写后应该是 OpenAI -[produces]-> ChatGPT,**方向反过来**
110111 let (s, o): (Uuid, Option<Uuid>) = sqlx::query_as(
modified docs/decisions/0002-reasoning-engine.md +1 −0
@@ -101,6 +101,7 @@
101101
102102 > **修订记录(2026-09-02):R0 建成,四处与上面写的不同。**
103103 > 一、**四类不是三类,且不是那三类**:`self_loop` / `asymmetry` / `cycle` / `functional`(兼含 inverse_functional)。**事实层的 disjointWith 违反没有做**——disjoint 只进了本体自检。
104+> 〔后来多了第五类 `signature`(#190 / #196):主语不在谓词的 domain、或宾语不在 range。它不由纯逻辑引擎算——要看实体类型与闭包,那是库里的东西——`store::reasoning::signature_breaks` 用 SQL 量,算出来后与其它四类走同一条落库、清陈、裁决的路。合并之后对搬动过的事实立刻查,手动跑检查时全量查。未分类实体不算。〕
104105 > 二、**不进 `fact_conflicts`,另建 `axiom_violations`**:那张表问的是「哪条对」,公理违规问的是「错在数据还是错在定义」,出路是 `fact_retracted` / `axiom_relaxed` / `accepted`。「零新界面」也没守住,Review 页多了 `violations` 与 `defects` 两个页签。
105106 > 三、**多出另一半:本体自身的自洽性**(`ontology_defects`,八类:symmetric 且 asymmetric、transitive 且 functional、子类成环、与祖先 disjoint、继承来的 disjoint、自逆、逆没指回来、子属性成环)。理由是自相矛盾的本体会让事实层的结论全部可疑,所以缺陷优先于违规展示。
106107 > 四、环检测是深度优先不是半朴素——闭包只告诉你 A 推出了 A,人要的是**路径**;半朴素在 R1。
modified docs/decisions/0012-the-ontology-is-a-contract-not-a-suggestion.md +1 −1
@@ -167,7 +167,7 @@
167167 ## 待做
168168
169169 - **写入时的守卫挡不住写入之后的改动**:实体合并会把主语换成另一个类型的实体,
170- 于是事实「变成」违反。实测 6 条残留里 4 条如此。要治得把同样的检查放进合并路径。〔仍未做:`merge_entities` 只做互指事实作废、主宾改指、SPO 去重,全程没有 domain / range 复核。〕
170+ 于是事实「变成」违反。实测 6 条残留里 4 条如此。要治得把同样的检查放进合并路径。〔**已做**(#190 / #196,`fix/one-domain-check-for-three-paths`):写入时的判断抽成 `ontology::judge_direction`,抽取与**采纳**共用——采纳是第二条写谓词的路,实测把违反率从 0 抬到 12.3%,全在包关系上;两边都不合的采纳**不挂谓词**,条数随 `facts_left_off` 上报。**合并**不掰不改只报:搬动过的事实查一遍 domain / range,违反的进 `axiom_violations`(新 kind `signature`)。一致性检查(0002 R0)也多了这一类,全量量、事实撤了就清,所以本体事后改 domain 也逃不过。未分类实体不算违反——「不知道」不是「不符合」。〕
171171 - 另外 2 条残留(`Stability AI Ltd`、`Colossus 2 data center`)没有合并也没有改类型,
172172 **原因未查明**。
173173 - 导入本体包时过滤掉需要中间节点才能用的关系(domain 全是 `Action`/`Offer`/
modified docs/decisions/0014-identity-from-the-person-scope-from-the-token.md +2 −2
@@ -1,6 +1,6 @@
11 # 0014 · 身份跟着人,范围跟着令牌
22
3-- **状态**:已实施(#161 记录、#180 落地)· `personal_tokens` + Streamable HTTP 的 MCP 服务端已上线,暴露五个只读工具;**尚无前端界面**——令牌的发放 / 列表 / 撤销与 MCP 配置提示今天都只有 API(2026-09-02 核,修订见文末)
3+- **状态**:已实施(#161 记录、#180 落地)· `personal_tokens` + Streamable HTTP 的 MCP 服务端已上线,暴露五个只读工具;界面在 `feat/tokens-have-a-page`(0016 A2):账户层「Agents & tokens」页,发放时明文与 MCP 客户端配置片段一起只显示一次,列表只剩前缀,撤销留痕(2026-09-02 核,修订见文末)
44 - **成文**:2026-09-01(约定见 [README](README.md))
55 - **相关**:迁移 `0014_data_source_grants` 刚给数据源补上授权层——本篇是同一个问题
66 换到「机器来敲门」这一侧;[0004](0004-language-and-localization.md) 定下服务端只说英文,
@@ -136,4 +136,4 @@
136136 和 Utopia 已经是个服务端相称)。这个选择不影响本篇的结论,两种都要认令牌。〔**已答:Streamable HTTP**,一条路由 `POST /api/v1/kbs/{kb_id}/mcp`,响应用 `application/json` 不用 SSE——工具一问一答,没有服务端主动推的东西。〕
137137 - **令牌能不能跨工作区。** 现在的 `kb_ids` 是库级白名单;如果将来要按工作区发,
138138 和数据源授权那张表会长得很像,届时看要不要合并概念。〔仍未做。〕
139-- **(2026-09-02 补)没有界面。** 「UI 默认给 90 天」的 90 天在服务端,而前端根本没有令牌那一页。这是 MCP 今天对用户不可用的直接原因。
139+- **(2026-09-02 补)没有界面。** 「UI 默认给 90 天」的 90 天在服务端,而前端根本没有令牌那一页。这是 MCP 今天对用户不可用的直接原因。〔**已做**,同日:`/account/tokens`。三个决定落在界面上——scope 缺省只读、库多选、过期缺省 90 天且「不过期」要显式选;配置片段按库出端点(令牌限定到库,端点也按库分),写法取 Claude Code / Claude Desktop 一族的 Streamable HTTP 键名,别的客户端要自己改键。〕
modified docs/decisions/0015-recording-a-sentence-is-not-asserting-a-fact.md +23 −2
@@ -1,6 +1,6 @@
11 # 0015 · 记下一句话,不等于断言一个事实
22
3-- **状态**:进行中 · schema 已落(迁移 `0018_a_fact_awaiting_a_nod`,与本文同一 PR #180)· **抽取侧尚未接线,三条决定一条都没落地;`remember` 已被整体停用作为临时闸**(2026-09-02 核,修订见文末)
3+- **状态**:已实施 · schema 在迁移 `0018`(#180),运行时随 [0016](0016-close-the-open-seams-before-cutting-new-ones.md) A1 接上:抽取分流进 `pending_facts`、Review 新一档、对话里跟在 remember 后面的确认卡、`remember` 重新打开。**决定 3 的措辞与本文写的不同**,见文末最后一条修订
44 - **成文**:2026-09-01(约定见 [README](README.md))
55 - **相关**:[0010](0010-no-relation-is-no-relation.md) 删掉兜底关系(本篇那条空谓词正是它的
66 正确行为)、[0011](0011-a-mapping-is-not-a-fact.md) 批过「拿浮点数编码二值状态」——
@@ -136,12 +136,33 @@
136136
137137 **同一类问题的另一面**(#173,迁移 `0015_what_it_did_not_just_what_it_said`):跨轮回放助手上一轮的工具调用与结果,模型才知道自己做过什么,不会把上一轮的检索重跑一遍落到另一批同名实体上。本文讲的是「助手说的」与「图里得到的」之间的落差,那一条讲的是「助手说的」与「助手做的」之间的落差。
138138
139+## 修订记录:接上运行时之后,三处与本文不同
140+
141+**一、助手说不出「抽出 N 条」。** 决定 3 写的是「已记录,抽出 N 条待你确认」。抽取是异步走队列的,
142+`remember` 回话的那一刻抽取还没跑,N 不存在。两条路:把记忆抽取改成同步(一句话十来秒,卡住整个对话循环),
143+或者如实说「这句话记下了,从中抽出的事实会先给你确认,确认前不进图」,等抽取完成时再把确认卡**长到对话里**。
144+选了后者。卡片靠 SSE 的 `pending` 事件触发,按那句记忆的 chunk 取待确认项;回放旧会话时同样按 chunk 取,
145+还有没点头的就照样显示,都处理完了就不占地方。
146+
147+**二、确认界面在两处,同一个组件。** Review 页新一档「等你点头」排在最前——它是人自己说的话,而且这一档里的
148+东西还没进图,别处每一档审的都是已经在图上的。对话里那张卡是同一行组件。载荷是声明式的(chunk + 三元组列表),
149+将来若要让别人的客户端渲染它(MCP 那一侧),换的是渲染器不是服务端。
150+
151+**三、确认走的正是抽取那条路。** 事实 + 证据(指回那句记忆,引句就是整句)+ 时态对账。所以「Mira 交给
152+Devin 了」点头之后,Mira 那条会像从文档里抽出来时一样被闭合。置信度不动,人的态度在台账里
153+(`fact.nod_confirmed` / `fact.nod_rejected`,快照自包含)。
154+
155+**顺带定下的**:拒绝记录按(主语, 谓词, 宾语实体)查,**字面值事实不查**——`rejected_facts` 没有 `object_value`
156+列,按(主语, 谓词)挡会把「薪水 28000 被拒」扩大成「薪水这个属性永远不再提」,宁可多问一次。
157+实体照常消解并创建,`pending_facts.subject_id` 是外键,这是 0018 定下的取舍;代价是几个暂时孤立的节点。
158+「谁说的」从 `remember` 经 `memory_ingest` 与 `extract_document` 的任务载荷一路传到 `proposed_by`。
159+
139160 ## 未决
140161
141162 - **闸只拦记忆,还是拦所有「单条、交互式」的写入?** 今天只有 `remember` 这一条路,
142163 但将来若有「在图上手工加一条边」的界面,它该走哪边?
143164 - **确认之后置信度取什么。** 人点了头还留 0.9,还是升到 1.0?0011 的教训说别拿
144- confidence 表达人的态度,那大概是「不动它」——但要想清楚。
165+ confidence 表达人的态度,那大概是「不动它」——但要想清楚。〔**已定:不动**。人的态度在台账里。〕
145166 - **拒绝之后那条记忆怎么办。** 文档还在(人确实说过那句话),只是没抽出可用的事实。
146167 下一轮重抽会不会又提议一遍?`concept_mappings` 那边靠 `status='rejected'` 挡住了
147168 重复提议,这里需要对应的东西。〔答了一半:`rejected_facts` 表与查重索引建好了,语义就是「这个三元组在这个库里被拒过」,但没有任何代码写它或查它。〕
modified docs/decisions/0016-close-the-open-seams-before-cutting-new-ones.md +9 −4
@@ -26,7 +26,7 @@
2626 | `utopia-mcp` / `utopia-connectors` / `utopia-graph` 三个 crate 是三行占位,其中一个宣称的工具名从未实现 | 0014 | 读源码的人被误导 |
2727 | 证明树只展开一层;增量维护没做;派生 vs 断言矛盾不记信号 | 0002 | README 说 derivation path expands back to the sentence,只对了一层 |
2828 | `disjointWith` 落库了,消解侧仍用硬编码 `CONFUSABLE_TYPE_KEYS` | 0009 / 0001 P5 | 本体声明了不相交,合并候选照样跨过去 |
29-| 合并路径没有签名复核 | 0012 待做 | 写入时掰正的方向,合并一次就能再反回去 |
29+| 合并路径没有签名复核〔已做,#196;采纳那条路也没有,#190,一并做了〕 | 0012 待做 | 写入时掰正的方向,合并一次就能再反回去 |
3030 | 类型消解只能手动跑 | 0001 P3a | 大本体下新实体的细化靠人记得点一下 |
3131 | 中文库拿到纯英文本体;`zh.ts` 没追平所以界面默认英文 | 0008 / 0004 | 中文用户两头都是英文 |
3232 | `merge_key` 不折 `_by`;叙述动词进本体 | 0007 | 同一关系两个方向并存 |
@@ -50,16 +50,16 @@
5050
5151 ### A · 收口——两到三周,不加新概念
5252
53-**A1 · 把 0015 接上。** 抽取遇到记忆文档(`memory::is_memory_document`,已写好零调用)时写 `pending_facts` 而不是 `facts`;
53+**A1 · 把 0015 接上。**〔已做,形态与下文有两处不同,见 0015 末尾的修订:助手说不出 N,确认卡在对话里随抽取完成长出来。〕 抽取遇到记忆文档(`memory::is_memory_document`,已写好零调用)时写 `pending_facts` 而不是 `facts`;
5454 Review 加 `pending` 一档,界面**原句在上、三元组在下**;确认 → `insert_fact`,**置信度不动**(0011 的教训:别拿浮点数表达人的态度,人的态度在审计台账里);
5555 拒绝 → 写 `rejected_facts`,下一轮重抽先查它;`remember` 的回话改成「已记录,抽出 N 条待你确认」;然后把 `REMEMBER_ENABLED` 改回 true。
5656 **验收**:那条实测(「Acme 把总部搬到深圳」)跑一遍,图上不出现空谓词活边,Review 里出现一条带原句的待确认项。
5757 做完这一条,MCP 可以放 `remember`(scope = write,令牌以人的身份提议,人自己确认)——0014 未决的答案由此成立。
5858
59-**A2 · 令牌有界面。** Account 页:列表(前缀、名字、scope、库、最后使用、过期)、发放(明文只显示一次)、撤销;旁边给一段可复制的 MCP 客户端配置(URL + Authorization 头)。
59+**A2 · 令牌有界面。**〔已做,`feat/tokens-have-a-page`〕Account 页:列表(前缀、名字、scope、库、最后使用、过期)、发放(明文只显示一次)、撤销;旁边给一段可复制的 MCP 客户端配置(URL + Authorization 头)。
6060 三个占位 crate **删掉**(已做,与 A3 同一刀):`utopia-mcp` 宣称的三个工具从未存在,服务端住在 `utopia-server/src/api/mcp.rs`;`utopia-graph` 没有对应物;`utopia-connectors` 的意图是对的,但两个连接器看不出边界该划在哪,[0013](0013-a-source-should-hand-over-its-history.md) 说等第三个来了再看抽象,crate 是同一个判断。占位是对读者的承诺,兑现不了就别留,需要时 `cargo new` 是几分钟的事。
6161
62-**A3 · 清死代码与陈旧注释。** 上表最后一行那五处,加上 `resolution.rs` 里 `CONFUSABLE_TYPE_KEYS` 上方停留在旧世界的注释。一个 PR。
62+**A3 · 清死代码与陈旧注释。**〔已做,分两刀:#188 那批清了五处死代码与三个占位 crate;`chore/comments-catch-up` 补了还在描述「兜底谓词」的五处注释和一处指向仓库外 DESIGN.md 的引用〕上表最后一行那五处,加上 `resolution.rs` 里 `CONFUSABLE_TYPE_KEYS` 上方停留在旧世界的注释。一个 PR。
6363
6464 **A4 · README 与代码对表。** Reasoning 那一行的 "derivation path expands all the way back to the original sentence" 在 B1 做完之前改成只承诺一层;
6565 Chat memory 与 MCP 两处在 A1 / A2 落地前标 in development。中英两份一起改。
@@ -70,6 +70,7 @@
7070 **B2 · 派生 vs 断言矛盾要有信号。** `axiom_violations` 加一种 kind(`derived_contradiction`),进 Review 同一档——0002 写了没做的那一行。
7171 **B3 · `disjointWith` 进消解,合并路径复核签名。** `classify_type_drift` 改从 `entity_type_disjoint` 读(没声明就退回今天的行为,不硬编码);
7272 `merge_entities` 搬事实前跑一遍与写入时相同的 domain / range 检查,违反的进 `axiom_violations` 而不是静默搬过去。这是 0009 与 0012 各自待做的同一件事。
73+〔**签名那一半已提前做了**(#190 / #196 逼出来的,A 线里插队):`ontology::judge_direction` 一处判断,抽取与采纳共用;合并后对搬动过的事实报 `signature` 违规;R0 多一类。剩下 `disjointWith` 进消解那一半仍在这里。〕
7374 **B4 · R3 增量维护——后置。** 只在测量台上全量重推超过一个明确阈值(建议:`ai-timeline-ends` 语料超过 10 秒)时才做。今天每次全量重推活得下去。
7475
7576 ### C · 本体与抽取质量——先造尺子,再调参
@@ -114,5 +115,9 @@
114115 - **A1 的闸只拦记忆,还是拦所有单条交互式写入?** 0015 未决。今天只有 `remember` 一条路,先拦它;将来「在图上手工加一条边」的界面出现时,按同一张表走。
115116 - **C3 生成的中文描述算不算「原文保真」的例外?** 它不是导入的原文,是我们生成的投影。倾向记成投影(可重跑、可丢弃),原文 IRI 与英文描述保留在包里。
116117 - **B4 的阈值**:10 秒是拍的。
118+- **对话内 agent 生成的界面走哪个协议。** A1 的确认卡载荷是声明式的(chunk + 三元组列表),渲染器是我们的 React。
119+ 讨论过 A2UI(2026-09-02):它解决的是「你不控制的客户端渲染你 agent 的 UI」,而 Chat 页两头都是我们的;
120+ 卖点成立的地方在 MCP 那一侧,那里对应的是 MCP 自己的 UI 扩展,不是 A2UI。**判据是谁的客户端在看**,
121+ 等 MCP 放开写工具、有外部客户端要渲染这张卡时再定。
117122 - **要不要把抽取层拆出 `utopia-server`。** 今天约 6,500 行领域代码(extraction、type_resolution、bootstrap_ontology、predicate_match、adjudication、owl_import、连接器)住在 HTTP crate 里,依赖方向仍是干净的一条线。讨论过(2026-09-02)决定**不拆**:唯一实在的收益是脱离 server 测纯函数,而它们的单测今天已经不起 server;搬动 1,500 行的 `extraction.rs` 会让紧接着的 A1 diff 和 blame 变难看。判据留下:**等它造成实际损失再拆,损失的定义是「有东西没法脱离 server 测试」**。连接器那一块的边界等第三个连接器(飞书)来了再定。
118123 - **十万文档基准跑出来之后**,单进程 worker 与内嵌 Tantivy 的天花板在哪,决定了要不要在 v0.2 谈横向扩展。现在不谈。
modified docs/decisions/README.md +4 −4
@@ -27,7 +27,7 @@
2727 | | 文档 | 状态 |
2828 |---|---|---|
2929 | 0001 | [本体导入与治理路线](0001-ontology-import-and-governance.md) | 进行中 · P0–P2c 全建成;P3 按预算落地、P3a 只能手动跑;P3b 建成但形态不同;**P4b/P4c 待做**;P5 已由 0002 落地;判据 2 被 0012 推翻一半 |
30-| 0002 | [推理机](0002-reasoning-engine.md) | R0 建成(含本体自检八类)· R1 建成带开关默认关 · **R2 只一层、R3 未做** · 派生 vs 断言矛盾无信号 |
30+| 0002 | [推理机](0002-reasoning-engine.md) | R0 建成(事实层五类含签名、本体自检八类)· R1 建成带开关默认关 · **R2 只一层、R3 未做** · 派生 vs 断言矛盾无信号 |
3131 | 0003 | [本体从语料里长出来,人站在哪一环](0003-ontology-growth-loop.md) | 已建成且仍在跑 · 起点已被 0010 与种子退场改写 · 「拒绝有记忆」被 0007 推翻重做 · 新说法提醒待做 |
3232 | 0004 | [语言:哪些字跟着看的人走,哪些跟着语料走](0004-language-and-localization.md) | 已建成 · L0–L3 全落地 · 界面刻意不猜浏览器语言 · 「中文内置本体」随播种退场作废 |
3333 | 0005 | [告警中心](0005-alert-center.md) | 已建成 · 五种告警 · 三个决定推翻两个(就地留痕)· `no_text_layer` 待接 |
@@ -37,10 +37,10 @@
3737 | 0009 | [「还没判出来」不该是一个类](0009-no-type-is-a-type.md) | 已实施 · `disjointWith` 落库但消解侧未消费 · `metric`/`dimension` 去处未答且有可见代价 |
3838 | 0010 | [「说不出是什么关系」不该是一个关系](0010-no-relation-is-no-relation.md) | 已实施 · 待做两条随 0011 完成 · 两处死代码待清 |
3939 | 0011 | [「怎么算」不是「有什么」](0011-a-mapping-is-not-a-fact.md) | 已实施(#126 / #140 / #148)· 证据链未做 · 多源选法未做 |
40-| 0012 | [本体是一份契约,不只是一份建议](0012-the-ontology-is-a-contract-not-a-suggestion.md) | 已实施 · 违反率 57%→4%、反向 39→0 · 三条待做全未做 |
40+| 0012 | [本体是一份契约,不只是一份建议](0012-the-ontology-is-a-contract-not-a-suggestion.md) | 已实施 · 违反率 57%→4%、反向 39→0 · 守卫已扩到采纳与合并(#190 / #196),另两条待做仍在 |
4141 | 0013 | [一个来源该交出它的历史,不是它的现状](0013-a-source-should-hand-over-its-history.md) | 已实施两个(GitHub / Jira)· 文档协作类未开工 |
42-| 0014 | [身份跟着人,范围跟着令牌](0014-identity-from-the-person-scope-from-the-token.md) | 已实施(#180)· MCP 只读五工具 · **没有令牌界面** · 误导性的占位 crate 已删 |
43-| 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 进行中 · schema 已落、**运行时零接线** · `remember` 整体停用作临时闸 |
42+| 0014 | [身份跟着人,范围跟着令牌](0014-identity-from-the-person-scope-from-the-token.md) | 已实施(#180)· MCP 只读五工具 · 令牌页在账户层(A2)· 误导性的占位 crate 已删 |
43+| 0015 | [记下一句话,不等于断言一个事实](0015-recording-a-sentence-is-not-asserting-a-fact.md) | 已实施 · 记忆抽出的事实进 `pending_facts`,Review 新档 + 跟在 remember 步骤后的确认卡 · `remember` 重新打开 · MCP 放开写是下一刀 |
4444 | 0016 | [先把开着的口子收上,再开新的](0016-close-the-open-seams-before-cutting-new-ones.md) | 规划中 · v0.1.0 之后的排期:A 收口 → B 推理机 ∥ C 尺子与本体 → D 语义层 → E 企业交付;模拟引擎后置 |
4545
4646 ## 不是决策记录的那些
modified docs/pipeline.md +3 −1
@@ -249,7 +249,7 @@
249249 flowchart TB
250250 ONT[(本体的公理<br/>functional · symmetric · asymmetric<br/>transitive · inverseOf · subPropertyOf · disjoint)] --> SELF[本体自检<br/>八类缺陷]
251251 SELF --> DEF[(ontology_defects)]
252- ONT --> R0[事实层检查<br/>自环 · 反对称 · 传递环 · 基数]
252+ ONT --> R0[事实层检查<br/>自环 · 反对称 · 传递环 · 基数 · 签名]
253253 G[(图谱)] --> R0
254254 R0 --> VIO[(axiom_violations<br/>带完整路径)]
255255 VIO --> DEC{人裁}
@@ -264,6 +264,8 @@
264264 style DEC fill:#3a3a5a,color:#fff
265265 ```
266266
267+**签名在三条写路径上都算数**(#190 / #196):第一节那道「主宾对得上签名吗」的判断住在 store(`ontology::judge_direction`),抽取落新事实、采纳把谓词挂回旧事实都调它——两边都不合的采纳**不挂**,条数随 `facts_left_off` 上报;合并换了主宾之后不掰不改,只对搬动过的事实查一遍,违反的进 `axiom_violations`(`signature`)。检查里的第五类就是它的全量版,本体事后改了 domain 也逃不过。
268+
267269 **检查不写库,推导写另一张表。** 一致性检查(R0)只指出问题,风险面为零;物化推导(R1)会往图里加东西,所以它的每条约束都是必要的:
268270 规则**只从本体公理编译**,没有用户 DSL;**断言硬性优先于派生**——已经断言过的三元组不再派生,「这条是谁说的」有唯一答案;
269271 深度上限加环检测,每谓词封顶两万条且被截掉的**要说出来**;有效时间取前提的交集,空交集不推。
added migrations/0019_a_signature_holds_on_every_path.sql +18 −0
@@ -0,0 +1,18 @@
1+-- 签名违规成为一致性检查的一种(见 #190 / #196,docs/decisions/0012 待做第一条)。
2+--
3+-- #138 在抽取写入时按关系的 domain 掰正方向:主语不合、宾语合就对调,都不合就
4+-- 留空谓词。但写谓词的路不止抽取一条:**采纳**把谓词挂回旧事实(#190,实测把
5+-- 违反率从 0 抬到 12.3%),**合并**换掉主语的类型(#196)。守卫只在一条路上,
6+-- 另外两条各自绕过去了。
7+--
8+-- 修法两层:写入时的判断抽成一处(`ontology::judge_direction`),抽取与采纳共用;
9+-- 账本层再加一道兜底——一致性检查(0002 R0)多查一种 `signature`:活事实的主语
10+-- 不在谓词声明的 domain 里、或宾语不在 range 里。合并之后对搬动过的事实立刻查一遍,
11+-- 手动跑检查时全量查。**任何一条路写反了,人都能在 Review 里看见**,出路与其它
12+-- 违规一样:撤事实、放宽公理(去掉那条 domain 声明)、或认可并存。
13+--
14+-- 只动 CHECK 约束:表的形状够用——签名违规只涉及一条事实,left 与 right 同一条,
15+-- 与自反那类同款。
16+ALTER TABLE axiom_violations DROP CONSTRAINT axiom_violations_kind_check;
17+ALTER TABLE axiom_violations ADD CONSTRAINT axiom_violations_kind_check
18+ CHECK (kind IN ('self_loop', 'asymmetry', 'cycle', 'functional', 'signature'));
modified scripts/bench/fetch-wiki-history.mjs +11 −0
@@ -225,6 +225,17 @@
225225 .replace(/<style[\s\S]*?<\/style>/gi, "")
226226 .replace(/<script[\s\S]*?<\/script>/gi, "")
227227 .replace(/<table[\s\S]*?<\/table>/gi, "") // 信息框/导航框:全是模板残渣
228+ // **引文列表按结构切,不按标题切。** `CUT` 认的是 `== References ==` 那行,
229+ // 而参考文献是渲染出来的一个块,它**不一定在那个标题下面**:`<references/>`
230+ // 写在哪一节,它就渲染在哪一节。实测 216 张快照里有一张如此
231+ //(`Mistral AI` @2024-12-10,refs 块落在 Recent Developments 里),
232+ // 于是标题切完了,93 条引文照样留在正文里——占那一版正文的三分之一,
233+ // 而它们正是 `Wired --employee--> Steven Levy` 那类假事实的来源。
234+ //
235+ // 容器名是 MediaWiki 渲染的,不是条目作者写的,所以它比标题文字稳
236+ // (标题可以被译、被改写、被写成 `== Notes and references ==`)。
237+ // 标题那条留着:它还管着 External links / See also 这些不该进语料的尾节
238+ .replace(/<ol class="references"[\s\S]*?<\/ol>/gi, "")
228239 .replace(/<sup class="reference"[\s\S]*?<\/sup>/gi, "") // 脚注角标
229240 .replace(/<span class="mw-editsection"[\s\S]*?<\/span>/gi, "")
230241 .replace(/<h([1-6])[^>]*>/gi, (_, n) => "\n\n" + "=".repeat(+n) + " ")
modified web/src/api.ts +77 −0
@@ -57,6 +57,22 @@
5757 created_at: string;
5858 }
5959
60+/** 个人访问令牌(0014):给 MCP 客户端的长命钥匙,以发它的人的身份行事。
61+ * 有效权限 = 这个人的角色 ∩ scope;`kb_ids` 为空 = 这个人能进的全部库。 */
62+export interface TokenView {
63+ id: string;
64+ name: string;
65+ /** 给人认的那一小截(`utp_pat_ab12`),够对上配置文件里那一串,又不足以复原 */
66+ token_prefix: string;
67+ scope: "read" | "write";
68+ kb_ids: string[] | null;
69+ expires_at: string | null;
70+ last_used_at: string | null;
71+ /** 撤销打戳不删行 */
72+ revoked_at: string | null;
73+ created_at: string;
74+}
75+
6076 export interface Workspace {
6177 id: string;
6278 org_id: string;
@@ -169,6 +185,11 @@
169185 | "custom"
170186 | "github_issues"
171187 | "jira_issues"
188+ | "s3"
189+ | "azure_blob"
190+ | "gcs"
191+ | "webdav"
192+ | "notion"
172193 | "memory"
173194 | "upload";
174195 name: string;
@@ -304,6 +325,7 @@
304325 /** 审核页的分档。**与服务端的 queue 参数是同一组字面量**——拼错会拿到
305326 * 一个明确的 unknown_queue 错误,而不是悄悄的空列表。 */
306327 export type ReviewQueue =
328+ | "pending"
307329 | "duplicates"
308330 | "conflicts"
309331 | "unconfirmed"
@@ -315,6 +337,8 @@
315337
316338 /** 各档的真实条数。左栏的徽标读它,不读列表长度 */
317339 export interface ReviewCounts {
340+ /** 记忆抽出、等人点头的事实(0015) */
341+ pending: number;
318342 duplicates: number;
319343 conflicts: number;
320344 unconfirmed: number;
@@ -469,6 +493,29 @@
469493 quote: string | null;
470494 }
471495
496+/** 一句记忆抽出、等人点头的事实(0015)。`quote` 是那句记忆的全文——
497+ * 确认界面把原句放在三元组上面,人对着原句判断,而不是凭空判断三元组。 */
498+export interface PendingFactItem {
499+ id: string;
500+ subject_id: string;
501+ subject_name: string;
502+ predicate_id: string | null;
503+ /** 本体里的关系名;为空时显示 `proposed_predicate`(斜体,标明是原话) */
504+ predicate_label: string | null;
505+ proposed_predicate: string | null;
506+ object_id: string | null;
507+ object_name: string | null;
508+ object_value: { value?: unknown; unit?: string; summary?: string } | null;
509+ valid_from: string | null;
510+ valid_to: string | null;
511+ confidence: number;
512+ chunk_id: string;
513+ quote: string;
514+ proposed_by: string | null;
515+ proposed_by_name: string | null;
516+ created_at: string;
517+}
518+
472519 /** 时态冲突(自动闭合拿不准的那些):旧事实 vs 新事实。 */
473520 export interface ConflictItem {
474521 id: string;
@@ -782,6 +829,9 @@
782829 kind: "search" | "docs" | "entity" | "facts" | "changes" | "query" | "tool";
783830 label: string;
784831 detail: string;
832+ /** `remember` 那一步带着它:那句记忆落成的 chunk。对话里的确认卡按它取
833+ * 待确认项(0015);回放时也据此重画 */
834+ chunk_id?: string;
785835 /** 这一步发生时正文已经有多长(UTF-16 码元,与 `string.length` 同一单位)。
786836 * 据此把轨迹穿回正文里,而不是全堆在最前面。
787837 * **这条迁移之前的消息没有它**——缺省时整段轨迹回到顶部,即旧的样子 */
@@ -882,6 +932,23 @@
882932 new_password: newPassword,
883933 }),
884934 }),
935+ /** 我发过的个人令牌(0014)。撤销过的也在——撤过这件事本身要看得见 */
936+ tokens: () => request<{ tokens: TokenView[] }>("/api/v1/me/tokens"),
937+ /** 发一枚。**明文只在这一次的响应里**,列表永远给不出它 */
938+ issueToken: (body: {
939+ name: string;
940+ scope: "read" | "write";
941+ /** 缺省 = 这个人能进的全部库 */
942+ kb_ids?: string[] | null;
943+ /** 0 = 不过期 */
944+ expires_in_days: number;
945+ }) =>
946+ request<{ token: string; info: TokenView }>("/api/v1/me/tokens", {
947+ method: "POST",
948+ body: JSON.stringify(body),
949+ }),
950+ revokeToken: (tokenId: string) =>
951+ request<{ ok: boolean }>(`/api/v1/me/tokens/${tokenId}`, { method: "DELETE" }),
885952 workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
886953
887954 kbs: (workspaceId: string) =>
@@ -1518,6 +1585,16 @@
15181585 method: "POST",
15191586 body: JSON.stringify(body),
15201587 }),
1588+ /** 一句记忆抽出的全部待确认项(0015)。空数组 = 这句话没有等着人的东西了 */
1589+ pendingForChunk: (kbId: string, chunkId: string) =>
1590+ request<{ items: PendingFactItem[] }>(
1591+ `/api/v1/kbs/${kbId}/review/pending?chunk_id=${chunkId}`,
1592+ ),
1593+ decidePending: (kbId: string, pendingId: string, action: "confirm" | "reject") =>
1594+ request<{ ok: boolean; fact_id?: string; created?: boolean; conflicts?: number }>(
1595+ `/api/v1/kbs/${kbId}/review/pending/${pendingId}`,
1596+ { method: "POST", body: JSON.stringify({ action }) },
1597+ ),
15211598 decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
15221599 request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
15231600 method: "POST",
modified web/src/i18n/en.ts +98 −0
@@ -119,6 +119,47 @@
119119 deploymentAdmin: "Deployment admin",
120120 openKb: "Open",
121121 kbSettingsBtn: "Settings",
122+ /* 个人令牌页(0014 / 0016 A2):给 agent 的钥匙,以这个人的身份行事 */
123+ tokensNav: "Agents & tokens",
124+ tokensTitle: "Personal access tokens",
125+ tokensHint:
126+ "A token lets an agent reach Utopia over MCP as you, never with more than you can do yourself. Read-only by default, limited to the bases you pick, revocable here at any time.",
127+ newToken: "New token",
128+ tokenName: "Name",
129+ tokenNamePlaceholder: "My laptop",
130+ tokenScope: "Scope",
131+ scopeRead: "Read",
132+ scopeWrite: "Write",
133+ scopeHint:
134+ "Effective rights are your own role ∩ this scope. Write is a ceiling, not a grant: a viewer's write token still cannot write.",
135+ tokenKbs: "Knowledge bases",
136+ kbsAllHint: "Nothing selected means every base you can open.",
137+ tokenExpires: "Expires",
138+ expiresDays: (n: number) => `${n} days`,
139+ expiresNever: "Never",
140+ issueToken: "Create token",
141+ issuedTitle: "Copy it now. It will not be shown again.",
142+ issuedHint:
143+ "Utopia keeps only a hash of it. If you lose it, revoke it here and create another.",
144+ copy: "Copy",
145+ copied: "Copied",
146+ mcpTitle: "MCP client configuration",
147+ mcpHint:
148+ "For Claude Code, Claude Desktop and other Streamable HTTP clients. Each base has its own endpoint, so pick the one the agent should talk to. Other clients spell the keys differently.",
149+ mcpBase: "Base",
150+ yourTokens: "Your tokens",
151+ noTokens: "No tokens yet.",
152+ allBases: "All bases",
153+ nBases: (n: number) => `${n} base${n === 1 ? "" : "s"}`,
154+ lastUsed: (d: string) => `last used ${d}`,
155+ neverUsed: "never used",
156+ expiresOn: (d: string) => `expires ${d}`,
157+ noExpiry: "no expiry",
158+ createdOn: (d: string) => `created ${d}`,
159+ revoke: "Revoke",
160+ revokeConfirm: "Revoke?",
161+ revokedOn: (d: string) => `revoked ${d}`,
162+ tokenDone: "Done",
122163 roleNames: {
123164 owner: "Owner",
124165 admin: "Admin",
@@ -418,6 +459,11 @@
418459 custom: "Custom",
419460 github_issues: "GitHub issues",
420461 jira_issues: "Jira issues",
462+ s3: "S3 / MinIO",
463+ azure_blob: "Azure Blob",
464+ gcs: "Google Cloud Storage",
465+ webdav: "WebDAV",
466+ notion: "Notion",
421467 },
422468 sourceKindHints: {
423469 folder:
@@ -432,6 +478,24 @@
432478 "Syncs a repository's issues. **Each ticket, together with its state history**, becomes " +
433479 "one document — when it was opened, closed, relabelled, reassigned, all dated. " +
434480 "Without a token GitHub allows only 60 requests an hour.",
481+ s3:
482+ "Reads documents out of an S3 bucket, or anything speaking the same protocol " +
483+ "(MinIO, Ceph, R2). **Leave the endpoint empty for AWS**; fill it in for a " +
484+ "self-hosted one. Each object becomes a document dated by its last modification.",
485+ azure_blob:
486+ "Reads documents out of an Azure Blob container. Leave the endpoint empty for " +
487+ "Azure itself; fill it in for Azurite or a gateway.",
488+ gcs:
489+ "Reads documents out of a Google Cloud Storage bucket. The service account JSON " +
490+ "goes in whole — there is no file on the server to point at.",
491+ webdav:
492+ "Reads documents off a WebDAV share — Nextcloud, ownCloud, Synology, or anything " +
493+ "else speaking the protocol. Walks folders one level at a time; each file becomes " +
494+ "a document dated by its last modification.",
495+ notion:
496+ "Syncs the pages a Notion integration can see — share a page with the integration " +
497+ "and it appears here. Dated by when the page was last edited, which is the page's " +
498+ "own clock rather than ours.",
435499 api: "External systems push JSON documents here, authenticated with this source's own token.",
436500 custom:
437501 "Polls a URL you control on a schedule — your service returns JSON items and Utopia keeps them in sync.",
@@ -478,6 +542,21 @@
478542 repoField: "Repository (owner/name)",
479543 jiraUrlField: "Jira site URL",
480544 jiraProjectField: "Project key",
545+ s3BucketField: "Bucket",
546+ s3PrefixField: "Prefix (optional — without one the whole bucket is read)",
547+ s3EndpointField: "Endpoint (leave empty for AWS S3)",
548+ s3RegionField: "Region",
549+ s3KeyField: "Access key ID",
550+ s3SecretField: "Secret access key",
551+ azAccountField: "Storage account name",
552+ azKeyField: "Account key",
553+ gcsKeyField: "Service account JSON (paste the whole file)",
554+ davUrlField: "Server URL",
555+ davPathField: "Folder (optional — defaults to the root)",
556+ davUserField: "Username",
557+ davPassField: "Password",
558+ notionTokenField: "Internal integration token",
559+ notionQueryField: "Search term (optional — empty takes every shared page)",
481560 tokenField: "GitHub token (optional, never shown again)",
482561 includePullRequests: "Treat pull requests as tickets too",
483562 interval: "Sync schedule",
@@ -1149,6 +1228,7 @@
11491228 empty: "Nothing to review — the graph is clean.",
11501229 historyEmpty: "No merges yet.",
11511230 // 左栏分类导航
1231+ railPending: "Awaiting your nod",
11521232 railDuplicates: "Duplicates",
11531233 railConflicts: "Conflicts",
11541234 railUnconfirmed: "Unconfirmed",
@@ -1170,6 +1250,8 @@
11701250 "review.keep": "Kept apart",
11711251 "fact.confirm": "Confirmed",
11721252 "fact.reject": "Rejected",
1253+ "fact.nod_confirmed": "Confirmed a remembered fact",
1254+ "fact.nod_rejected": "Rejected a remembered fact",
11731255 "fact.close": "Closed",
11741256 "conflict.close_old": "Closed old",
11751257 "conflict.keep_both": "Kept both",
@@ -1231,6 +1313,9 @@
12311313 violationAsymmetry: "Both directions asserted",
12321314 violationCycle: "Cycle through the transitive chain",
12331315 violationFunctional: "Should hold one value, holds two",
1316+ /** 签名违规(#190 / #196):一条事实的主语或宾语落在谓词声明的类型之外——
1317+ * 抽取时会掰正,采纳与合并这两条路从前绕过了检查 */
1318+ violationSignature: "Subject or object outside the declared types",
12341319 violationVia: (p: string) => `via ${p}`,
12351320 violationPath: (n: number) => `${n} facts in the cycle`,
12361321 retractFact: "Data is wrong",
@@ -1251,6 +1336,19 @@
12511336 mappingsHint:
12521337 "Proposed mappings from a business concept to how it is computed. Confirm one and Ask uses it instead of guessing from the schema.",
12531338 mappingDerived: "derived",
1339+ // 记忆抽出、等人点头的事实(0015)
1340+ pending: "Awaiting your confirmation",
1341+ pendingHint:
1342+ "Facts extracted from what you asked the assistant to remember. Nothing here is in the graph yet: " +
1343+ "the sentence is kept, the facts wait for your nod. Confirm to add with the sentence as evidence; " +
1344+ "reject and it will not be proposed again.",
1345+ pendingNoPredicate: "The ontology has no relation for this; the word is the model's own.",
1346+ pendingNoPredicateChip: "no relation in ontology",
1347+ pendingSaidBy: (name: string) => `said by ${name}`,
1348+ nodCardTitle: (n: number) =>
1349+ n === 1
1350+ ? "One fact extracted from this. Confirm to add it to the graph, or reject."
1351+ : `${n} facts extracted from this. Confirm to add them to the graph, or reject.`,
12541352 lowConfidenceHint:
12551353 "Extracted with confidence below 75%. Confirm to trust, reject to remove from the graph (the ledger keeps the record).",
12561354 confirm: "Confirm",
modified web/src/i18n/zh.ts +89 −0
@@ -108,6 +108,45 @@
108108 deploymentAdmin: "部署管理员",
109109 openKb: "打开",
110110 kbSettingsBtn: "设置",
111+ tokensNav: "Agent 与令牌",
112+ tokensTitle: "个人访问令牌",
113+ tokensHint:
114+ "令牌让 agent 经 MCP 以你的身份使用 Utopia,权限永远不超过你自己。缺省只读,限定到你选的库,随时可在这里撤销。",
115+ newToken: "新令牌",
116+ tokenName: "名字",
117+ tokenNamePlaceholder: "我的笔记本",
118+ tokenScope: "范围",
119+ scopeRead: "只读",
120+ scopeWrite: "可写",
121+ scopeHint:
122+ "有效权限 = 你自己的角色 ∩ 这个范围。可写是上限不是授权:只读成员的可写令牌照样写不了。",
123+ tokenKbs: "知识库",
124+ kbsAllHint: "一个都不选 = 你能进的全部库。",
125+ tokenExpires: "过期",
126+ expiresDays: (n: number) => `${n} 天`,
127+ expiresNever: "不过期",
128+ issueToken: "创建令牌",
129+ issuedTitle: "现在就复制,之后不会再显示。",
130+ issuedHint: "Utopia 只保存它的哈希。丢了就在这里撤销,再建一枚。",
131+ copy: "复制",
132+ copied: "已复制",
133+ mcpTitle: "MCP 客户端配置",
134+ mcpHint:
135+ "适用于 Claude Code、Claude Desktop 及其它 Streamable HTTP 客户端。每个库有自己的端点,选 agent 要对话的那个库。别的客户端键名可能不同。",
136+ mcpBase: "库",
137+ yourTokens: "你的令牌",
138+ noTokens: "还没有令牌。",
139+ allBases: "全部库",
140+ nBases: (n: number) => `${n} 个库`,
141+ lastUsed: (d: string) => `最近使用 ${d}`,
142+ neverUsed: "从未使用",
143+ expiresOn: (d: string) => `${d} 过期`,
144+ noExpiry: "不过期",
145+ createdOn: (d: string) => `${d} 创建`,
146+ revoke: "撤销",
147+ revokeConfirm: "确认撤销?",
148+ revokedOn: (d: string) => `${d} 已撤销`,
149+ tokenDone: "完成",
111150 roleNames: {
112151 owner: "所有者",
113152 admin: "管理员",
@@ -386,6 +425,11 @@
386425 custom: "自定义",
387426 github_issues: "GitHub 工单",
388427 jira_issues: "Jira 工单",
428+ s3: "S3 / MinIO",
429+ azure_blob: "Azure Blob",
430+ gcs: "Google Cloud Storage",
431+ webdav: "WebDAV",
432+ notion: "Notion",
389433 },
390434 sourceKindHints: {
391435 folder:
@@ -399,6 +443,22 @@
399443 "同步一个仓库的工单。**每张工单连同它的状态变更史**成为一篇文档——" +
400444 "何时开出、何时关闭、标签与负责人怎么变的,都带着日期。未配令牌时" +
401445 "每小时只有 60 次请求配额。",
446+ s3:
447+ "从 S3 桶里读文档,或者任何说同一套协议的东西(MinIO、Ceph、R2)。" +
448+ "**端点留空就是 AWS**,填了就是自建。每个对象成为一篇文档," +
449+ "日期取它最后一次修改的时刻。",
450+ azure_blob:
451+ "从 Azure Blob 容器里读文档。用 Azure 本身就把端点留空," +
452+ "填了是指向 Azurite 或某个网关。",
453+ gcs:
454+ "从 Google Cloud Storage 桶里读文档。服务账号 JSON 整份贴进来——" +
455+ "服务器上没有那个文件可以指。",
456+ webdav:
457+ "从 WebDAV 网盘读文档——Nextcloud、ownCloud、群晖,以及一切说这套协议的。" +
458+ "逐层走目录,每个文件成为一篇文档,日期取它最后一次修改的时刻。",
459+ notion:
460+ "同步一个 Notion 集成能看见的页面——把页面分享给集成,它就会出现在这里。" +
461+ "日期取页面最后一次编辑的时刻,那是页面自己的时钟,不是我们抓它的时刻。",
402462 api: "外部系统把 JSON 文档推送到这里,用这个来源自己的令牌认证。",
403463 custom:
404464 "按计划轮询一个你控制的 URL——你的服务返回 JSON 条目,Utopia 保持同步。",
@@ -444,6 +504,21 @@
444504 repoField: "仓库(owner/name)",
445505 jiraUrlField: "Jira 地址",
446506 jiraProjectField: "项目 key",
507+ s3BucketField: "桶名",
508+ s3PrefixField: "前缀(可选——不填则读整个桶)",
509+ s3EndpointField: "端点(用 AWS S3 就留空)",
510+ s3RegionField: "区域",
511+ s3KeyField: "Access Key ID",
512+ s3SecretField: "Secret Access Key",
513+ azAccountField: "存储账号名",
514+ azKeyField: "账号密钥",
515+ gcsKeyField: "服务账号 JSON(整个文件贴进来)",
516+ davUrlField: "服务器地址",
517+ davPathField: "目录(可选——默认从根开始)",
518+ davUserField: "用户名",
519+ davPassField: "密码",
520+ notionTokenField: "内部集成令牌",
521+ notionQueryField: "搜索词(可选——留空则取全部已分享页面)",
447522 tokenField: "GitHub 令牌(可选,不再显示)",
448523 includePullRequests: "把 PR 也当工单收进来",
449524 interval: "同步计划",
@@ -1032,6 +1107,7 @@
10321107 tabHistory: "历史",
10331108 empty: "没有待审阅的——图谱是干净的。",
10341109 historyEmpty: "还没有合并记录。",
1110+ railPending: "等你点头",
10351111 railDuplicates: "重复项",
10361112 railConflicts: "冲突",
10371113 railUnconfirmed: "未确认",
@@ -1052,6 +1128,8 @@
10521128 "review.keep": "保持分开",
10531129 "fact.confirm": "已确认",
10541130 "fact.reject": "已驳回",
1131+ "fact.nod_confirmed": "已确认一条记忆事实",
1132+ "fact.nod_rejected": "已驳回一条记忆事实",
10551133 "fact.close": "已闭合",
10561134 "conflict.close_old": "闭合旧的",
10571135 "conflict.keep_both": "两条都留",
@@ -1109,6 +1187,7 @@
11091187 violationAsymmetry: "两个方向都断言了",
11101188 violationCycle: "传递链绕成了环",
11111189 violationFunctional: "该只有一个值,却有两个",
1190+ violationSignature: "主语或宾语不在关系声明的类型里",
11121191 violationVia: (p: string) => `依据 ${p}`,
11131192 violationPath: (n: number) => `环上 ${n} 条事实`,
11141193 retractFact: "数据错了",
@@ -1128,6 +1207,16 @@
11281207 mappingsHint:
11291208 "从业务概念到「这个数怎么算」的提议。确认之后问数直接用这个口径,而不是每次从 schema 猜。",
11301209 mappingDerived: "派生",
1210+ // 记忆抽出、等人点头的事实(0015)
1211+ pending: "等你确认",
1212+ pendingHint:
1213+ "从你让助手记住的话里抽出的事实。这里的东西都还没进图:那句话已经存下,事实等你点头。" +
1214+ "确认后以那句话为证据进账本;驳回后不会再被提议。",
1215+ pendingNoPredicate: "本体里没有这个关系,这个词是模型自己的说法。",
1216+ pendingNoPredicateChip: "本体里没有这个关系",
1217+ pendingSaidBy: (name: string) => `${name} 说的`,
1218+ nodCardTitle: (n: number) =>
1219+ n === 1 ? "从这句话里抽出 1 条事实。确认进图,或驳回。" : `从这句话里抽出 ${n} 条事实。确认进图,或驳回。`,
11311220 lowConfidenceHint:
11321221 "抽取时置信度低于 75%。确认表示采信,驳回表示从图谱移除(台账仍留有记录)。",
11331222 confirm: "确认",
modified web/src/pages/AccountShell.tsx +5 −1
@@ -3,7 +3,7 @@
33 import { useQuery } from "@tanstack/react-query";
44 import { Link, Outlet, useNavigate } from "@tanstack/react-router";
55 import { usePageTitle } from "../useTitle";
6-import { BookMarked, ShieldCheck, UserRound } from "lucide-react";
6+import { BookMarked, KeyRound, ShieldCheck, UserRound } from "lucide-react";
77 import { api, ApiError } from "../api";
88 import { S } from "../i18n";
99 import { GithubMark, RAIL_CLS, SectionMark } from "../ui";
@@ -81,6 +81,10 @@
8181 <BookMarked size={14} />
8282 {S.account.kbsNav}
8383 </Link>
84+ <Link to="/account/tokens" className={rail} activeProps={{ className: railActive }}>
85+ <KeyRound size={14} />
86+ {S.account.tokensNav}
87+ </Link>
8488 {me.data.is_admin && (
8589 <Link to="/admin" className={rail} activeProps={{ className: railActive }}>
8690 <ShieldCheck size={14} />
modified web/src/pages/Chat.tsx +10 −4
@@ -36,6 +36,7 @@
3636 import { useKb, useKbId } from "../kb";
3737 import { DangerConfirm, RAIL_CLS } from "../ui";
3838 import { liveAnswer, type Turn } from "../liveAnswer";
39+import { NodCard } from "./PendingFacts";
3940
4041 /* `Turn` 定义在 liveAnswer 里:进行中的那一次也是一串 Turn,
4142 而它必须活得比这个组件长(见那个文件顶上的说明) */
@@ -705,10 +706,15 @@
705706 className="my-2.5 space-y-1 border-l border-white/15 pl-2.5"
706707 >
707708 {seg.steps.map((s, j) => (
708- <div key={j} className="flex items-center gap-1.5 text-xs">
709- <span className="text-neutral-600">{stepIcon(s.kind)}</span>
710- <span className="text-neutral-400 truncate">{s.label}</span>
711- <span className="text-neutral-600 shrink-0">· {s.detail}</span>
709+ <div key={j}>
710+ <div className="flex items-center gap-1.5 text-xs">
711+ <span className="text-neutral-600">{stepIcon(s.kind)}</span>
712+ <span className="text-neutral-400 truncate">{s.label}</span>
713+ <span className="text-neutral-600 shrink-0">· {s.detail}</span>
714+ </div>
715+ {/* remember 那一步后面跟着确认卡(0015):这句话抽出的事实先等人点头。
716+ 抽取是异步的,卡片在任务完成时才长出来;回放时按同一个 chunk 重画 */}
717+ {s.chunk_id && <NodCard kbId={kbId} chunkId={s.chunk_id} />}
712718 </div>
713719 ))}
714720 </div>
modified web/src/pages/Library.tsx +233 −3
@@ -1270,6 +1270,11 @@
12701270 | "api"
12711271 | "github_issues"
12721272 | "jira_issues"
1273+ | "s3"
1274+ | "azure_blob"
1275+ | "gcs"
1276+ | "webdav"
1277+ | "notion"
12731278 >("folder");
12741279 const [name, setName] = useState("");
12751280 const [icon, setIcon] = useState<string | null>(null);
@@ -1280,6 +1285,21 @@
12801285 const [repo, setRepo] = useState("");
12811286 const [jiraUrl, setJiraUrl] = useState("");
12821287 const [jiraProject, setJiraProject] = useState("");
1288+ const [s3Bucket, setS3Bucket] = useState("");
1289+ const [s3Prefix, setS3Prefix] = useState("");
1290+ const [s3Endpoint, setS3Endpoint] = useState("");
1291+ const [s3Region, setS3Region] = useState("");
1292+ const [s3Key, setS3Key] = useState("");
1293+ const [s3Secret, setS3Secret] = useState("");
1294+ const [azAccount, setAzAccount] = useState("");
1295+ const [azKey, setAzKey] = useState("");
1296+ const [gcsKey, setGcsKey] = useState("");
1297+ const [davUrl, setDavUrl] = useState("");
1298+ const [davPath, setDavPath] = useState("");
1299+ const [davUser, setDavUser] = useState("");
1300+ const [davPass, setDavPass] = useState("");
1301+ const [notionToken, setNotionToken] = useState("");
1302+ const [notionQuery, setNotionQuery] = useState("");
12831303 // PR 在 GitHub 的模型里也是工单。默认不收——问「工单」要的是工单;
12841304 // 但有些仓库的决策记录实际写在 PR 描述里,所以给个开关
12851305 const [includePrs, setIncludePrs] = useState(false);
@@ -1293,7 +1313,12 @@
12931313 kind === "rss" ||
12941314 kind === "custom" ||
12951315 kind === "github_issues" ||
1296- kind === "jira_issues";
1316+ kind === "jira_issues" ||
1317+ kind === "s3" ||
1318+ kind === "azure_blob" ||
1319+ kind === "gcs" ||
1320+ kind === "webdav" ||
1321+ kind === "notion";
12971322
12981323 const create = useMutation({
12991324 mutationFn: () => {
@@ -1319,7 +1344,48 @@
13191344 project: jiraProject.trim(),
13201345 ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
13211346 }
1322- : {};
1347+ : kind === "s3"
1348+ ? {
1349+ bucket: s3Bucket.trim(),
1350+ ...(s3Prefix.trim() ? { prefix: s3Prefix.trim() } : {}),
1351+ // 端点留空 = 公有云 S3;填了就是自建,后端据此走 path-style
1352+ ...(s3Endpoint.trim() ? { endpoint: s3Endpoint.trim() } : {}),
1353+ ...(s3Region.trim() ? { region: s3Region.trim() } : {}),
1354+ ...(s3Key.trim() ? { access_key_id: s3Key.trim() } : {}),
1355+ ...(s3Secret.trim() ? { secret_access_key: s3Secret.trim() } : {}),
1356+ }
1357+ : kind === "azure_blob"
1358+ ? {
1359+ bucket: s3Bucket.trim(),
1360+ ...(s3Prefix.trim() ? { prefix: s3Prefix.trim() } : {}),
1361+ ...(s3Endpoint.trim() ? { endpoint: s3Endpoint.trim() } : {}),
1362+ ...(azAccount.trim() ? { account_name: azAccount.trim() } : {}),
1363+ ...(azKey.trim() ? { account_key: azKey.trim() } : {}),
1364+ }
1365+ : kind === "gcs"
1366+ ? {
1367+ bucket: s3Bucket.trim(),
1368+ ...(s3Prefix.trim() ? { prefix: s3Prefix.trim() } : {}),
1369+ ...(s3Endpoint.trim() ? { endpoint: s3Endpoint.trim() } : {}),
1370+ ...(gcsKey.trim()
1371+ ? { service_account_key: gcsKey.trim() }
1372+ : {}),
1373+ }
1374+ : kind === "webdav"
1375+ ? {
1376+ base_url: davUrl.trim(),
1377+ ...(davPath.trim() ? { path: davPath.trim() } : {}),
1378+ ...(davUser.trim() ? { username: davUser.trim() } : {}),
1379+ ...(davPass ? { password: davPass } : {}),
1380+ }
1381+ : kind === "notion"
1382+ ? {
1383+ token: notionToken.trim(),
1384+ ...(notionQuery.trim()
1385+ ? { query: notionQuery.trim() }
1386+ : {}),
1387+ }
1388+ : {};
13231389 return api.createSource(kbId, {
13241390 kind,
13251391 name: name.trim(),
@@ -1341,7 +1407,13 @@
13411407 ? feedUrl.trim()
13421408 : kind === "custom"
13431409 ? endpoint.trim()
1344- : true);
1410+ : kind === "notion"
1411+ ? notionToken.trim()
1412+ : kind === "webdav"
1413+ ? davUrl.trim()
1414+ : kind === "s3" || kind === "azure_blob" || kind === "gcs"
1415+ ? s3Bucket.trim()
1416+ : true);
13451417
13461418 // 注意用 div 而非 label:label 会把 :hover/click 转发给内部第一个可标记控件
13471419 //(button 也算),导致图标网格/日程选择器悬停时第一个按钮常亮
@@ -1377,6 +1449,11 @@
13771449 "rss",
13781450 "github_issues",
13791451 "jira_issues",
1452+ "s3",
1453+ "azure_blob",
1454+ "gcs",
1455+ "webdav",
1456+ "notion",
13801457 "api",
13811458 "custom",
13821459 ] as const
@@ -1520,6 +1597,159 @@
15201597 )}
15211598 </>
15221599 )}
1600+ {(kind === "s3" || kind === "azure_blob" || kind === "gcs") && (
1601+ <>
1602+ {field(
1603+ S.library.s3BucketField,
1604+ <input
1605+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1606+ placeholder="documents"
1607+ value={s3Bucket}
1608+ onChange={(e) => setS3Bucket(e.target.value)}
1609+ />,
1610+ )}
1611+ {field(
1612+ S.library.s3PrefixField,
1613+ <input
1614+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1615+ placeholder="reports/2026/"
1616+ value={s3Prefix}
1617+ onChange={(e) => setS3Prefix(e.target.value)}
1618+ />,
1619+ )}
1620+ {field(
1621+ S.library.s3EndpointField,
1622+ <input
1623+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1624+ placeholder="http://minio.internal:9000"
1625+ value={s3Endpoint}
1626+ onChange={(e) => setS3Endpoint(e.target.value)}
1627+ />,
1628+ )}
1629+ {field(
1630+ S.library.s3RegionField,
1631+ <input
1632+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1633+ placeholder="us-east-1"
1634+ value={s3Region}
1635+ onChange={(e) => setS3Region(e.target.value)}
1636+ />,
1637+ )}
1638+ {kind === "s3" && (
1639+ <>
1640+ {field(
1641+ S.library.s3KeyField,
1642+ <input
1643+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1644+ value={s3Key}
1645+ onChange={(e) => setS3Key(e.target.value)}
1646+ />,
1647+ )}
1648+ {field(
1649+ S.library.s3SecretField,
1650+ <input
1651+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1652+ type="password"
1653+ value={s3Secret}
1654+ onChange={(e) => setS3Secret(e.target.value)}
1655+ />,
1656+ )}
1657+ </>
1658+ )}
1659+ {kind === "azure_blob" && (
1660+ <>
1661+ {field(
1662+ S.library.azAccountField,
1663+ <input
1664+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1665+ value={azAccount}
1666+ onChange={(e) => setAzAccount(e.target.value)}
1667+ />,
1668+ )}
1669+ {field(
1670+ S.library.azKeyField,
1671+ <input
1672+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1673+ type="password"
1674+ value={azKey}
1675+ onChange={(e) => setAzKey(e.target.value)}
1676+ />,
1677+ )}
1678+ </>
1679+ )}
1680+ {kind === "gcs" &&
1681+ field(
1682+ S.library.gcsKeyField,
1683+ <textarea
1684+ className="input-dark w-full px-3 py-2 text-sm font-mono h-24"
1685+ placeholder='{"type":"service_account",...}'
1686+ value={gcsKey}
1687+ onChange={(e) => setGcsKey(e.target.value)}
1688+ />,
1689+ )}
1690+ </>
1691+ )}
1692+ {kind === "webdav" && (
1693+ <>
1694+ {field(
1695+ S.library.davUrlField,
1696+ <input
1697+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1698+ placeholder="https://cloud.example.com/remote.php/dav/files/alice"
1699+ value={davUrl}
1700+ onChange={(e) => setDavUrl(e.target.value)}
1701+ />,
1702+ )}
1703+ {field(
1704+ S.library.davPathField,
1705+ <input
1706+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1707+ placeholder="/Documents"
1708+ value={davPath}
1709+ onChange={(e) => setDavPath(e.target.value)}
1710+ />,
1711+ )}
1712+ {field(
1713+ S.library.davUserField,
1714+ <input
1715+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1716+ value={davUser}
1717+ onChange={(e) => setDavUser(e.target.value)}
1718+ />,
1719+ )}
1720+ {field(
1721+ S.library.davPassField,
1722+ <input
1723+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1724+ type="password"
1725+ value={davPass}
1726+ onChange={(e) => setDavPass(e.target.value)}
1727+ />,
1728+ )}
1729+ </>
1730+ )}
1731+ {kind === "notion" && (
1732+ <>
1733+ {field(
1734+ S.library.notionTokenField,
1735+ <input
1736+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1737+ type="password"
1738+ placeholder="ntn_..."
1739+ value={notionToken}
1740+ onChange={(e) => setNotionToken(e.target.value)}
1741+ />,
1742+ )}
1743+ {field(
1744+ S.library.notionQueryField,
1745+ <input
1746+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1747+ value={notionQuery}
1748+ onChange={(e) => setNotionQuery(e.target.value)}
1749+ />,
1750+ )}
1751+ </>
1752+ )}
15231753 {kind === "github_issues" && (
15241754 <>
15251755 {field(
added web/src/pages/PendingFacts.tsx +150 −0
@@ -0,0 +1,150 @@
1+/* 等人点头的事实(docs/decisions/0015)。
2+ 一句 remember 抽出的三元组先进待确认队列,不上图;人在这里点头它才进账本。
3+ **原句在上,三元组在下**:只列三元组等于要人凭空判断它对不对——
4+ 实测里 `Acme --?--> 深圳` 那条,人一看原句就知道该拒。
5+ 两处共用同一行组件:Review 页的「待确认」一档,与 Chat 里跟在 remember 步骤后面的那张卡。 */
6+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
7+import { api, type PendingFactItem } from "../api";
8+import { S } from "../i18n";
9+import { toast } from "../toast";
10+
11+function ym(iso: string | null): string | null {
12+ return iso ? iso.slice(0, 7) : null;
13+}
14+
15+/** 记忆落库时正文前面带着 `[YYYY-MM-DD HH:MM] `(`memory::append_episode` 加的时间戳)。
16+ * 卡片上要的是那句话本身,时间戳是索引用的,剥掉 */
17+function sentence(quote: string): string {
18+ return quote.replace(/^\[\d{4}-\d{2}-\d{2}(?: \d{2}:\d{2})?\]\s*/, "");
19+}
20+
21+function objectText(f: PendingFactItem): string {
22+ if (f.object_name) return f.object_name;
23+ const v = f.object_value;
24+ if (!v) return "?";
25+ if (v.summary) return v.summary;
26+ const val = v.value === undefined || v.value === null ? "?" : String(v.value);
27+ return v.unit ? `${val} ${v.unit}` : val;
28+}
29+
30+/** 点头是写图的动作,Editor 起步——与服务端 `require_kb(Role::Editor)` 同一口径。
31+ * Viewer 看得见提议、看不见按钮:按钮亮着却点不动,等于让人猜自己有没有权限。
32+ * 查询键与 Library 页共用(`kbOne`),不多打一次接口 */
33+export function useCanDecide(kbId: string | undefined): boolean {
34+ const kbDetail = useQuery({
35+ queryKey: ["kbOne", kbId],
36+ queryFn: () => api.kbDetail(kbId!),
37+ enabled: !!kbId,
38+ });
39+ return ["editor", "admin", "owner"].includes(kbDetail.data?.my_role ?? "");
40+}
41+
42+export function PendingFactRow({
43+ fact,
44+ busy,
45+ canDecide,
46+ onConfirm,
47+ onReject,
48+}: {
49+ fact: PendingFactItem;
50+ busy: boolean;
51+ canDecide: boolean;
52+ onConfirm: () => void;
53+ onReject: () => void;
54+}) {
55+ const from = ym(fact.valid_from);
56+ const to = ym(fact.valid_to);
57+ const range = from || to ? `${from ?? "…"} → ${to ?? S.review.ongoing}` : null;
58+ return (
59+ <div className="glass rounded-xl p-4">
60+ {/* 原句先出。它是人自己说的,判断的依据就是它 */}
61+ <p className="text-xs text-neutral-400 italic">“{sentence(fact.quote)}”</p>
62+ <div className="mt-2.5 flex items-center gap-2 flex-wrap">
63+ <span className="text-sm font-medium text-white">{fact.subject_name}</span>
64+ <span className="text-xs text-neutral-500">
65+ —{" "}
66+ {fact.predicate_label ? (
67+ <span>{fact.predicate_label}</span>
68+ ) : (
69+ /* 本体里没有这个关系:显示原话,斜体标明它不是词表里的词(0010) */
70+ <span
71+ className="italic text-neutral-600"
72+ title={S.review.pendingNoPredicate}
73+ >
74+ {fact.proposed_predicate ?? S.graph.unknownPredicate}
75+ </span>
76+ )}{" "}
77+ →
78+ </span>
79+ <span className="text-sm font-medium text-white">{objectText(fact)}</span>
80+ {range && <span className="text-xs text-neutral-500">({range})</span>}
81+ {!fact.predicate_label && (
82+ <span className="u-chip u-chip-warn ml-auto">{S.review.pendingNoPredicateChip}</span>
83+ )}
84+ </div>
85+ <div className="mt-3 flex items-center gap-2">
86+ {fact.proposed_by_name && (
87+ <span className="text-[11px] text-neutral-600">
88+ {S.review.pendingSaidBy(fact.proposed_by_name)}
89+ </span>
90+ )}
91+ {canDecide && (
92+ <div className="ml-auto flex gap-2">
93+ <button
94+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
95+ disabled={busy}
96+ onClick={onReject}
97+ >
98+ {S.review.reject}
99+ </button>
100+ <button
101+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
102+ disabled={busy}
103+ onClick={onConfirm}
104+ >
105+ {S.review.confirm}
106+ </button>
107+ </div>
108+ )}
109+ </div>
110+ </div>
111+ );
112+}
113+
114+/** 跟在 remember 步骤后面的确认卡。
115+ * 抽取是异步的,卡片在任务完成时才长出来(SSE `pending` 事件让查询失效重取);
116+ * 回放旧会话时同样按 chunk 取——还有没点头的就照样显示,都处理完了就不占地方。 */
117+export function NodCard({ kbId, chunkId }: { kbId: string; chunkId: string }) {
118+ const queryClient = useQueryClient();
119+ const canDecide = useCanDecide(kbId);
120+ const q = useQuery({
121+ queryKey: ["pending", kbId, chunkId],
122+ queryFn: () => api.pendingForChunk(kbId, chunkId),
123+ });
124+ const decide = useMutation({
125+ mutationFn: ({ id, action }: { id: string; action: "confirm" | "reject" }) =>
126+ api.decidePending(kbId, id, action),
127+ onError: (e: Error) => toast.error(e.message),
128+ onSettled: () => {
129+ queryClient.invalidateQueries({ queryKey: ["pending", kbId] });
130+ queryClient.invalidateQueries({ queryKey: ["review", kbId] });
131+ },
132+ });
133+ const items = q.data?.items ?? [];
134+ if (items.length === 0) return null;
135+ return (
136+ <div className="my-2 space-y-2">
137+ <div className="text-xs text-neutral-500">{S.review.nodCardTitle(items.length)}</div>
138+ {items.map((f) => (
139+ <PendingFactRow
140+ key={f.id}
141+ fact={f}
142+ busy={decide.isPending && decide.variables?.id === f.id}
143+ canDecide={canDecide}
144+ onConfirm={() => decide.mutate({ id: f.id, action: "confirm" })}
145+ onReject={() => decide.mutate({ id: f.id, action: "reject" })}
146+ />
147+ ))}
148+ </div>
149+ );
150+}
modified web/src/pages/Review.tsx +56 −0
@@ -10,10 +10,12 @@
1010 type ConflictItem,
1111 type FactReviewItem,
1212 type MergeLog,
13+ type PendingFactItem,
1314 type ReviewHistoryEvent,
1415 type ReviewItem,
1516 type ReviewSide,
1617 } from "../api";
18+import { PendingFactRow, useCanDecide } from "./PendingFacts";
1719 import { S } from "../i18n";
1820 import { useKb, useKbId } from "../kb";
1921 import { Chip, type ChipTone, Pager, RAIL_CLS, cn } from "../ui";
@@ -543,6 +545,7 @@
543545 asymmetry: S.review.violationAsymmetry,
544546 cycle: S.review.violationCycle,
545547 functional: S.review.violationFunctional,
548+ signature: S.review.violationSignature,
546549 }[v.kind];
547550 // 自反那一类两条事实是同一条——显示一遍就够,显示两遍像个 bug
548551 const single = v.left_fact === v.right_fact;
@@ -597,6 +600,9 @@
597600 /* ---------- 页面:左栏分类 + 单类内容区 ---------- */
598601
599602 type Sel =
603+ // 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话,
604+ // 而且在这一档里的东西**还没进图**——别处每一档审的都是已经在图上的
605+ | "pending"
600606 | "duplicates"
601607 | "conflicts"
602608 | "unconfirmed"
@@ -611,6 +617,7 @@
611617
612618 /** 走服务端分页的那几档(决策台账另有自己的接口) */
613619 const QUEUE_FETCHED: ReviewQueue[] = [
620+ "pending",
614621 "duplicates",
615622 "conflicts",
616623 "unconfirmed",
@@ -621,6 +628,7 @@
621628 ];
622629
623630 const QUEUE_ORDER: Sel[] = [
631+ "pending",
624632 "duplicates",
625633 "conflicts",
626634 "unconfirmed",
@@ -629,6 +637,7 @@
629637 "defects",
630638 ];
631639 const PAGE_SIZE: Record<Sel, number> = {
640+ pending: FACT_PAGE,
632641 duplicates: DUP_PAGE,
633642 conflicts: CONFLICT_PAGE,
634643 unconfirmed: FACT_PAGE,
@@ -749,6 +758,22 @@
749758 : api.rejectFact(kb!.id, id),
750759 onSettled: invalidate,
751760 });
761+ // 等人点头的事实(0015):确认进账本,驳回记进 rejected_facts
762+ // 点头是写图的动作:Viewer 看得见提议、看不见按钮(与服务端 Editor 门槛同口径)
763+ const canDecidePending = useCanDecide(kb?.id);
764+ const pendingAction = useMutation({
765+ mutationFn: ({
766+ id,
767+ action,
768+ }: {
769+ id: string;
770+ action: "confirm" | "reject";
771+ }) => api.decidePending(kb!.id, id, action),
772+ onSettled: () => {
773+ invalidate();
774+ queryClient.invalidateQueries({ queryKey: ["pending", kb?.id] });
775+ },
776+ });
752777 const defectAction = useMutation({
753778 mutationFn: ({
754779 id,
@@ -804,6 +829,7 @@
804829 // mappings 不是本页的一档(审批在「数据映射」页),但计数照收:
805830 // 收件箱该说「有几条等你」
806831 const counts: Record<Sel | "mappings", number> = {
832+ pending: c?.pending ?? 0,
807833 duplicates: c?.duplicates ?? 0,
808834 conflicts: c?.conflicts ?? 0,
809835 unconfirmed: c?.unconfirmed ?? 0,
@@ -817,6 +843,7 @@
817843 // 当前这一档的一页。**服务端已经切好了**,这里只按档收窄类型——
818844 // 收窄错了会在渲染时露馅,而不是悄悄显示空列表
819845 const rows = review.data?.queue === queueSel ? (review.data.items ?? []) : [];
846+ const asPending = () => rows as PendingFactItem[];
820847 const asDuplicates = () => rows as ReviewItem[];
821848 const asFacts = () => rows as FactReviewItem[];
822849 const asConflicts = () => rows as ConflictItem[];
@@ -841,6 +868,7 @@
841868 const isQueueSel = QUEUE_ORDER.includes(active);
842869
843870 const SECTION: Record<Sel, { title: string; hint: string | null }> = {
871+ pending: { title: S.review.pending, hint: S.review.pendingHint },
844872 duplicates: { title: S.review.duplicates, hint: S.review.duplicatesHint },
845873 conflicts: { title: S.review.conflicts, hint: S.review.conflictsHint },
846874 unconfirmed: {
@@ -869,6 +897,12 @@
869897 <aside className={`${RAIL_CLS} flex flex-col overflow-y-auto u-scroll`}>
870898 <RailHeader label={S.review.tabQueue} />
871899 <div className="px-2 space-y-0.5">
900+ <RailItem
901+ active={active === "pending"}
902+ label={S.review.railPending}
903+ count={counts.pending}
904+ onClick={() => select("pending")}
905+ />
872906 <RailItem
873907 active={active === "duplicates"}
874908 label={S.review.railDuplicates}
@@ -1032,6 +1066,28 @@
10321066 </div>
10331067 )}
10341068
1069+ {active === "pending" && counts.pending > 0 && (
1070+ <div className="space-y-3">
1071+ {asPending().map((fact) => (
1072+ <PendingFactRow
1073+ key={fact.id}
1074+ fact={fact}
1075+ canDecide={canDecidePending}
1076+ busy={
1077+ pendingAction.isPending &&
1078+ pendingAction.variables?.id === fact.id
1079+ }
1080+ onConfirm={() =>
1081+ pendingAction.mutate({ id: fact.id, action: "confirm" })
1082+ }
1083+ onReject={() =>
1084+ pendingAction.mutate({ id: fact.id, action: "reject" })
1085+ }
1086+ />
1087+ ))}
1088+ </div>
1089+ )}
1090+
10351091 {active === "lowconf" && counts.lowconf > 0 && (
10361092 <div className="space-y-3">
10371093 {asFacts().map((fact) => (
modified web/src/pages/SourcesRail.tsx +10 −0
@@ -67,6 +67,11 @@
6767 custom: Puzzle,
6868 github_issues: CircleDot,
6969 jira_issues: SquareKanban,
70+ s3: HardDrive,
71+ azure_blob: Cloud,
72+ gcs: Cloud,
73+ webdav: FolderOpen,
74+ notion: Notebook,
7075 memory: Brain,
7176 upload: Upload,
7277 } as const;
@@ -78,6 +83,11 @@
7883 "custom",
7984 "github_issues",
8085 "jira_issues",
86+ "s3",
87+ "azure_blob",
88+ "gcs",
89+ "webdav",
90+ "notion",
8191 ]);
8292
8393 export const SYNC_DOT: Record<SourceView["last_sync_status"], string> = {
added web/src/pages/Tokens.tsx +359 −0
@@ -0,0 +1,359 @@
1+/* 个人访问令牌页(docs/decisions/0014,0016 的 A2)。
2+ 令牌属于人、以人的身份行事:有效权限 = 角色 ∩ scope,`kb_ids` 只收窄不授权。
3+ 服务端三个端点早就在(发放 / 列表 / 撤销),缺的只是这一页——没有它,
4+ MCP 对用户就是「有 API、配不了」。
5+ 明文只在发放那一次的响应里出现,所以这一页的重心是那一刻:把令牌和一段可复制的
6+ 客户端配置一起端出来,人复制完点「完成」,之后列表里只剩前缀。 */
7+import { useMemo, useState } from "react";
8+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
9+import { Check, Copy, KeyRound } from "lucide-react";
10+import { api, type TokenView } from "../api";
11+import { S } from "../i18n";
12+import { useKb } from "../kb";
13+import { Chip, Loading } from "../ui";
14+import { toast } from "../toast";
15+
16+const ymd = (iso: string) => iso.slice(0, 10);
17+const EXPIRY_CHOICES = [30, 90, 365, 0] as const;
18+
19+function copyText(text: string) {
20+ navigator.clipboard
21+ ?.writeText(text)
22+ .then(() => toast.success(S.account.copied))
23+ .catch(() => {});
24+}
25+
26+/** Claude Code / Claude Desktop 一族的 Streamable HTTP 写法。每个库一个端点(0014:
27+ * 令牌限定到库,端点也按库分),所以片段里要把库选出来 */
28+function mcpSnippet(kbId: string, kbName: string, token: string): string {
29+ const slug = kbName
30+ .toLowerCase()
31+ .replace(/[^a-z0-9]+/g, "-")
32+ .replace(/^-+|-+$/g, "") || "kb";
33+ const cfg = {
34+ mcpServers: {
35+ [`utopia-${slug}`]: {
36+ type: "http",
37+ url: `${window.location.origin}/api/v1/kbs/${kbId}/mcp`,
38+ headers: { Authorization: `Bearer ${token}` },
39+ },
40+ },
41+ };
42+ return JSON.stringify(cfg, null, 2);
43+}
44+
45+function CopyButton({ text, small }: { text: string; small?: boolean }) {
46+ const [done, setDone] = useState(false);
47+ return (
48+ <button
49+ className={`u-btn u-btn-ghost ${small ? "px-2 py-1 text-[11px]" : "px-3 py-1.5 text-xs"} flex items-center gap-1.5`}
50+ onClick={() => {
51+ copyText(text);
52+ setDone(true);
53+ setTimeout(() => setDone(false), 1500);
54+ }}
55+ >
56+ {done ? <Check size={12} /> : <Copy size={12} />}
57+ {done ? S.account.copied : S.account.copy}
58+ </button>
59+ );
60+}
61+
62+/** 刚发出来的那一枚:明文 + 配置片段,关掉就再也看不到 */
63+function IssuedPanel({
64+ token,
65+ info,
66+ kbs,
67+ onDone,
68+}: {
69+ token: string;
70+ info: TokenView;
71+ kbs: { id: string; name: string }[];
72+ onDone: () => void;
73+}) {
74+ // 片段默认指向令牌限定的第一个库;没限定就取列表第一个
75+ const candidates = info.kb_ids?.length
76+ ? kbs.filter((k) => info.kb_ids!.includes(k.id))
77+ : kbs;
78+ const [kbId, setKbId] = useState(candidates[0]?.id ?? kbs[0]?.id ?? "");
79+ const kb = kbs.find((k) => k.id === kbId);
80+ const snippet = kb ? mcpSnippet(kb.id, kb.name, token) : "";
81+ return (
82+ <div className="glass rounded-2xl p-5 mb-4 border border-[var(--u-warn)]/40">
83+ <div className="text-[13px] font-medium text-neutral-100">{S.account.issuedTitle}</div>
84+ <p className="mt-1 text-xs text-neutral-500">{S.account.issuedHint}</p>
85+ <div className="mt-3 flex items-center gap-2">
86+ <code className="flex-1 min-w-0 truncate rounded-lg bg-black/40 px-3 py-2 font-mono text-[12px] text-neutral-200">
87+ {token}
88+ </code>
89+ <CopyButton text={token} />
90+ </div>
91+
92+ <div className="mt-5 flex items-baseline justify-between gap-3 flex-wrap">
93+ <div className="text-[13px] font-medium text-neutral-200">{S.account.mcpTitle}</div>
94+ {candidates.length > 1 && (
95+ <label className="flex items-center gap-2 text-xs text-neutral-500">
96+ {S.account.mcpBase}
97+ <select
98+ className="input-dark px-2 py-1 text-xs"
99+ value={kbId}
100+ onChange={(e) => setKbId(e.target.value)}
101+ >
102+ {candidates.map((k) => (
103+ <option key={k.id} value={k.id}>
104+ {k.name}
105+ </option>
106+ ))}
107+ </select>
108+ </label>
109+ )}
110+ </div>
111+ <p className="mt-1 text-xs text-neutral-500">{S.account.mcpHint}</p>
112+ <div className="mt-2 relative">
113+ <pre className="rounded-lg bg-black/40 px-3 py-2 font-mono text-[11.5px] text-neutral-300 overflow-x-auto u-scroll">
114+ {snippet}
115+ </pre>
116+ <div className="absolute top-1.5 right-1.5">
117+ <CopyButton text={snippet} small />
118+ </div>
119+ </div>
120+
121+ <div className="mt-4 flex justify-end">
122+ <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onDone}>
123+ {S.account.tokenDone}
124+ </button>
125+ </div>
126+ </div>
127+ );
128+}
129+
130+function TokenRow({
131+ t,
132+ kbName,
133+ busy,
134+ onRevoke,
135+}: {
136+ t: TokenView;
137+ kbName: (id: string) => string;
138+ busy: boolean;
139+ onRevoke: () => void;
140+}) {
141+ // 撤销不可撤回,但代价只是重发一枚——轻确认(二次点击),不做打字解锁
142+ const [arm, setArm] = useState(false);
143+ const revoked = !!t.revoked_at;
144+ const bases = t.kb_ids?.length
145+ ? t.kb_ids.map(kbName).join(" · ")
146+ : S.account.allBases;
147+ return (
148+ <div className={`glass rounded-xl px-4 py-3 ${revoked ? "opacity-55" : ""}`}>
149+ <div className="flex items-center gap-2 flex-wrap">
150+ <KeyRound size={13} className="text-neutral-500 shrink-0" />
151+ <span className="text-sm font-medium text-neutral-100">{t.name}</span>
152+ <code className="font-mono text-[11px] text-neutral-500">{t.token_prefix}…</code>
153+ <Chip tone={t.scope === "write" ? "warn" : "neutral"}>
154+ {t.scope === "write" ? S.account.scopeWrite : S.account.scopeRead}
155+ </Chip>
156+ {revoked && <Chip tone="danger">{S.account.revokedOn(ymd(t.revoked_at!))}</Chip>}
157+ {!revoked && (
158+ <div className="ml-auto flex gap-2">
159+ {arm ? (
160+ <button
161+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
162+ disabled={busy}
163+ onClick={onRevoke}
164+ onBlur={() => setArm(false)}
165+ >
166+ {S.account.revokeConfirm}
167+ </button>
168+ ) : (
169+ <button
170+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
171+ disabled={busy}
172+ onClick={() => setArm(true)}
173+ >
174+ {S.account.revoke}
175+ </button>
176+ )}
177+ </div>
178+ )}
179+ </div>
180+ <div className="mt-1.5 text-[11.5px] text-neutral-500 flex gap-x-3 gap-y-0.5 flex-wrap u-num">
181+ <span title={t.kb_ids?.length ? bases : undefined}>
182+ {t.kb_ids?.length ? S.account.nBases(t.kb_ids.length) : S.account.allBases}
183+ </span>
184+ <span>·</span>
185+ <span>
186+ {t.last_used_at ? S.account.lastUsed(ymd(t.last_used_at)) : S.account.neverUsed}
187+ </span>
188+ <span>·</span>
189+ <span>{t.expires_at ? S.account.expiresOn(ymd(t.expires_at)) : S.account.noExpiry}</span>
190+ <span>·</span>
191+ <span>{S.account.createdOn(ymd(t.created_at))}</span>
192+ </div>
193+ </div>
194+ );
195+}
196+
197+export function Tokens() {
198+ const queryClient = useQueryClient();
199+ const { kbs } = useKb();
200+ const list = useQuery({ queryKey: ["tokens"], queryFn: api.tokens });
201+
202+ const [name, setName] = useState("");
203+ const [scope, setScope] = useState<"read" | "write">("read");
204+ const [picked, setPicked] = useState<Set<string>>(new Set());
205+ const [days, setDays] = useState<number>(90);
206+ const [issued, setIssued] = useState<{ token: string; info: TokenView } | null>(null);
207+
208+ const issue = useMutation({
209+ mutationFn: () =>
210+ api.issueToken({
211+ name: name.trim(),
212+ scope,
213+ kb_ids: picked.size ? Array.from(picked) : null,
214+ expires_in_days: days,
215+ }),
216+ onSuccess: (res) => {
217+ setIssued(res);
218+ setName("");
219+ setPicked(new Set());
220+ queryClient.invalidateQueries({ queryKey: ["tokens"] });
221+ },
222+ onError: (e) => toast.error((e as Error).message),
223+ });
224+ const revoke = useMutation({
225+ mutationFn: (id: string) => api.revokeToken(id),
226+ onSettled: () => queryClient.invalidateQueries({ queryKey: ["tokens"] }),
227+ onError: (e) => toast.error((e as Error).message),
228+ });
229+
230+ const kbName = useMemo(() => {
231+ const m = new Map(kbs.map((k) => [k.id, k.name]));
232+ return (id: string) => m.get(id) ?? id.slice(0, 8);
233+ }, [kbs]);
234+
235+ if (list.isPending) return <Loading>{S.nav.loading}</Loading>;
236+ // 活的在前、按新到旧;撤销过的沉底但仍然列着——撤过这件事本身要看得见
237+ const rows = [...(list.data?.tokens ?? [])].sort((a, b) => {
238+ if (!!a.revoked_at !== !!b.revoked_at) return a.revoked_at ? 1 : -1;
239+ return b.created_at.localeCompare(a.created_at);
240+ });
241+
242+ const field = (label: string, node: React.ReactNode, hint?: string) => (
243+ <div className="mb-4">
244+ <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
245+ {node}
246+ {hint && <p className="mt-1 text-[11px] text-neutral-600">{hint}</p>}
247+ </div>
248+ );
249+
250+ return (
251+ <div className="max-w-2xl p-8">
252+ <h1 className="u-title text-lg">{S.account.tokensTitle}</h1>
253+ <p className="mt-1 mb-6 text-xs text-neutral-500 max-w-lg">{S.account.tokensHint}</p>
254+
255+ {issued && (
256+ <IssuedPanel
257+ token={issued.token}
258+ info={issued.info}
259+ kbs={kbs}
260+ onDone={() => setIssued(null)}
261+ />
262+ )}
263+
264+ <div className="glass rounded-2xl p-5 mb-6">
265+ <h2 className="text-[13px] font-medium text-neutral-200 mb-4">{S.account.newToken}</h2>
266+ {field(
267+ S.account.tokenName,
268+ <input
269+ className="input-dark w-full px-3 py-2 text-sm"
270+ placeholder={S.account.tokenNamePlaceholder}
271+ value={name}
272+ maxLength={64}
273+ onChange={(e) => setName(e.target.value)}
274+ />,
275+ )}
276+ {field(
277+ S.account.tokenScope,
278+ <div className="flex gap-2">
279+ {(["read", "write"] as const).map((s) => (
280+ <button
281+ key={s}
282+ className={`u-btn px-3 py-1.5 text-xs ${scope === s ? "u-btn-primary" : "u-btn-ghost"}`}
283+ onClick={() => setScope(s)}
284+ >
285+ {s === "read" ? S.account.scopeRead : S.account.scopeWrite}
286+ </button>
287+ ))}
288+ </div>,
289+ S.account.scopeHint,
290+ )}
291+ {field(
292+ S.account.tokenKbs,
293+ <div className="flex gap-2 flex-wrap">
294+ {kbs.map((k) => {
295+ const on = picked.has(k.id);
296+ return (
297+ <button
298+ key={k.id}
299+ className={`u-btn px-2.5 py-1 text-xs ${on ? "u-btn-primary" : "u-btn-ghost"}`}
300+ onClick={() => {
301+ const next = new Set(picked);
302+ if (on) next.delete(k.id);
303+ else next.add(k.id);
304+ setPicked(next);
305+ }}
306+ >
307+ {k.name}
308+ </button>
309+ );
310+ })}
311+ </div>,
312+ S.account.kbsAllHint,
313+ )}
314+ {field(
315+ S.account.tokenExpires,
316+ <div className="flex gap-2">
317+ {EXPIRY_CHOICES.map((d) => (
318+ <button
319+ key={d}
320+ className={`u-btn px-2.5 py-1 text-xs u-num ${days === d ? "u-btn-primary" : "u-btn-ghost"}`}
321+ onClick={() => setDays(d)}
322+ >
323+ {d === 0 ? S.account.expiresNever : S.account.expiresDays(d)}
324+ </button>
325+ ))}
326+ </div>,
327+ )}
328+ <div className="flex justify-end">
329+ <button
330+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
331+ disabled={!name.trim() || issue.isPending}
332+ onClick={() => issue.mutate()}
333+ >
334+ {S.account.issueToken}
335+ </button>
336+ </div>
337+ </div>
338+
339+ <h2 className="text-[13px] font-medium text-neutral-200 mb-3">{S.account.yourTokens}</h2>
340+ {rows.length === 0 ? (
341+ <div className="glass rounded-xl p-8 text-center text-sm text-neutral-500">
342+ {S.account.noTokens}
343+ </div>
344+ ) : (
345+ <div className="space-y-2">
346+ {rows.map((t) => (
347+ <TokenRow
348+ key={t.id}
349+ t={t}
350+ kbName={kbName}
351+ busy={revoke.isPending && revoke.variables === t.id}
352+ onRevoke={() => revoke.mutate(t.id)}
353+ />
354+ ))}
355+ </div>
356+ )}
357+ </div>
358+ );
359+}
modified web/src/router.tsx +9 −1
@@ -6,6 +6,7 @@
66 } from "@tanstack/react-router";
77 import { Account } from "./pages/Account";
88 import { AccountShell } from "./pages/AccountShell";
9+import { Tokens } from "./pages/Tokens";
910 import { Chat } from "./pages/Chat";
1011 import { DocViewer } from "./pages/DocViewer";
1112 import { DocsPage } from "./pages/Docs";
@@ -179,6 +180,13 @@
179180 component: MyKbs,
180181 });
181182
183+// 个人令牌(0014):给 agent 的钥匙属于人,所以在账户层,不在库里
184+const tokensRoute = createRoute({
185+ getParentRoute: () => accountShellRoute,
186+ path: "/account/tokens",
187+ component: Tokens,
188+});
189+
182190 const adminRoute = createRoute({
183191 getParentRoute: () => accountShellRoute,
184192 path: "/admin",
@@ -266,7 +274,7 @@
266274 settingsRoute,
267275 docsIndexRoute,
268276 docsRoute,
269- accountShellRoute.addChildren([accountRoute, myKbsRoute, adminRoute]),
277+ accountShellRoute.addChildren([accountRoute, myKbsRoute, tokensRoute, adminRoute]),
270278 appRoute.addChildren([
271279 indexRoute,
272280 legacyGraphRoute,
modified web/src/useKbEvents.ts +5 −0
@@ -19,6 +19,11 @@
1919 es.addEventListener("review", () => {
2020 queryClient.invalidateQueries({ queryKey: ["review", kbId] });
2121 });
22+ // 一句记忆抽出了等人点头的事实(0015):对话里那张确认卡跟着长出来
23+ es.addEventListener("pending", () => {
24+ queryClient.invalidateQueries({ queryKey: ["pending", kbId] });
25+ queryClient.invalidateQueries({ queryKey: ["review", kbId] });
26+ });
2227 es.addEventListener("source", () => {
2328 queryClient.invalidateQueries({ queryKey: ["sources", kbId] });
2429 queryClient.invalidateQueries({ queryKey: ["documents", kbId] });