Skip to content

World's first open-source enterprise world model.

Utopia v0.1

WaylandYangcd2fa125af6b
diff --git a/.env.example b/.env.example
new file mode 100644
index 00000000..9c910b50
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,11 @@
+# 复制为 .env 后按需修改。所有配置走 UTOPIA_ 前缀的环境变量。
+UTOPIA_DATABASE_URL=postgres://utopia:utopia@localhost:5432/utopia
+UTOPIA_BIND_ADDR=0.0.0.0:8080
+# 生产环境必须改成随机长密钥
+UTOPIA_JWT_SECRET=dev-secret-change-me
+# 前端构建产物目录(存在则由服务端托管 SPA)
+UTOPIA_WEB_DIST=web/dist
+# 数据目录:原始文件(files/)与全文索引(index/)
+UTOPIA_DATA_DIR=data
+# 开放注册;false 时仅首个用户可注册,其余由管理员开放
+UTOPIA_OPEN_REGISTRATION=true
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..87de85fe
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,5 @@
+* text=auto eol=lf
+*.png binary
+*.jpg binary
+*.ico binary
+*.woff2 binary
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..215c2752
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,47 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+env:
+ CARGO_TERM_COLOR: always
+
+jobs:
+ backend:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: rustfmt, clippy
+ - uses: Swatinem/rust-cache@v2
+ - name: Format
+ run: cargo fmt --all --check
+ - name: Clippy
+ run: cargo clippy --workspace --all-targets -- -D warnings
+ - name: Test
+ run: cargo test --workspace
+ - name: Build
+ run: cargo build --workspace
+
+ web:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: web
+ steps:
+ - uses: actions/checkout@v4
+ - uses: pnpm/action-setup@v4
+ with:
+ version: 10
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: pnpm
+ cache-dependency-path: web/pnpm-lock.yaml
+ - name: Install
+ run: pnpm install --frozen-lockfile
+ - name: Build (含类型检查)
+ run: pnpm build
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..dd8d52c1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+/target
+**/*.rs.bk
+.env
+node_modules/
+web/dist/
+*.log
+.DS_Store
+/data
+/docs
+.claude/
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 00000000..d8a1112a
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,5321 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "adler32"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"
+
+[[package]]
+name = "adobe-cmap-parser"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae8abfa9a4688de8fc9f42b3f013b6fffec18ed8a554f5f113577e0b9b3212a3"
+dependencies = [
+ "pom",
+]
+
+[[package]]
+name = "aes"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures 0.2.17",
+]
+
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "ar_archive_writer"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
+dependencies = [
+ "object",
+]
+
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+dependencies = [
+ "derive_arbitrary",
+]
+
+[[package]]
+name = "arc-swap"
+version = "1.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"
+dependencies = [
+ "rustversion",
+]
+
+[[package]]
+name = "argon2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
+dependencies = [
+ "base64ct",
+ "blake2",
+ "cpufeatures 0.2.17",
+ "password-hash",
+]
+
+[[package]]
+name = "async-stream"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
+dependencies = [
+ "async-stream-impl",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-stream-impl"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "async-trait"
+version = "0.1.92"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "atoi"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "atoi_simd"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44"
+dependencies = [
+ "debug_unsafe",
+ "rustversion",
+]
+
+[[package]]
+name = "atomic"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "auto_enums"
+version = "0.8.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3091d68264354f211516b91dce6f71046e444fab1867716035f736667243affb"
+dependencies = [
+ "derive_utils",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "aws-lc-rs"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e"
+dependencies = [
+ "aws-lc-sys",
+ "zeroize",
+]
+
+[[package]]
+name = "aws-lc-sys"
+version = "0.44.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483"
+dependencies = [
+ "cc",
+ "cmake",
+ "dunce",
+ "fs_extra",
+ "pkg-config",
+]
+
+[[package]]
+name = "axum"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "form_urlencoded",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "multer",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "serde_json",
+ "serde_path_to_error",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "axum-extra"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9963ff19f40c6102c76756ef0a46004c0d58957d87259fc9208ff8441c12ab96"
+dependencies = [
+ "axum",
+ "axum-core",
+ "bytes",
+ "cookie",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "rustversion",
+ "serde_core",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "bitflags"
+version = "2.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "bitpacking"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019"
+dependencies = [
+ "crunchy",
+]
+
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bon"
+version = "3.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e3fac94a66da67200398458a25412bcc3f9b6443b5119a6cad9cf3ccfcd8cc6"
+dependencies = [
+ "bon-macros",
+]
+
+[[package]]
+name = "bon-macros"
+version = "3.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4654961ad0494e4774c5c60b4cb4cd0ae9b9d92d039d901638b1dba97ebebf5"
+dependencies = [
+ "darling",
+ "ident_case",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytecount"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "calamine"
+version = "0.36.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fa68281b1a76b54a62156474adb06bb380a67e07dd60656e3217152b42183f3"
+dependencies = [
+ "atoi_simd",
+ "byteorder",
+ "codepage",
+ "encoding_rs",
+ "fast-float2",
+ "log",
+ "quick-xml 0.41.0",
+ "serde",
+ "zip 8.6.0",
+]
+
+[[package]]
+name = "cbc"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
+dependencies = [
+ "cipher",
+]
+
+[[package]]
+name = "cc"
+version = "1.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273"
+dependencies = [
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
+]
+
+[[package]]
+name = "cedarwood"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0524a528a6a0288df1863c3c20fe92c301875b4941e7b6c4b394ab08c5a4c55"
+dependencies = [
+ "smallvec",
+]
+
+[[package]]
+name = "census"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0"
+
+[[package]]
+name = "cesu8"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+
+[[package]]
+name = "cfb"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"
+dependencies = [
+ "fnv",
+ "uuid",
+ "web-time",
+]
+
+[[package]]
+name = "cff-parser"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5810ca1a2b5870df2aab1c03e11c40c361ba51d6e3e361e56310f1cb3b4e087"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "chacha20"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "chardetng"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13de944a44b5064ee5d3a5ceccc49a41bfec50f2580e66f82e87703acdb88b53"
+dependencies = [
+ "cfg-if",
+ "encoding_rs",
+ "memchr",
+]
+
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "serde",
+ "wasm-bindgen",
+ "windows-link",
+]
+
+[[package]]
+name = "cipher"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
+dependencies = [
+ "crypto-common 0.1.7",
+ "inout",
+]
+
+[[package]]
+name = "cmake"
+version = "0.1.58"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "codepage"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48f68d061bc2828ae826206326e61251aca94c1e4a5305cf52d9138639c918b4"
+dependencies = [
+ "encoding_rs",
+]
+
+[[package]]
+name = "combine"
+version = "4.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
+[[package]]
+name = "cookie"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
+dependencies = [
+ "percent-encoding",
+ "time",
+ "version_check",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core_maths"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
+dependencies = [
+ "libm",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc"
+version = "3.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
+dependencies = [
+ "crc-catalog",
+]
+
+[[package]]
+name = "crc-catalog"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
+
+[[package]]
+name = "crc32fast"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "cron"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f8c3e73077b4b4a6ab1ea5047c37c57aee77657bc8ecd6f29b0af082d0b0c07"
+dependencies = [
+ "chrono",
+ "nom 7.1.3",
+ "once_cell",
+]
+
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-queue"
+version = "0.3.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "cssparser"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"
+dependencies = [
+ "cssparser-macros",
+ "dtoa-short",
+ "itoa",
+ "phf",
+ "smallvec",
+]
+
+[[package]]
+name = "cssparser-macros"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a2a99df6e410a8ff4245aa2006499ea662245f967cc7c0a38c83ef8eb44dbf"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "csv"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
+dependencies = [
+ "csv-core",
+ "itoa",
+ "ryu",
+ "serde_core",
+]
+
+[[package]]
+name = "csv-core"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "darling"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
+dependencies = [
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "dary_heap"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"
+
+[[package]]
+name = "datasketches"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
+
+[[package]]
+name = "debug_unsafe"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2"
+
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid 0.9.6",
+ "pem-rfc7468",
+ "zeroize",
+]
+
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "derive_arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "derive_more"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "derive_utils"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc05a5d33db20c784f873e84934ad94bb209a090987ac5f62fede2c178234f23"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer 0.10.4",
+ "const-oid 0.9.6",
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer 0.12.1",
+ "const-oid 0.10.2",
+ "crypto-common 0.2.2",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "dotenvy"
+version = "0.15.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
+
+[[package]]
+name = "downcast-rs"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
+
+[[package]]
+name = "dtoa"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"
+
+[[package]]
+name = "dtoa-short"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"
+dependencies = [
+ "dtoa",
+]
+
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
+[[package]]
+name = "ecb"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a8bfa975b1aec2145850fcaa1c6fe269a16578c44705a532ae3edc92b8881c7"
+dependencies = [
+ "cipher",
+]
+
+[[package]]
+name = "ego-tree"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b04dc5a38e4f151a79d9f2451ae6037fb6eaf5cba34771f44781f80e508498e3"
+
+[[package]]
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "encoding_rs"
+version = "0.8.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "erased-serde"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
+dependencies = [
+ "serde",
+ "serde_core",
+ "typeid",
+]
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "etcetera"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943"
+dependencies = [
+ "cfg-if",
+ "home",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "euclid"
+version = "0.20.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bb7ef65b3777a325d1eeefefab5b6d4959da54747e33bd6258e789640f307ad"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "event-listener"
+version = "5.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
+dependencies = [
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "fast-float2"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f"
+
+[[package]]
+name = "fastdivide"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471"
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "feed-rs"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "369995dae0733f1fe5ab0e3f345f6503a5f384179df5d8da333702031a131cf9"
+dependencies = [
+ "chrono",
+ "mediatype",
+ "quick-xml 0.41.0",
+ "regex",
+ "serde",
+ "serde_json",
+ "siphasher",
+ "url",
+ "uuid",
+]
+
+[[package]]
+name = "figment"
+version = "0.10.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3"
+dependencies = [
+ "atomic",
+ "pear",
+ "serde",
+ "uncased",
+ "version_check",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"
+
+[[package]]
+name = "flate2"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "flume"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "spin",
+]
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "fs4"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
+dependencies = [
+ "rustix",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "fs_extra"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-intrusive"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
+dependencies = [
+ "futures-core",
+ "lock_api",
+ "parking_lot",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getopts"
+version = "0.2.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
+dependencies = [
+ "unicode-width",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi 6.0.0",
+ "rand_core 0.10.1",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "h2"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash 0.1.5",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash 0.2.0",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "hashlink"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
+dependencies = [
+ "hashbrown 0.15.5",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "home"
+version = "0.5.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "html5ever"
+version = "0.39.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"
+dependencies = [
+ "log",
+ "markup5ever",
+]
+
+[[package]]
+name = "htmlescape"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163"
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "http-range-header"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "hyper"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "system-configuration",
+ "tokio",
+ "tower-service",
+ "tracing",
+ "windows-registry",
+]
+
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "serde",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_fallback"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
+dependencies = [
+ "icu_locale_core",
+ "icu_locale_fallback_data",
+ "icu_provider",
+ "potential_utf",
+ "tinystr",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_fallback_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "serde",
+ "stable_deref_trait",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_segmenter"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db"
+dependencies = [
+ "core_maths",
+ "icu_collections",
+ "icu_locale_fallback",
+ "icu_provider",
+ "icu_segmenter_data",
+ "potential_utf",
+ "smallvec",
+ "utf8_iter",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_segmenter_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"
+
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "include-flate"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48f173716febb1ad596c16ea5637b5f1790ea32de8e627493ff82bc73b0876ce"
+dependencies = [
+ "include-flate-codegen",
+ "include-flate-compress",
+]
+
+[[package]]
+name = "include-flate-codegen"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a7875b62a72ad3f3203cdd8950d4cf9947db036030b974b8b37ceae90c8d8c0"
+dependencies = [
+ "include-flate-compress",
+ "proc-macro-error3",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "include-flate-compress"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44fbb9c5ccb9a5b67b4afa2974c27e5507ea1bf6d22828cef418e4dfaeca51dd"
+dependencies = [
+ "libflate",
+ "zstd",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "infer"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"
+dependencies = [
+ "cfb",
+]
+
+[[package]]
+name = "inlinable_string"
+version = "0.1.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb"
+
+[[package]]
+name = "inout"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
+dependencies = [
+ "block-padding",
+ "generic-array",
+]
+
+[[package]]
+name = "inventory"
+version = "0.3.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b"
+dependencies = [
+ "rustversion",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78"
+
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "jieba-macros"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34904340bc65749a9e9a02fcc7f3368e675427c18447b9bbe02df52c15c9a36a"
+dependencies = [
+ "phf_codegen",
+]
+
+[[package]]
+name = "jieba-rs"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb5bdea4dc241d589e179f39d2a778f31490f3370aa2f626223dbd930ebc5c9d"
+dependencies = [
+ "bytecount",
+ "cedarwood",
+ "include-flate",
+ "jieba-macros",
+ "phf",
+ "regex",
+ "rustc-hash",
+]
+
+[[package]]
+name = "jni"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
+dependencies = [
+ "cesu8",
+ "cfg-if",
+ "combine",
+ "jni-sys 0.3.1",
+ "log",
+ "thiserror 1.0.69",
+ "walkdir",
+ "windows-sys 0.45.0",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jobserver"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
+dependencies = [
+ "getrandom 0.4.3",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "jsonwebtoken"
+version = "9.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
+dependencies = [
+ "base64",
+ "js-sys",
+ "pem",
+ "ring",
+ "serde",
+ "serde_json",
+ "simple_asn1",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+dependencies = [
+ "spin",
+]
+
+[[package]]
+name = "levenshtein_automata"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25"
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "libflate"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4da9b700e758e57152a1fd1c52cbdc5727c1aa6d8743dc1acda917398f1d76c"
+dependencies = [
+ "adler32",
+ "crc32fast",
+ "dary_heap",
+ "libflate_lz77",
+ "no_std_io2",
+]
+
+[[package]]
+name = "libflate_lz77"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff7a10e427698aef6eef269482776debfef63384d30f13aad39a1a95e0e098fd"
+dependencies = [
+ "hashbrown 0.16.1",
+ "no_std_io2",
+ "rle-decode-fast",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "libredox"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d0a00925a9f930d679b6789b721e3a7f9ed110f41b86d2497caa780c3a070a"
+dependencies = [
+ "bitflags",
+ "libc",
+ "plain",
+ "redox_syscall 0.9.3",
+]
+
+[[package]]
+name = "libsqlite3-sys"
+version = "0.30.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
+dependencies = [
+ "pkg-config",
+ "vcpkg",
+]
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "lopdf"
+version = "0.42.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25aab26d99567469098e64a02f42679f8965c6401263eefa31d8f2dcc37a221c"
+dependencies = [
+ "aes",
+ "bitflags",
+ "cbc",
+ "ecb",
+ "encoding_rs",
+ "flate2",
+ "getrandom 0.4.3",
+ "indexmap",
+ "itoa",
+ "log",
+ "md-5",
+ "nom 8.0.0",
+ "rand 0.10.2",
+ "rangemap",
+ "sha2 0.10.9",
+ "stringprep",
+ "thiserror 2.0.20",
+ "ttf-parser",
+ "weezl",
+]
+
+[[package]]
+name = "lru"
+version = "0.16.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"
+dependencies = [
+ "hashbrown 0.16.1",
+]
+
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
+[[package]]
+name = "lz4_flex"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e"
+
+[[package]]
+name = "markup5ever"
+version = "0.39.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"
+dependencies = [
+ "log",
+ "tendril",
+ "web_atoms",
+]
+
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "measure_time"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e"
+dependencies = [
+ "log",
+]
+
+[[package]]
+name = "mediatype"
+version = "0.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "120fa187be19d9962f0926633453784691731018a2bf936ddb4e29101b79c4a7"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memmap2"
+version = "0.9.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "mime_guess"
+version = "2.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
+dependencies = [
+ "mime",
+ "unicase",
+]
+
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "multer"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b"
+dependencies = [
+ "bytes",
+ "encoding_rs",
+ "futures-util",
+ "http",
+ "httparse",
+ "memchr",
+ "mime",
+ "spin",
+ "version_check",
+]
+
+[[package]]
+name = "murmurhash32"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b"
+
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
+[[package]]
+name = "no_std_io2"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-bigint-dig"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
+dependencies = [
+ "lazy_static",
+ "libm",
+ "num-integer",
+ "num-iter",
+ "num-traits",
+ "rand 0.8.8",
+ "smallvec",
+ "zeroize",
+]
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-iter"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+ "libm",
+]
+
+[[package]]
+name = "object"
+version = "0.39.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "oneshot"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "ordered-float"
+version = "5.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "ownedbytes"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e"
+dependencies = [
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall 0.5.18",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "password-hash"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
+dependencies = [
+ "base64ct",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "pdf-extract"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "417e8fdc940f1d5bc62c5f89864c3a2255f74f69aa353c98509213d67df61e73"
+dependencies = [
+ "adobe-cmap-parser",
+ "cff-parser",
+ "encoding_rs",
+ "euclid",
+ "log",
+ "lopdf",
+ "postscript",
+ "type1-encoding-parser",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "pear"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467"
+dependencies = [
+ "inlinable_string",
+ "pear_codegen",
+ "yansi",
+]
+
+[[package]]
+name = "pear_codegen"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147"
+dependencies = [
+ "proc-macro2",
+ "proc-macro2-diagnostics",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "pem"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
+dependencies = [
+ "base64",
+ "serde_core",
+]
+
+[[package]]
+name = "pem-rfc7468"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
+dependencies = [
+ "base64ct",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pgvector"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3673cba5b9a124916096a423b806a9f29620972c6c97b08db5f2053e9428b481"
+dependencies = [
+ "sqlx",
+]
+
+[[package]]
+name = "phf"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
+dependencies = [
+ "phf_macros",
+ "phf_shared",
+ "serde",
+]
+
+[[package]]
+name = "phf_codegen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
+dependencies = [
+ "fastrand",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_macros"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
+dependencies = [
+ "siphasher",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pkcs1"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
+dependencies = [
+ "der",
+ "pkcs8",
+ "spki",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
+[[package]]
+name = "pom"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60f6ce597ecdcc9a098e7fddacb1065093a3d66446fa16c675e7e71d1b5c28e6"
+
+[[package]]
+name = "postscript"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78451badbdaebaf17f053fd9152b3ffb33b516104eacb45e7864aaa9c712f306"
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "serde_core",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "powerfmt"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "precomputed-hash"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+
+[[package]]
+name = "prettyplease"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
+dependencies = [
+ "proc-macro2",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "proc-macro-error-attr3"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0084e6206a967a2dad822180626b2f6b07a3b379325e8f1ec0438e33a469ba7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+]
+
+[[package]]
+name = "proc-macro-error3"
+version = "3.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cf066225f2373bc711684792b69bdeac0356019b007e721090c24d92d5d5a50"
+dependencies = [
+ "proc-macro-error-attr3",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "proc-macro2-diagnostics"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "version_check",
+ "yansi",
+]
+
+[[package]]
+name = "psm"
+version = "0.1.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
+dependencies = [
+ "ar_archive_writer",
+ "cc",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "encoding_rs",
+ "memchr",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.42.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quinn"
+version = "0.11.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror 2.0.20",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83"
+dependencies = [
+ "aws-lc-rs",
+ "bytes",
+ "getrandom 0.4.3",
+ "lru-slab",
+ "rand 0.10.2",
+ "rand_pcg",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror 2.0.20",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
+dependencies = [
+ "libc",
+ "rand_chacha",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rand_pcg"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
+dependencies = [
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "rangemap"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
+
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "recursive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0786a43debb760f491b1bc0269fe5e84155353c67482b9e60d0cfb596054b43e"
+dependencies = [
+ "recursive-proc-macro-impl",
+ "stacker",
+]
+
+[[package]]
+name = "recursive-proc-macro-impl"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d678d17679829e73d371e96880897e98fee2ded7acc0a50bdf8af2affa4b2fe5"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "reqwest"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04e9018c9d814e5f30cc16a0f03271aeab3571e609612d9fe78c1aa8d11c2f62"
+dependencies = [
+ "base64",
+ "bytes",
+ "encoding_rs",
+ "futures-core",
+ "futures-util",
+ "h2",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
+ "serde",
+ "serde_json",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tokio-util",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-streams",
+ "web-sys",
+ "webpki-roots 1.0.9",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rle-decode-fast"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"
+
+[[package]]
+name = "rsa"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
+dependencies = [
+ "const-oid 0.9.6",
+ "digest 0.10.7",
+ "num-bigint-dig",
+ "num-integer",
+ "num-traits",
+ "pkcs1",
+ "pkcs8",
+ "rand_core 0.6.4",
+ "signature",
+ "spki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rust-stemmers"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54"
+dependencies = [
+ "serde",
+ "serde_derive",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.43"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06"
+dependencies = [
+ "aws-lc-rs",
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"
+dependencies = [
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "jni",
+ "log",
+ "once_cell",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-platform-verifier-android",
+ "rustls-webpki",
+ "security-framework",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "aws-lc-rs",
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "scraper"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdd0be4d296f048bfb06dd01bbc80ef789ddd2e55583e8d2e6b804942abfabc2"
+dependencies = [
+ "cssparser",
+ "ego-tree",
+ "getopts",
+ "html5ever",
+ "precomputed-hash",
+ "selectors",
+ "tendril",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "selectors"
+version = "0.38.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"
+dependencies = [
+ "bitflags",
+ "cssparser",
+ "derive_more",
+ "log",
+ "new_debug_unreachable",
+ "phf",
+ "phf_codegen",
+ "precomputed-hash",
+ "rustc-hash",
+ "servo_arc",
+ "smallvec",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "servo_arc"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"
+dependencies = [
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "sha1"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "digest 0.11.3",
+]
+
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "digest 0.10.7",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "simple_asn1"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"
+dependencies = [
+ "num-bigint",
+ "num-traits",
+ "thiserror 2.0.20",
+ "time",
+]
+
+[[package]]
+name = "siphasher"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
+
+[[package]]
+name = "sketches-ddsketch"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "513c3f5f732bfd6fbb187619c2dfe9d2f25f1a2976f01d575f0fd329d565df56"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "spin"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
+dependencies = [
+ "lock_api",
+]
+
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "sqlparser"
+version = "0.62.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec"
+dependencies = [
+ "log",
+ "recursive",
+]
+
+[[package]]
+name = "sqlx"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"
+dependencies = [
+ "sqlx-core",
+ "sqlx-macros",
+ "sqlx-mysql",
+ "sqlx-postgres",
+ "sqlx-sqlite",
+]
+
+[[package]]
+name = "sqlx-core"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"
+dependencies = [
+ "base64",
+ "bytes",
+ "chrono",
+ "crc",
+ "crossbeam-queue",
+ "either",
+ "event-listener",
+ "futures-core",
+ "futures-intrusive",
+ "futures-io",
+ "futures-util",
+ "hashbrown 0.15.5",
+ "hashlink",
+ "indexmap",
+ "log",
+ "memchr",
+ "once_cell",
+ "percent-encoding",
+ "rustls",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "smallvec",
+ "thiserror 2.0.20",
+ "tokio",
+ "tokio-stream",
+ "tracing",
+ "url",
+ "uuid",
+ "webpki-roots 0.26.11",
+]
+
+[[package]]
+name = "sqlx-macros"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "sqlx-core",
+ "sqlx-macros-core",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "sqlx-macros-core"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b"
+dependencies = [
+ "dotenvy",
+ "either",
+ "heck",
+ "hex",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "sqlx-core",
+ "sqlx-mysql",
+ "sqlx-postgres",
+ "sqlx-sqlite",
+ "syn 2.0.119",
+ "tokio",
+ "url",
+]
+
+[[package]]
+name = "sqlx-mysql"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"
+dependencies = [
+ "atoi",
+ "base64",
+ "bitflags",
+ "byteorder",
+ "bytes",
+ "chrono",
+ "crc",
+ "digest 0.10.7",
+ "dotenvy",
+ "either",
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-util",
+ "generic-array",
+ "hex",
+ "hkdf",
+ "hmac",
+ "itoa",
+ "log",
+ "md-5",
+ "memchr",
+ "once_cell",
+ "percent-encoding",
+ "rand 0.8.8",
+ "rsa",
+ "serde",
+ "sha1",
+ "sha2 0.10.9",
+ "smallvec",
+ "sqlx-core",
+ "stringprep",
+ "thiserror 2.0.20",
+ "tracing",
+ "uuid",
+ "whoami",
+]
+
+[[package]]
+name = "sqlx-postgres"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"
+dependencies = [
+ "atoi",
+ "base64",
+ "bitflags",
+ "byteorder",
+ "chrono",
+ "crc",
+ "dotenvy",
+ "etcetera",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "hex",
+ "hkdf",
+ "hmac",
+ "home",
+ "itoa",
+ "log",
+ "md-5",
+ "memchr",
+ "once_cell",
+ "rand 0.8.8",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "smallvec",
+ "sqlx-core",
+ "stringprep",
+ "thiserror 2.0.20",
+ "tracing",
+ "uuid",
+ "whoami",
+]
+
+[[package]]
+name = "sqlx-sqlite"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea"
+dependencies = [
+ "atoi",
+ "chrono",
+ "flume",
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-intrusive",
+ "futures-util",
+ "libsqlite3-sys",
+ "log",
+ "percent-encoding",
+ "serde",
+ "serde_urlencoded",
+ "sqlx-core",
+ "thiserror 2.0.20",
+ "tracing",
+ "url",
+ "uuid",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "stacker"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "libc",
+ "psm",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "string_cache"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
+dependencies = [
+ "new_debug_unreachable",
+ "parking_lot",
+ "phf_shared",
+ "precomputed-hash",
+]
+
+[[package]]
+name = "string_cache_codegen"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+]
+
+[[package]]
+name = "stringprep"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+ "unicode-properties",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "strum"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "system-configuration"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.9.4",
+ "system-configuration-sys",
+]
+
+[[package]]
+name = "system-configuration-sys"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "tantivy"
+version = "0.26.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edde6a10743fff00a4e1a8c9ef020bf5f3cbad301b7d2d39f2b07f123c4eac07"
+dependencies = [
+ "aho-corasick",
+ "arc-swap",
+ "base64",
+ "bitpacking",
+ "bon",
+ "byteorder",
+ "census",
+ "crc32fast",
+ "crossbeam-channel",
+ "datasketches",
+ "downcast-rs",
+ "fastdivide",
+ "fnv",
+ "fs4",
+ "htmlescape",
+ "itertools",
+ "levenshtein_automata",
+ "log",
+ "lru",
+ "lz4_flex",
+ "measure_time",
+ "memmap2",
+ "once_cell",
+ "oneshot",
+ "rayon",
+ "regex",
+ "rust-stemmers",
+ "rustc-hash",
+ "serde",
+ "serde_json",
+ "sketches-ddsketch",
+ "smallvec",
+ "tantivy-bitpacker",
+ "tantivy-columnar",
+ "tantivy-common",
+ "tantivy-fst",
+ "tantivy-query-grammar",
+ "tantivy-stacker",
+ "tantivy-tokenizer-api",
+ "tempfile",
+ "thiserror 2.0.20",
+ "time",
+ "typetag",
+ "uuid",
+ "winapi",
+]
+
+[[package]]
+name = "tantivy-bitpacker"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fed3d674429bcd2de5d0a6d1aa5495fed8afd9c5ecce993019caf7615f53fa4"
+dependencies = [
+ "bitpacking",
+]
+
+[[package]]
+name = "tantivy-columnar"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c57166f5bcfd478f370ab8445afb4678dce44801fa5ce5c451aaf8595583c5dc"
+dependencies = [
+ "downcast-rs",
+ "fastdivide",
+ "itertools",
+ "serde",
+ "tantivy-bitpacker",
+ "tantivy-common",
+ "tantivy-sstable",
+ "tantivy-stacker",
+]
+
+[[package]]
+name = "tantivy-common"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbf10915aa75da3c3b0d58b58853d2e889efbaf32d4982a4c3715dde6bba23e5"
+dependencies = [
+ "async-trait",
+ "byteorder",
+ "ownedbytes",
+ "serde",
+ "time",
+]
+
+[[package]]
+name = "tantivy-fst"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18"
+dependencies = [
+ "byteorder",
+ "regex-syntax",
+ "utf8-ranges",
+]
+
+[[package]]
+name = "tantivy-jieba"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3392170e86f1c387170aba7d171a466ffdc98a8b55b006e19ac64b123a7b690a"
+dependencies = [
+ "jieba-rs",
+ "lazy_static",
+ "tantivy-tokenizer-api",
+]
+
+[[package]]
+name = "tantivy-query-grammar"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfadb8526b6da90704feb293b0701a6aae62ea14983143344be2dc5ce30f1d82"
+dependencies = [
+ "fnv",
+ "nom 7.1.3",
+ "ordered-float",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "tantivy-sstable"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a2cfc3ac5164cbadc28965ffb145a8f47582a60ae5897859ad8d4316596c606"
+dependencies = [
+ "futures-util",
+ "itertools",
+ "tantivy-bitpacker",
+ "tantivy-common",
+ "tantivy-fst",
+ "zstd",
+]
+
+[[package]]
+name = "tantivy-stacker"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6cbb051742da9d53ca9e8fff43a9b10e319338b24e2c0e15d0372df19ffeb951"
+dependencies = [
+ "murmurhash32",
+ "tantivy-common",
+]
+
+[[package]]
+name = "tantivy-tokenizer-api"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eac258c2c6390673f2685813afeeafcb8c4e0ee7de8dd3fc46838dcc37263f98"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tendril"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"
+dependencies = [
+ "new_debug_unreachable",
+]
+
+[[package]]
+name = "text-splitter"
+version = "0.32.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f3eeec76988617ff1434d754d7e8e197be2cb8981ea77c17e32f3f7a2c6f95e"
+dependencies = [
+ "ahash",
+ "auto_enums",
+ "either",
+ "icu_provider",
+ "icu_segmenter",
+ "itertools",
+ "memchr",
+ "strum",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
+dependencies = [
+ "thiserror-impl 2.0.20",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "time"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
+dependencies = [
+ "deranged",
+ "num-conv",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+ "time-macros",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
+[[package]]
+name = "time-macros"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "serde_core",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "tokio"
+version = "1.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "parking_lot",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "libc",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "http-range-header",
+ "httpdate",
+ "mime",
+ "mime_guess",
+ "percent-encoding",
+ "pin-project-lite",
+ "tokio",
+ "tokio-util",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "ttf-parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+
+[[package]]
+name = "type1-encoding-parser"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa10c302f5a53b7ad27fd42a3996e23d096ba39b5b8dd6d9e683a05b01bee749"
+dependencies = [
+ "pom",
+]
+
+[[package]]
+name = "typed-path"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
+
+[[package]]
+name = "typeid"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "typetag"
+version = "0.2.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c90e86058a30d42a1a928dfb4b49bb33c98c3a2b4909492e6b0881cd94798ec2"
+dependencies = [
+ "erased-serde",
+ "inventory",
+ "once_cell",
+ "serde",
+ "typetag-impl",
+]
+
+[[package]]
+name = "typetag-impl"
+version = "0.2.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f153acc4e99a5f2a5aefa09fb078be54e26271b2813f6041200b224c098d8328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "uncased"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697"
+dependencies = [
+ "version_check",
+]
+
+[[package]]
+name = "unicase"
+version = "2.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "unicode-properties"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
+
+[[package]]
+name = "unicode-width"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+ "serde_derive",
+]
+
+[[package]]
+name = "utf8-ranges"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba"
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "utopia-connectors"
+version = "0.1.0"
+
+[[package]]
+name = "utopia-core"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "figment",
+ "pgvector",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.20",
+ "uuid",
+]
+
+[[package]]
+name = "utopia-extract"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "serde",
+ "serde_json",
+ "tracing",
+ "utopia-llm",
+]
+
+[[package]]
+name = "utopia-graph"
+version = "0.1.0"
+
+[[package]]
+name = "utopia-ingest"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "calamine",
+ "chardetng",
+ "csv",
+ "encoding_rs",
+ "infer",
+ "pdf-extract",
+ "quick-xml 0.42.0",
+ "scraper",
+ "text-splitter",
+ "tracing",
+ "zip 6.0.0",
+]
+
+[[package]]
+name = "utopia-llm"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-stream",
+ "futures-util",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "tracing",
+]
+
+[[package]]
+name = "utopia-mcp"
+version = "0.1.0"
+
+[[package]]
+name = "utopia-reason"
+version = "0.1.0"
+
+[[package]]
+name = "utopia-search"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "tantivy",
+ "tantivy-jieba",
+ "tracing",
+]
+
+[[package]]
+name = "utopia-server"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "argon2",
+ "async-stream",
+ "async-trait",
+ "axum",
+ "axum-extra",
+ "chrono",
+ "dotenvy",
+ "feed-rs",
+ "futures-util",
+ "jsonwebtoken",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "sha2 0.11.0",
+ "sqlparser",
+ "sqlx",
+ "tokio",
+ "tower-http",
+ "tracing",
+ "tracing-subscriber",
+ "utopia-core",
+ "utopia-extract",
+ "utopia-ingest",
+ "utopia-llm",
+ "utopia-search",
+ "utopia-store",
+ "uuid",
+]
+
+[[package]]
+name = "utopia-store"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "cron",
+ "pgvector",
+ "serde_json",
+ "sqlx",
+ "tokio",
+ "tracing",
+ "url",
+ "utopia-core",
+ "utopia-ingest",
+ "uuid",
+]
+
+[[package]]
+name = "uuid"
+version = "1.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f053576934f05a761a402421fbbe3d425d9366f75f978806a037b3ca481abecc"
+dependencies = [
+ "getrandom 0.4.3",
+ "js-sys",
+ "serde_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.127"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.77"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.127"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.127"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.127"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wasm-streams"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web_atoms"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3"
+dependencies = [
+ "phf",
+ "phf_codegen",
+ "string_cache",
+ "string_cache_codegen",
+]
+
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "0.26.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
+dependencies = [
+ "webpki-roots 1.0.9",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "whoami"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"
+dependencies = [
+ "libredox",
+ "wasite",
+]
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-registry"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
+dependencies = [
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.45.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
+dependencies = [
+ "windows-targets 0.42.2",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+dependencies = [
+ "windows-targets 0.48.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
+dependencies = [
+ "windows_aarch64_gnullvm 0.42.2",
+ "windows_aarch64_msvc 0.42.2",
+ "windows_i686_gnu 0.42.2",
+ "windows_i686_msvc 0.42.2",
+ "windows_x86_64_gnu 0.42.2",
+ "windows_x86_64_gnullvm 0.42.2",
+ "windows_x86_64_msvc 0.42.2",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
+dependencies = [
+ "windows_aarch64_gnullvm 0.48.5",
+ "windows_aarch64_msvc 0.48.5",
+ "windows_i686_gnu 0.48.5",
+ "windows_i686_msvc 0.48.5",
+ "windows_x86_64_gnu 0.48.5",
+ "windows_x86_64_gnullvm 0.48.5",
+ "windows_x86_64_msvc 0.48.5",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "yansi"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.56"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.56"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "serde",
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "zip"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "zopfli",
+]
+
+[[package]]
+name = "zip"
+version = "8.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "typed-path",
+ "zopfli",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
+[[package]]
+name = "zstd"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
+dependencies = [
+ "zstd-safe",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "7.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.0.16+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 00000000..540acd87
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,80 @@
+[workspace]
+resolver = "2"
+members = [
+ "crates/utopia-core",
+ "crates/utopia-store",
+ "crates/utopia-server",
+ "crates/utopia-ingest",
+ "crates/utopia-extract",
+ "crates/utopia-graph",
+ "crates/utopia-reason",
+ "crates/utopia-search",
+ "crates/utopia-llm",
+ "crates/utopia-mcp",
+ "crates/utopia-connectors",
+]
+
+[workspace.package]
+version = "0.1.0"
+edition = "2021"
+license = "Apache-2.0"
+repository = "https://github.com/deeplethe/utopia"
+
+[workspace.dependencies]
+utopia-core = { path = "crates/utopia-core" }
+utopia-store = { path = "crates/utopia-store" }
+
+tokio = { version = "1", features = ["full"] }
+axum = { version = "0.8", features = ["multipart"] }
+axum-extra = { version = "0.10", features = ["cookie"] }
+tower-http = { version = "0.6", features = ["cors", "trace", "fs"] }
+sqlx = { version = "0.8", default-features = false, features = [
+ "runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono", "json", "migrate", "macros",
+] }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+thiserror = "2"
+anyhow = "1"
+uuid = { version = "1", features = ["v7", "serde"] }
+chrono = { version = "0.4", features = ["serde"] }
+argon2 = { version = "0.5", features = ["std"] }
+jsonwebtoken = "9"
+figment = { version = "0.10", features = ["env"] }
+dotenvy = "0.15"
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter"] }
+
+# Phase 1: 摄入/检索/LLM
+utopia-ingest = { path = "crates/utopia-ingest" }
+utopia-search = { path = "crates/utopia-search" }
+utopia-llm = { path = "crates/utopia-llm" }
+tantivy = "0.26"
+tantivy-jieba = "0.20"
+text-splitter = "0.32"
+pdf-extract = "0.12"
+calamine = "0.36"
+pgvector = { version = "0.4", features = ["sqlx"] }
+reqwest = { version = "0.13", default-features = false, features = ["json", "stream", "http2", "rustls", "webpki-roots", "charset", "system-proxy"] }
+
+feed-rs = "2"
+cron = "0.12"
+infer = "0.22"
+sha2 = "0.11"
+scraper = "0.27"
+pulldown-cmark = { version = "0.13", default-features = false }
+chardetng = "1"
+encoding_rs = "0.8"
+quick-xml = "0.42"
+zip = { version = "6", default-features = false, features = ["deflate"] }
+csv = "1"
+async-stream = "0.3"
+futures-util = "0.3"
+tokio-stream = "0.1"
+tempfile = "3"
+
+[profile.dev]
+debug = 1
+
+[profile.release]
+lto = "thin"
+strip = true
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..8c4095ba
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 DeepLethe Contributors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..866637ec
--- /dev/null
+++ b/README.md
@@ -0,0 +1,126 @@
+<div align="center">
+
+# Utopia
+
+**The living memory of your organization.**
+
+Open-source, self-hosted knowledge platform: RAG over your own documents, on top of a knowledge graph that remembers *when* each fact was true.
+
+[Quick start](#quick-start) · [Features](#features) · [Configuration](#configuration) · [Roadmap](#roadmap) · [中文](README.zh-CN.md)
+
+[![CI](https://github.com/deeplethe/utopia/actions/workflows/ci.yml/badge.svg)](https://github.com/deeplethe/utopia/actions/workflows/ci.yml)
+[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
+
+</div>
+
+---
+
+Most knowledge bases answer *what*. Utopia is built around *when*.
+
+- **"Who owned project X in Q3 2024?"** — every fact carries a validity interval, so the graph can be read as of any moment.
+- **"When did this policy change, and what did it say before?"** — facts are append-only. A correction closes the previous version instead of overwriting it, so history stays replayable.
+- **Drag the timeline** on the graph page and watch the neighborhood redraw itself at that point in time.
+
+Every edge links back to the sentence it came from. Nothing enters the graph without evidence.
+
+One binary and one Postgres. No Elasticsearch, no vector service, no message queue.
+
+## Features
+
+**Ingest** — PDF, DOCX, PPTX, XLSX/XLS/ODS, CSV/TSV, Markdown, HTML and plain text, with encoding detection for Chinese sources. Web pages and RSS feeds sync on a cron. Push documents from anywhere with a per-source ingest token. Failed parses can be reprocessed in place without re-uploading.
+
+**Search and chat** — Hybrid retrieval: Tantivy full-text (jieba tokenizer for Chinese) and pgvector embeddings, fused with reciprocal rank fusion. Streaming answers carry inline citations that jump to the exact passage. Any OpenAI-compatible endpoint works — DeepSeek, Qwen, GLM, Ollama, vLLM — so the whole stack can run on an air-gapped network.
+
+**Knowledge graph** — LLM extraction of entities and facts against an ontology you can edit. Three-stage entity resolution with a merge log where every merge is reversible. Each fact stores `valid_from` / `valid_to` plus evidence rows pointing back to the source chunk.
+
+**Review queue** — Low-confidence extractions, merge candidates and cardinality conflicts land in a queue rather than interrupting anyone. Confirm, reject or close a fact by hand; the decision is recorded.
+
+**Ask your database** — Register a Postgres connection once at the system level, mount it on a knowledge base, and chat can query it alongside the documents.
+
+**Multi-tenant** — Organizations → workspaces → knowledge bases, with per-KB membership, role-based access and an audit trail.
+
+## Quick start
+
+Requirements: Docker (or Rust 1.85+, Node 20+ and pnpm for local development).
+
+```bash
+git clone https://github.com/deeplethe/utopia.git
+cd utopia
+docker compose --profile app up -d --build
+```
+
+Open http://localhost:8080 and register — the first account becomes the administrator. Then add an OpenAI-compatible endpoint under Settings, create a knowledge base, and drop in some files.
+
+### Local development
+
+```bash
+# 1. Postgres with pgvector
+docker compose up -d db
+
+# 2. Backend on :8080 — runs migrations on startup
+cargo run -p utopia-server
+
+# 3. Frontend on :5173, proxying /api to the backend
+cd web && pnpm install && pnpm dev
+```
+
+## Configuration
+
+Everything is an environment variable prefixed with `UTOPIA_`; copy [.env.example](.env.example) to `.env` to get started.
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `UTOPIA_DATABASE_URL` | `postgres://utopia:utopia@localhost:5432/utopia` | Postgres connection string |
+| `UTOPIA_BIND_ADDR` | `0.0.0.0:8080` | Listen address |
+| `UTOPIA_JWT_SECRET` | `dev-secret-change-me` | **Change this in production** |
+| `UTOPIA_WEB_DIST` | `web/dist` | Built frontend; served as an SPA when present |
+| `UTOPIA_DATA_DIR` | `data` | Original files and the full-text index |
+| `UTOPIA_OPEN_REGISTRATION` | `true` | When false, only the first account may self-register |
+
+LLM endpoints, models and API keys are configured in the UI, not through environment variables.
+
+## Architecture
+
+```
+React + Vite + Tailwind + TanStack
+ │ /api/v1
+ ┌─────┴─────┐
+ │ axum │ utopia-server HTTP, auth, jobs
+ └─────┬─────┘
+ ┌──────────┼──────────┬────────────┐
+utopia-ingest utopia-search utopia-extract utopia-llm
+ parse/chunk tantivy+RRF entities/facts OpenAI-compatible
+ └──────────┴──────────┴────────────┘
+ utopia-store
+ │
+ PostgreSQL + pgvector
+```
+
+Rust (axum · sqlx · tokio · tantivy) over PostgreSQL with pgvector as the only external dependency. Background work runs through a `SKIP LOCKED` job table; orphaned jobs are reclaimed at startup.
+
+## Roadmap
+
+Shipped: document ingest, hybrid search, cited RAG chat, ontology editing, entity and fact extraction, entity resolution, the review queue, graph browsing with a timeline, multi-tenant access control.
+
+Next:
+
+- **Temporal query API** — the data model is bitemporal and the timeline works client-side today; server-side as-of queries are not exposed yet.
+- **Reasoning engine** — temporal Datalog for derived facts with explanations. `utopia-reason` is a placeholder today.
+- **Agent memory over MCP** — memory spaces exist in the schema (`kb.kind = 'memory'`); the episode-write and retrieve endpoints and the MCP server are not built yet.
+- **More connectors** — S3/WebDAV, Notion, Feishu.
+- **OIDC SSO**, backup and restore commands, performance benchmarks at 100k documents.
+
+## Status
+
+Utopia is at **v0.1** and under active development by a single maintainer. It is usable, and the schema still changes between releases.
+
+Two things worth knowing before you deploy it:
+
+- Credentials entered in the UI — LLM API keys and database connection strings — are stored **unencrypted** in Postgres. Encryption at rest is a pre-1.0 hardening item. Run it on a trusted network.
+- There is no upgrade path guarantee yet. Migrations run forward automatically, but pin a version if you care about your data.
+
+Issues and pull requests are welcome.
+
+## License
+
+[Apache-2.0](LICENSE)
diff --git a/README.zh-CN.md b/README.zh-CN.md
new file mode 100644
index 00000000..2fd4d3df
--- /dev/null
+++ b/README.zh-CN.md
@@ -0,0 +1,126 @@
+<div align="center">
+
+# Utopia
+
+**企业的活记忆。**
+
+开源、自部署的知识平台:在自己的文档上做 RAG,底下是一张记得每条事实"什么时候成立"的知识图谱。
+
+[快速开始](#快速开始) · [功能](#功能) · [配置](#配置) · [路线图](#路线图) · [English](README.md)
+
+[![CI](https://github.com/deeplethe/utopia/actions/workflows/ci.yml/badge.svg)](https://github.com/deeplethe/utopia/actions/workflows/ci.yml)
+[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
+
+</div>
+
+---
+
+普通知识库只回答"是什么",Utopia 的差异化是**时间**。
+
+- **"2024 年 Q3 谁负责 X 项目?"** —— 每条事实都带有效区间,图谱可以按任意时点读取。
+- **"这条规定什么时候改的?改之前是什么?"** —— 事实只追加不覆盖。修正是闭合旧版本、写入新版本,历史永远可以回放。
+- **拖动图谱页的时间轴**,看邻域图在那个时刻长什么样。
+
+每条边都能跳回它来自的那句原文。没有证据的事实不进图谱。
+
+一个二进制加一个 Postgres。不需要 Elasticsearch,不需要向量服务,不需要消息队列。
+
+## 功能
+
+**摄入** —— PDF、DOCX、PPTX、XLSX/XLS/ODS、CSV/TSV、Markdown、HTML、纯文本,中文编码自动识别。网页和 RSS 按 cron 定时同步。用来源级别的 ingest token 可以从任何地方推送文档。解析失败的文档可以原地重处理,不必重新上传。
+
+**搜索与对话** —— 混合检索:Tantivy 全文(中文走 jieba 分词)+ pgvector 向量,用 RRF 融合。流式回答带引用角标,点击直接跳到原文段落。LLM 走 OpenAI 兼容协议 —— DeepSeek、Qwen、GLM、Ollama、vLLM 都行,整套可以跑在完全内网环境。
+
+**知识图谱** —— 基于可编辑的本体做 LLM 抽取,产出实体与事实。三段式实体消解,合并日志里每一次合并都可撤销。每条事实存 `valid_from` / `valid_to`,并带证据行指回原始分块。
+
+**审核队列** —— 低置信抽取、待合并候选、基数冲突都进队列,而不是打断使用者。可以手工确认、驳回或闭合一条事实,决策都会留痕。
+
+**问你的数据库** —— 在系统层注册一次 Postgres 连接,挂载到知识库上,对话就能在文档之外一并查询它。
+
+**多租户** —— 组织 → 工作区 → 知识库,知识库级成员管理、角色权限和审计流水。
+
+## 快速开始
+
+依赖:Docker(本地开发另需 Rust 1.85+、Node 20+、pnpm)。
+
+```bash
+git clone https://github.com/deeplethe/utopia.git
+cd utopia
+docker compose --profile app up -d --build
+```
+
+打开 http://localhost:8080 注册 —— 第一个账号即管理员。然后在设置里填一个 OpenAI 兼容端点,建一个知识库,把文件拖进去。
+
+### 本地开发
+
+```bash
+# 1. 启动数据库(pgvector 版 Postgres)
+docker compose up -d db
+
+# 2. 启动后端(自动跑迁移,默认 :8080)
+cargo run -p utopia-server
+
+# 3. 启动前端(:5173,/api 代理到后端)
+cd web && pnpm install && pnpm dev
+```
+
+## 配置
+
+所有配置都是 `UTOPIA_` 前缀的环境变量,复制 [.env.example](.env.example) 为 `.env` 即可开始。
+
+| 变量 | 默认值 | 用途 |
+|---|---|---|
+| `UTOPIA_DATABASE_URL` | `postgres://utopia:utopia@localhost:5432/utopia` | Postgres 连接串 |
+| `UTOPIA_BIND_ADDR` | `0.0.0.0:8080` | 监听地址 |
+| `UTOPIA_JWT_SECRET` | `dev-secret-change-me` | **生产环境必须修改** |
+| `UTOPIA_WEB_DIST` | `web/dist` | 前端构建产物;存在时由服务端托管 SPA |
+| `UTOPIA_DATA_DIR` | `data` | 原始文件与全文索引 |
+| `UTOPIA_OPEN_REGISTRATION` | `true` | 为 false 时仅首个账号可自助注册 |
+
+LLM 的端点、模型和 API Key 在界面里配置,不走环境变量。
+
+## 架构
+
+```
+React + Vite + Tailwind + TanStack
+ │ /api/v1
+ ┌─────┴─────┐
+ │ axum │ utopia-server HTTP · 认证 · 任务
+ └─────┬─────┘
+ ┌──────────┼──────────┬────────────┐
+utopia-ingest utopia-search utopia-extract utopia-llm
+ 解析/分块 tantivy+RRF 实体/事实 OpenAI 兼容
+ └──────────┴──────────┴────────────┘
+ utopia-store
+ │
+ PostgreSQL + pgvector
+```
+
+Rust(axum · sqlx · tokio · tantivy)+ PostgreSQL/pgvector 作为唯一外部依赖。后台任务走 `SKIP LOCKED` 任务表,启动时自动接管孤儿任务。
+
+## 路线图
+
+已完成:文档摄入、混合搜索、带引用的 RAG 对话、本体编辑、实体与事实抽取、实体消解、审核队列、带时间轴的图谱浏览、多租户权限。
+
+接下来:
+
+- **时态查询 API** —— 数据模型已是双时态,时间轴目前在客户端过滤,服务端 as-of 查询尚未开放。
+- **推理引擎** —— 时态 Datalog 派生事实并给出解释。`utopia-reason` 目前是空占位。
+- **MCP 上的 Agent 记忆** —— 记忆空间已在 schema 中(`kb.kind = 'memory'`),episodes 写入、retrieve 端点与 MCP 服务器尚未实现。
+- **更多连接器** —— S3/WebDAV、Notion、飞书。
+- **OIDC SSO**、备份恢复命令、10 万文档级别的性能基准。
+
+## 当前状态
+
+Utopia 目前是 **v0.1**,由一名维护者在持续开发。可用,但 schema 在版本之间仍会变化。
+
+部署前有两件事值得知道:
+
+- 界面里录入的凭据 —— LLM API Key 和数据库连接串 —— 在 Postgres 里是**明文存储**的。静态加密是 1.0 前的硬化项。请部署在可信网络内。
+- 暂不保证升级路径。迁移会自动前滚,但如果在意数据,请锁定版本。
+
+欢迎 issue 和 PR。
+
+## License
+
+[Apache-2.0](LICENSE)
diff --git a/crates/utopia-connectors/Cargo.toml b/crates/utopia-connectors/Cargo.toml
new file mode 100644
index 00000000..c7916a4c
--- /dev/null
+++ b/crates/utopia-connectors/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "utopia-connectors"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
diff --git a/crates/utopia-connectors/src/lib.rs b/crates/utopia-connectors/src/lib.rs
new file mode 100644
index 00000000..f1171457
--- /dev/null
+++ b/crates/utopia-connectors/src/lib.rs
@@ -0,0 +1,3 @@
+//! utopia-connectors: placeholder. External source connectors (S3/WebDAV, Notion,
+//! Feishu) live here once built; today's web and RSS sync is in utopia-server.
+//! See the Roadmap in README.md.
diff --git a/crates/utopia-core/Cargo.toml b/crates/utopia-core/Cargo.toml
new file mode 100644
index 00000000..7075cfd8
--- /dev/null
+++ b/crates/utopia-core/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "utopia-core"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+serde.workspace = true
+serde_json.workspace = true
+thiserror.workspace = true
+anyhow.workspace = true
+uuid.workspace = true
+chrono.workspace = true
+sqlx.workspace = true
+figment.workspace = true
+pgvector.workspace = true
diff --git a/crates/utopia-core/src/config.rs b/crates/utopia-core/src/config.rs
new file mode 100644
index 00000000..831819ee
--- /dev/null
+++ b/crates/utopia-core/src/config.rs
@@ -0,0 +1,42 @@
+use figment::{
+ providers::{Env, Serialized},
+ Figment,
+};
+use serde::{Deserialize, Serialize};
+
+/// 全局配置。来源优先级:环境变量(前缀 `UTOPIA_`)> 默认值。
+/// `.env` 文件由二进制入口通过 dotenvy 预加载进环境变量。
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AppConfig {
+ pub database_url: String,
+ pub bind_addr: String,
+ pub jwt_secret: String,
+ /// 前端构建产物目录;存在时由服务端托管 SPA(history fallback)。
+ pub web_dist: String,
+ /// 数据目录:原始文件(files/)与 Tantivy 索引(index/)。
+ pub data_dir: String,
+ /// 是否开放注册。false 时仅首个用户(引导部署)可注册,其余需管理员开放。
+ pub open_registration: bool,
+}
+
+impl Default for AppConfig {
+ fn default() -> Self {
+ Self {
+ database_url: "postgres://utopia:utopia@localhost:5432/utopia".into(),
+ bind_addr: "0.0.0.0:8080".into(),
+ jwt_secret: "dev-secret-change-me".into(),
+ web_dist: "web/dist".into(),
+ data_dir: "data".into(),
+ open_registration: true,
+ }
+ }
+}
+
+impl AppConfig {
+ pub fn load() -> anyhow::Result<Self> {
+ let cfg = Figment::from(Serialized::defaults(AppConfig::default()))
+ .merge(Env::prefixed("UTOPIA_"))
+ .extract()?;
+ Ok(cfg)
+ }
+}
diff --git a/crates/utopia-core/src/error.rs b/crates/utopia-core/src/error.rs
new file mode 100644
index 00000000..759d640f
--- /dev/null
+++ b/crates/utopia-core/src/error.rs
@@ -0,0 +1,19 @@
+#[derive(thiserror::Error, Debug)]
+pub enum AppError {
+ #[error("Not found")]
+ NotFound,
+ #[error("Not signed in or invalid credentials")]
+ Unauthorized,
+ #[error("You don't have permission to do that")]
+ Forbidden,
+ #[error("{0}")]
+ Conflict(String),
+ #[error("{0}")]
+ Validation(String),
+ #[error(transparent)]
+ Db(#[from] sqlx::Error),
+ #[error(transparent)]
+ Other(#[from] anyhow::Error),
+}
+
+pub type AppResult<T> = Result<T, AppError>;
diff --git a/crates/utopia-core/src/lib.rs b/crates/utopia-core/src/lib.rs
new file mode 100644
index 00000000..761be44c
--- /dev/null
+++ b/crates/utopia-core/src/lib.rs
@@ -0,0 +1,7 @@
+//! utopia-core: 领域模型、错误类型与配置。
+
+pub mod config;
+pub mod error;
+pub mod models;
+
+pub use error::{AppError, AppResult};
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
new file mode 100644
index 00000000..4e58e0c5
--- /dev/null
+++ b/crates/utopia-core/src/models.rs
@@ -0,0 +1,550 @@
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Organization {
+ pub id: Uuid,
+ pub name: String,
+ pub created_at: DateTime<Utc>,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct User {
+ pub id: Uuid,
+ pub org_id: Uuid,
+ pub email: String,
+ #[serde(skip_serializing)]
+ pub password_hash: String,
+ pub display_name: String,
+ /// 系统管理员(部署的首个注册用户)
+ pub is_admin: bool,
+ pub created_at: DateTime<Utc>,
+}
+
+/// 工作区成员视图(成员管理页用)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct MemberView {
+ pub user_id: Uuid,
+ pub email: String,
+ pub display_name: String,
+ pub role: String,
+ pub is_admin: bool,
+}
+
+/// 部署内用户列表(添加成员的选人器用)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct OrgUser {
+ pub id: Uuid,
+ pub email: String,
+ pub display_name: String,
+ pub is_admin: bool,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Workspace {
+ pub id: Uuid,
+ pub org_id: Uuid,
+ pub name: String,
+ pub created_at: DateTime<Utc>,
+}
+
+/// 成员角色,按权限从高到低排序。数据库中存小写文本。
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Role {
+ Viewer,
+ Editor,
+ Admin,
+ Owner,
+}
+
+impl Role {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Role::Owner => "owner",
+ Role::Admin => "admin",
+ Role::Editor => "editor",
+ Role::Viewer => "viewer",
+ }
+ }
+
+ pub fn parse(s: &str) -> Option<Role> {
+ match s {
+ "owner" => Some(Role::Owner),
+ "admin" => Some(Role::Admin),
+ "editor" => Some(Role::Editor),
+ "viewer" => Some(Role::Viewer),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Document {
+ pub id: Uuid,
+ pub kb_id: Uuid,
+ pub source_id: Option<Uuid>,
+ pub filename: String,
+ pub mime: String,
+ pub size_bytes: i64,
+ pub sha256: String,
+ /// pending → parsing → indexing → embedding → ready | failed
+ pub status: String,
+ pub error: Option<String>,
+ pub doc_time: Option<DateTime<Utc>>,
+ pub doc_time_source: String,
+ /// 图谱抽取状态:none → queued → extracting → done | failed
+ pub graph_status: String,
+ pub text_len: i32,
+ pub chunk_count: i32,
+ pub tags: Vec<String>,
+ /// 来源内的逻辑身份(相对路径 / url / rss guid / api external_id);上传为 NULL
+ pub external_key: Option<String>,
+ /// watch_folder 同步时发现源文件已消失(默认保留文档,仅标记)
+ pub missing_since: Option<DateTime<Utc>>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+/// 摄入来源("来源即文件夹":容器 + 定时同步)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Source {
+ pub id: Uuid,
+ pub kb_id: Uuid,
+ /// upload | watch_folder | url | rss | api
+ pub kind: String,
+ pub name: String,
+ /// kind 专属配置:watch_folder {path} / url {urls:[..]} / rss {feed_url}
+ pub config: serde_json::Value,
+ /// lucide 图标名(NULL 时前端按 kind 取默认)
+ pub icon: Option<String>,
+ /// NULL = 仅手动同步(与 sync_cron 互斥)
+ pub sync_interval_minutes: Option<i32>,
+ /// 标准 5 段 cron(服务器本地时区;与 sync_interval_minutes 互斥)
+ pub sync_cron: Option<String>,
+ pub last_sync_at: Option<DateTime<Utc>>,
+ /// never | queued | running | ok | failed
+ pub last_sync_status: String,
+ pub last_sync_error: Option<String>,
+ pub last_sync_added: i32,
+ /// api 来源的推送密钥(明文;查看走 Editor 权限的专用端点,列表响应不带)
+ #[serde(skip_serializing)]
+ pub ingest_token: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+/// 来源同步运行记录(渠道审计历史)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct SyncRun {
+ pub id: Uuid,
+ pub started_at: DateTime<Utc>,
+ pub finished_at: Option<DateTime<Utc>>,
+ /// running | ok | failed
+ pub status: String,
+ pub created_docs: i32,
+ pub updated_docs: i32,
+ pub error: Option<String>,
+}
+
+/// 分块的抽取产物视图(文档查看器右栏:这个 chunk 抽出了什么)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ChunkFactView {
+ pub chunk_id: Uuid,
+ pub fact_id: Uuid,
+ pub subject_id: Uuid,
+ pub subject: String,
+ pub predicate: String,
+ pub object_id: Option<Uuid>,
+ pub object: Option<String>,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub confidence: f32,
+}
+
+/// 来源列表视图(带文档数)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct SourceView {
+ pub id: Uuid,
+ pub kind: String,
+ pub name: String,
+ pub config: serde_json::Value,
+ pub icon: Option<String>,
+ pub sync_interval_minutes: Option<i32>,
+ pub sync_cron: Option<String>,
+ pub last_sync_at: Option<DateTime<Utc>>,
+ pub last_sync_status: String,
+ pub last_sync_error: Option<String>,
+ pub last_sync_added: i32,
+ pub doc_count: i64,
+ /// 已标记"不在来源中"的文档数(url 全集对账 / custom 墓碑产生)
+ pub missing_count: i64,
+}
+
+/// 审计事件视图(带操作人显示名;删号后为 NULL)。纯审计展示用。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct AuditEventView {
+ pub id: Uuid,
+ pub action: String,
+ pub target_kind: String,
+ pub target_id: Option<Uuid>,
+ pub detail: serde_json::Value,
+ pub actor_name: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+/// 账户层"我的知识库"行信息(成员行可空:open 库凭部署身份进入,无矩阵记录)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct MyKbInfo {
+ pub kb_id: Uuid,
+ pub member_role: Option<String>,
+ pub joined_at: Option<DateTime<Utc>>,
+ pub added_by_name: Option<String>,
+ pub doc_count: i64,
+ pub member_count: i64,
+}
+
+/// Chat 会话行(左栏列表)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ConversationView {
+ pub id: Uuid,
+ pub title: String,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+ pub message_count: i64,
+}
+
+/// Chat 消息(含落库的行动轨迹与引用,历史回放用)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ConversationMessage {
+ pub id: Uuid,
+ pub role: String,
+ pub content: String,
+ pub steps: serde_json::Value,
+ pub sources: serde_json::Value,
+ pub created_at: DateTime<Utc>,
+}
+
+/// 检索结果用的分块视图(带文档信息)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ChunkView {
+ pub id: Uuid,
+ pub document_id: Uuid,
+ pub seq: i32,
+ pub text: String,
+ pub filename: String,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct LlmSettings {
+ pub workspace_id: Uuid,
+ pub chat_base_url: Option<String>,
+ #[serde(skip_serializing)]
+ pub chat_api_key: Option<String>,
+ pub chat_model: Option<String>,
+ pub embed_base_url: Option<String>,
+ #[serde(skip_serializing)]
+ pub embed_api_key: Option<String>,
+ pub embed_model: Option<String>,
+ pub embed_dim: Option<i32>,
+ pub updated_at: DateTime<Utc>,
+}
+
+impl LlmSettings {
+ pub fn chat_ready(&self) -> bool {
+ self.chat_base_url.is_some() && self.chat_model.is_some()
+ }
+ pub fn embed_ready(&self) -> bool {
+ self.embed_base_url.is_some() && self.embed_model.is_some()
+ }
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct EntityType {
+ pub id: Uuid,
+ pub kb_id: Uuid,
+ pub key: String,
+ pub label: String,
+ pub color: String,
+ /// 图谱节点形状:circle | square
+ pub shape: String,
+ pub builtin: bool,
+ /// subClassOf 层级(公理推理 P4 点亮,编辑器先维护数据)
+ pub parent_id: Option<Uuid>,
+ /// 语义指引:注入抽取 prompt(什么算这个类,举例)
+ pub description: String,
+}
+
+/// 本体编辑器:某个类下的实体实例行(详情区实例列表用)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct EntityInstance {
+ pub id: Uuid,
+ pub name: String,
+ pub fact_count: i64,
+}
+
+/// 本体编辑器视图:类型 + 使用量(删除保护与 UX 提示用)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct EntityTypeView {
+ pub id: Uuid,
+ pub key: String,
+ pub label: String,
+ pub color: String,
+ pub shape: String,
+ pub builtin: bool,
+ pub parent_id: Option<Uuid>,
+ pub description: String,
+ pub usage: i64,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct RelationTypeView {
+ pub id: Uuid,
+ pub key: String,
+ pub label: String,
+ pub temporal: String,
+ pub functional: bool,
+ pub inverse_functional: bool,
+ pub builtin: bool,
+ pub description: String,
+ /// relation(宾语是实体)| attribute(宾语是字面值)
+ pub kind: String,
+ /// attribute 专用:挂在哪个类下
+ pub domain_type_id: Option<Uuid>,
+ /// attribute 专用:text | number | date | bool
+ pub datatype: Option<String>,
+ pub unit: Option<String>,
+ pub usage: i64,
+}
+
+/// 抽取未匹配统计(本体扩展建议的信号源)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct OntologyMiss {
+ pub kind: String,
+ pub key: String,
+ pub example: Option<String>,
+ pub count: i32,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct RelationType {
+ pub id: Uuid,
+ pub kb_id: Uuid,
+ pub key: String,
+ pub label: String,
+ /// state | event | eternal
+ pub temporal: String,
+ /// 主语侧唯一:同一时刻一个主语至多一个宾语
+ pub functional: bool,
+ /// 宾语侧唯一:同一时刻一个宾语至多一个主语(如一个项目只有一个 leads 它的人)
+ pub inverse_functional: bool,
+ pub builtin: bool,
+ /// 语义指引:注入抽取 prompt
+ pub description: String,
+ /// relation(宾语是实体)| attribute(宾语是字面值,走 facts.object_value)
+ pub kind: String,
+ /// attribute 专用:属性挂在哪个类下
+ pub domain_type_id: Option<Uuid>,
+ /// attribute 专用:text | number | date | bool
+ pub datatype: Option<String>,
+ pub unit: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct Entity {
+ pub id: Uuid,
+ pub kb_id: Uuid,
+ pub type_id: Uuid,
+ pub canonical_name: String,
+ pub aliases: Vec<String>,
+ pub merged_into: Option<Uuid>,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+/// 图渲染节点。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct GraphNode {
+ pub id: Uuid,
+ pub name: String,
+ pub type_key: String,
+ pub type_label: String,
+ pub color: String,
+ /// 类型形状:circle | square
+ pub shape: String,
+ pub degree: i64,
+ /// 同名并存时的展示消歧后缀(如所属组织名)
+ pub disambiguator: Option<String>,
+}
+
+/// 图渲染边(= 一条 live 事实)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct GraphEdge {
+ pub id: Uuid,
+ pub source: Uuid,
+ pub target: Uuid,
+ pub predicate: String,
+ pub label: String,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub confidence: f32,
+}
+
+/// 实体详情页的事实行(时间线)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct EntityFact {
+ pub id: Uuid,
+ /// out = 该实体为主语;in = 为宾语
+ pub direction: String,
+ pub predicate_key: String,
+ pub predicate_label: String,
+ pub temporal: String,
+ pub other_id: Option<Uuid>,
+ pub other_name: Option<String>,
+ /// 字面值宾语(属性事实/问数映射):{"value":…,"unit":…} 或 {"summary":…}
+ pub object_value: Option<serde_json::Value>,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub valid_precision: String,
+ pub confidence: f32,
+ pub evidence_count: i64,
+ /// 证据全部停留在来源文档的旧版(未被现行内容确认;不代表事实失效)
+ pub stale: bool,
+ /// 修正行(supersedes 链上):区间闭合来自引擎对账/人工裁决而非抽取原文
+ pub corrected: bool,
+ /// 证据集合里最新的文档时间——开放事实的"最后确认时间"(时效性透明化)
+ pub last_evidence_time: Option<DateTime<Utc>>,
+}
+
+/// 消解审核项的一侧实体摘要。
+#[derive(Debug, Clone, Serialize)]
+pub struct ReviewSide {
+ pub id: Uuid,
+ pub name: String,
+ pub type_label: String,
+ pub color: String,
+ pub disambiguator: Option<String>,
+ pub degree: i64,
+ pub top_facts: Vec<String>,
+}
+
+/// 消解审核项:疑似同一实体的灰区对。
+#[derive(Debug, Clone, Serialize)]
+pub struct ReviewItem {
+ pub id: Uuid,
+ pub score: f32,
+ pub reason: Option<String>,
+ /// adjudicating = 等 LLM 裁决;human = 等人工终审
+ pub stage: String,
+ pub created_at: DateTime<Utc>,
+ pub left: ReviewSide,
+ pub right: ReviewSide,
+}
+
+/// 合并日志行(审核页历史区)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct MergeLogView {
+ pub id: Uuid,
+ pub source_name: String,
+ pub target_name: String,
+ /// NULL = LLM 自动合并
+ pub merged_by_name: Option<String>,
+ pub reason: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub reverted_at: Option<DateTime<Utc>>,
+}
+
+/// 低置信事实审核行。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct FactReviewItem {
+ pub id: Uuid,
+ pub subject_name: String,
+ pub predicate_label: String,
+ pub object_name: Option<String>,
+ pub valid_from: Option<DateTime<Utc>>,
+ pub valid_to: Option<DateTime<Utc>>,
+ pub confidence: f32,
+ pub evidence_count: i64,
+ pub quote: Option<String>,
+}
+
+/// 事实的证据(引句 + 原文定位)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct EvidenceView {
+ pub quote: Option<String>,
+ pub chunk_id: Uuid,
+ pub document_id: Uuid,
+ pub filename: String,
+ pub seq: i32,
+ /// 证据出自文档的第几版
+ pub doc_version: i32,
+ /// 文档已有更新的版本(证据停留在旧版;不代表事实失效)
+ pub stale: bool,
+}
+
+/// 时态冲突(S3 自动闭合拿不准的那些):旧事实 vs 新事实,Review 页人裁。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ConflictView {
+ pub id: Uuid,
+ /// no_time | simultaneous | low_confidence
+ pub reason: String,
+ pub created_at: DateTime<Utc>,
+ pub predicate_label: String,
+ /// 双方完整三元组:主语侧冲突变的是宾语,宾语侧冲突变的是主语
+ pub old_fact_id: Uuid,
+ pub old_subject: String,
+ pub old_object: Option<String>,
+ pub old_valid_from: Option<DateTime<Utc>>,
+ pub new_fact_id: Uuid,
+ pub new_subject: String,
+ pub new_object: Option<String>,
+ pub new_valid_from: Option<DateTime<Utc>>,
+ pub new_confidence: f32,
+}
+
+/// 文档查看器用的分块视图。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct ChunkFull {
+ pub id: Uuid,
+ pub seq: i32,
+ pub text: String,
+}
+
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct KnowledgeBase {
+ pub id: Uuid,
+ pub workspace_id: Uuid,
+ pub name: String,
+ /// `knowledge` | `memory`(Agent 记忆空间)
+ pub kind: String,
+ pub description: Option<String>,
+ /// open = 全员按部署角色;restricted = 仅 kb_members 名单可见
+ pub visibility: String,
+ /// 部署的公共默认空间(第一个建的库):永远 open、不可删除
+ pub is_default: bool,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+/// KB 成员矩阵行(库 Settings 的 Members 区)。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct KbMemberView {
+ pub user_id: Uuid,
+ pub email: String,
+ pub display_name: String,
+ /// viewer | editor | admin
+ pub role: String,
+}
+
+/// 问数数据源列表视图:连接串不下发(凭据只进不出),只露 host:port/db 摘要。
+#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
+pub struct DataSourceView {
+ pub id: Uuid,
+ pub name: String,
+ pub engine: String,
+ /// 连接摘要(host:port/db,无凭据)
+ pub summary: String,
+ pub created_at: DateTime<Utc>,
+ pub last_test_at: Option<DateTime<Utc>>,
+ pub last_test_ok: Option<bool>,
+}
diff --git a/crates/utopia-extract/Cargo.toml b/crates/utopia-extract/Cargo.toml
new file mode 100644
index 00000000..ee407ae0
--- /dev/null
+++ b/crates/utopia-extract/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "utopia-extract"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+serde.workspace = true
+serde_json.workspace = true
+anyhow.workspace = true
+chrono.workspace = true
+utopia-llm.workspace = true
+tracing.workspace = true
diff --git a/crates/utopia-extract/src/lib.rs b/crates/utopia-extract/src/lib.rs
new file mode 100644
index 00000000..82aeff79
--- /dev/null
+++ b/crates/utopia-extract/src/lib.rs
@@ -0,0 +1,376 @@
+//! utopia-extract: LLM 抽取(实体/关系/时间归一化)。
+//! 提示词注入本体类型与文档元时间;输出严格 JSON;证据引句强制(无引句降置信度)。
+
+use chrono::{DateTime, NaiveDate, TimeZone, Utc};
+use serde::Deserialize;
+use utopia_llm::ChatMessage;
+
+#[derive(Debug, Deserialize)]
+pub struct Extraction {
+ #[serde(default)]
+ pub entities: Vec<ExtractedEntity>,
+ #[serde(default)]
+ pub facts: Vec<ExtractedFact>,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ExtractedEntity {
+ pub name: String,
+ #[serde(rename = "type")]
+ pub type_key: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ExtractedFact {
+ pub subject: String,
+ pub predicate: String,
+ /// 关系事实的宾语实体名;属性事实为空
+ #[serde(default)]
+ pub object: Option<String>,
+ /// 属性事实的字面值(谓词是 attribute 时)
+ #[serde(default)]
+ pub value: Option<serde_json::Value>,
+ #[serde(default)]
+ pub valid_from: Option<String>,
+ #[serde(default)]
+ pub valid_to: Option<String>,
+ #[serde(default)]
+ pub confidence: Option<f32>,
+ #[serde(default)]
+ pub quote: Option<String>,
+}
+
+/// 构造抽取提示词。`types`/`relations` 为 (key, label, description) 三元组;
+/// description 非空时按行列出——本体里的语义指引直接决定抽取质量。
+/// `attributes` 为调用方预排版的属性行("person.salary (number, CNY): 月薪");
+/// 为空时提示词一字不变——没定义属性的库零成本。
+pub fn build_messages(
+ types: &[(String, String, String)],
+ relations: &[(String, String, String)],
+ attributes: &[String],
+ doc_time: Option<&str>,
+ filename: &str,
+ chunk_text: &str,
+) -> Vec<ChatMessage> {
+ let fmt_list = |items: &[(String, String, String)]| {
+ items
+ .iter()
+ .map(|(k, l, d)| {
+ let d = d.trim();
+ if d.is_empty() {
+ format!("- {k} ({l})")
+ } else {
+ format!("- {k} ({l}): {d}")
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ let type_list = fmt_list(types);
+ let rel_list = fmt_list(relations);
+ let time_ctx = doc_time
+ .map(|t| {
+ format!(
+ "Document date: {t}. Resolve relative time expressions (e.g. \"last year\", \
+ \"this March\") to absolute dates using it as the reference."
+ )
+ })
+ .unwrap_or_else(|| {
+ "Document date unknown — only output dates explicitly written in the text.".into()
+ });
+
+ // 属性段按需注入:清单 + 输出说明 + 取值规则。没定义属性时完全不出现
+ let attr_section = if attributes.is_empty() {
+ String::new()
+ } else {
+ format!(
+ "\nAttributes (literal-valued fields, listed as class.attribute_key; as \"predicate\" \
+ use the attribute_key alone — e.g. \"salary\", not \"person.salary\" — with a \
+ \"value\" instead of \"object\"):\n{}\n",
+ attributes.join("\n")
+ )
+ };
+ let attr_rules = if attributes.is_empty() {
+ String::new()
+ } else {
+ "\n8. Attribute facts carry \"value\" (no \"object\"): number = plain number without \
+ thousands separators or unit symbols; date = \"YYYY[-MM[-DD]]\"; bool = true/false; \
+ text = a short string. Only attach an attribute to a subject of its listed class. \
+ valid_from = when this value took effect, if the text says so."
+ .to_string()
+ };
+ let system = format!(
+ "You are a knowledge-graph extraction engine. Extract entities and factual relations \
+ from the given text. Output exactly one JSON object and nothing else.\n\
+ \n\
+ Entity types (use only these keys):\n{type_list}\n\
+ \n\
+ Relation types (use only these keys):\n{rel_list}\n\
+ {attr_section}\
+ \n\
+ Output format:\n\
+ {{\"entities\":[{{\"name\":\"entity name\",\"type\":\"type key\"}}],\n\
+ \"facts\":[{{\"subject\":\"subject entity name\",\"predicate\":\"relation key\",\"object\":\"object entity name\",\n\
+ \"valid_from\":\"2023-01\",\"valid_to\":null,\"confidence\":0.9,\"quote\":\"verbatim supporting quote\"}}]}}\n\
+ \n\
+ Rules:\n\
+ 1. Use the canonical full name as written in the text, in the text's original language; \
+ list each entity once.\n\
+ 2. Every fact's subject/object must appear in entities.\n\
+ 3. Dates must be \"YYYY\", \"YYYY-MM\", \"YYYY-MM-DD\", or null. If a relation is still \
+ ongoing, valid_to is null. If the text states no date, use null — never invent dates.\n\
+ 4. {time_ctx}\n\
+ 5. quote must be a contiguous excerpt from the source text; every fact needs one.\n\
+ 6. confidence in 0~1: 0.9 explicitly stated, 0.7 inferred, 0.5 uncertain.\n\
+ 7. If nothing can be extracted, output {{\"entities\":[],\"facts\":[]}}.{attr_rules}"
+ );
+
+ let user = format!("Source file: \"{filename}\"\n\nText:\n{chunk_text}");
+
+ vec![
+ ChatMessage {
+ role: "system".into(),
+ content: system,
+ },
+ ChatMessage {
+ role: "user".into(),
+ content: user,
+ },
+ ]
+}
+
+/// 从 LLM 回复中稳健地取出 JSON 块(容忍代码围栏与前后废话)。
+pub fn json_block(raw: &str) -> anyhow::Result<String> {
+ let text = raw.trim();
+ let cleaned = text
+ .strip_prefix("```json")
+ .or_else(|| text.strip_prefix("```"))
+ .map(|s| s.trim_end_matches("```"))
+ .unwrap_or(text);
+ let start = cleaned.find('{');
+ let end = cleaned.rfind('}');
+ match (start, end) {
+ (Some(s), Some(e)) if e > s => Ok(cleaned[s..=e].to_string()),
+ _ => anyhow::bail!("No JSON found in LLM reply"),
+ }
+}
+
+pub fn parse_response(raw: &str) -> anyhow::Result<Extraction> {
+ let json_str = json_block(raw)?;
+ let extraction: Extraction = serde_json::from_str(&json_str)
+ .map_err(|e| anyhow::anyhow!("Failed to parse extraction JSON: {e}"))?;
+ Ok(extraction)
+}
+
+// ---------------------------------------------------------------------------
+// 实体消解裁决(攒批:一次调用裁多对,LLM 只处理 embedding 分不出的灰区)
+// ---------------------------------------------------------------------------
+
+/// 待裁决的一侧:名字 + 类型 + 事实摘要行。
+pub struct AdjudicationSide {
+ pub name: String,
+ pub type_label: String,
+ pub facts: Vec<String>,
+}
+
+pub struct AdjudicationPair {
+ pub left: AdjudicationSide,
+ pub right: AdjudicationSide,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct AdjudicationVerdict {
+ pub i: usize,
+ pub verdict: String,
+ #[serde(default)]
+ pub confidence: Option<f32>,
+}
+
+#[derive(Debug, Deserialize)]
+struct AdjudicationReply {
+ #[serde(default)]
+ verdicts: Vec<AdjudicationVerdict>,
+}
+
+/// 构造攒批裁决提示词。保守偏置:证据不足答 unsure(宁分勿合,合并要证据)。
+pub fn build_adjudication_messages(pairs: &[AdjudicationPair]) -> Vec<ChatMessage> {
+ let system = "You are an entity-resolution adjudicator for a knowledge graph. \
+ For each numbered pair, decide whether the two records refer to the SAME real-world \
+ entity or are namesakes (different entities that share a name).\n\
+ \n\
+ Judge by the facts attached to each record: employer/affiliation, role, time ranges, \
+ and connected entities. Identical names alone are NEVER sufficient evidence of sameness. \
+ Contradictory affiliations in overlapping time periods indicate different entities \
+ (but people do change jobs — non-overlapping periods can belong to one person).\n\
+ \n\
+ Output exactly one JSON object and nothing else:\n\
+ {\"verdicts\":[{\"i\":0,\"verdict\":\"same|different|unsure\",\"confidence\":0.9}]}\n\
+ \n\
+ Rules:\n\
+ 1. One verdict per pair, using the pair's number as \"i\".\n\
+ 2. confidence in 0~1.\n\
+ 3. Be conservative: if the evidence is insufficient to decide, answer \"unsure\" — \
+ a wrong merge is far more damaging than leaving two records separate."
+ .to_string();
+
+ let mut user = String::new();
+ for (i, p) in pairs.iter().enumerate() {
+ let fmt = |s: &AdjudicationSide| {
+ let facts = if s.facts.is_empty() {
+ " (no recorded facts)".to_string()
+ } else {
+ s.facts
+ .iter()
+ .map(|f| format!(" - {f}"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ format!("\"{}\" ({})\n{}", s.name, s.type_label, facts)
+ };
+ user.push_str(&format!(
+ "Pair {i}:\nRecord A: {}\nRecord B: {}\n\n",
+ fmt(&p.left),
+ fmt(&p.right)
+ ));
+ }
+
+ vec![
+ ChatMessage {
+ role: "system".into(),
+ content: system,
+ },
+ ChatMessage {
+ role: "user".into(),
+ content: user,
+ },
+ ]
+}
+
+pub fn parse_adjudication(raw: &str) -> anyhow::Result<Vec<AdjudicationVerdict>> {
+ let json_str = json_block(raw)?;
+ let reply: AdjudicationReply = serde_json::from_str(&json_str)
+ .map_err(|e| anyhow::anyhow!("Failed to parse adjudication JSON: {e}"))?;
+ Ok(reply.verdicts)
+}
+
+/// 属性值按 datatype 归一。失败返回 None——宁缺勿脏,调用方跳过并记日志。
+/// number 容忍千分位/空格;date 要求 YYYY[-MM[-DD]] 且保留原精度;bool 宽容 yes/no。
+pub fn normalize_attr_value(datatype: &str, raw: &serde_json::Value) -> Option<serde_json::Value> {
+ match datatype {
+ "number" => match raw {
+ serde_json::Value::Number(n) => Some(serde_json::Value::Number(n.clone())),
+ serde_json::Value::String(s) => {
+ let cleaned: String = s
+ .chars()
+ .filter(|c| !matches!(c, ',' | ' ' | '_'))
+ .collect();
+ cleaned
+ .parse::<f64>()
+ .ok()
+ .filter(|f| f.is_finite())
+ .and_then(serde_json::Number::from_f64)
+ .map(serde_json::Value::Number)
+ }
+ _ => None,
+ },
+ "date" => {
+ let s = raw.as_str()?.trim();
+ parse_time(s).map(|_| serde_json::Value::String(s.to_string()))
+ }
+ "bool" => match raw {
+ serde_json::Value::Bool(b) => Some(serde_json::Value::Bool(*b)),
+ serde_json::Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
+ "true" | "yes" | "是" => Some(serde_json::Value::Bool(true)),
+ "false" | "no" | "否" => Some(serde_json::Value::Bool(false)),
+ _ => None,
+ },
+ _ => None,
+ },
+ _ => {
+ let s = match raw {
+ serde_json::Value::String(s) => s.trim().to_string(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => return None,
+ };
+ (!s.is_empty()).then(|| serde_json::Value::String(s.chars().take(500).collect()))
+ }
+ }
+}
+
+/// 解析时间字符串 → (UTC 时间, 精度)。支持 YYYY / YYYY-MM / YYYY-MM-DD。
+pub fn parse_time(s: &str) -> Option<(DateTime<Utc>, &'static str)> {
+ let s = s.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("null") {
+ return None;
+ }
+ if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
+ return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "day"));
+ }
+ if let Ok(d) = NaiveDate::parse_from_str(&format!("{s}-01"), "%Y-%m-%d") {
+ return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "month"));
+ }
+ if s.len() == 4 {
+ if let Ok(year) = s.parse::<i32>() {
+ let d = NaiveDate::from_ymd_opt(year, 1, 1)?;
+ return Some((Utc.from_utc_datetime(&d.and_hms_opt(0, 0, 0)?), "year"));
+ }
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_time_precisions() {
+ assert_eq!(parse_time("2024").unwrap().1, "year");
+ assert_eq!(parse_time("2024-07").unwrap().1, "month");
+ assert_eq!(parse_time("2024-07-15").unwrap().1, "day");
+ assert!(parse_time("null").is_none());
+ assert!(parse_time("").is_none());
+ assert!(parse_time("下个月").is_none());
+ }
+
+ #[test]
+ fn parse_adjudication_reply() {
+ let raw = "```json\n{\"verdicts\":[{\"i\":0,\"verdict\":\"same\",\"confidence\":0.92},{\"i\":1,\"verdict\":\"unsure\"}]}\n```";
+ let v = parse_adjudication(raw).unwrap();
+ assert_eq!(v.len(), 2);
+ assert_eq!(v[0].verdict, "same");
+ assert_eq!(v[1].confidence, None);
+ }
+
+ #[test]
+ fn normalize_attr_values() {
+ use serde_json::json;
+ assert_eq!(
+ normalize_attr_value("number", &json!("35,000")),
+ Some(json!(35000.0))
+ );
+ assert_eq!(normalize_attr_value("number", &json!(42)), Some(json!(42)));
+ assert_eq!(normalize_attr_value("number", &json!("about ten")), None);
+ assert_eq!(
+ normalize_attr_value("date", &json!("2024-07")),
+ Some(json!("2024-07"))
+ );
+ assert_eq!(normalize_attr_value("date", &json!("下个月")), None);
+ assert_eq!(
+ normalize_attr_value("bool", &json!("yes")),
+ Some(json!(true))
+ );
+ assert_eq!(
+ normalize_attr_value("text", &json!(" CTO ")),
+ Some(json!("CTO"))
+ );
+ assert_eq!(normalize_attr_value("text", &json!([1])), None);
+ }
+
+ #[test]
+ fn parse_response_with_fence() {
+ let raw = "好的,结果如下:\n```json\n{\"entities\":[{\"name\":\"张三\",\"type\":\"person\"}],\"facts\":[]}\n```";
+ let e = parse_response(raw).unwrap();
+ assert_eq!(e.entities.len(), 1);
+ assert_eq!(e.entities[0].type_key, "person");
+ }
+}
diff --git a/crates/utopia-graph/Cargo.toml b/crates/utopia-graph/Cargo.toml
new file mode 100644
index 00000000..22901933
--- /dev/null
+++ b/crates/utopia-graph/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "utopia-graph"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
diff --git a/crates/utopia-graph/src/lib.rs b/crates/utopia-graph/src/lib.rs
new file mode 100644
index 00000000..9c14917b
--- /dev/null
+++ b/crates/utopia-graph/src/lib.rs
@@ -0,0 +1,3 @@
+//! utopia-graph: placeholder. Graph traversal and neighborhood queries currently
+//! live in utopia-store; this crate is where they land once they outgrow it.
+//! See the Roadmap in README.md.
diff --git a/crates/utopia-ingest/Cargo.toml b/crates/utopia-ingest/Cargo.toml
new file mode 100644
index 00000000..1077557d
--- /dev/null
+++ b/crates/utopia-ingest/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "utopia-ingest"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+anyhow.workspace = true
+text-splitter.workspace = true
+pdf-extract.workspace = true
+calamine.workspace = true
+scraper.workspace = true
+chardetng.workspace = true
+encoding_rs.workspace = true
+quick-xml.workspace = true
+zip.workspace = true
+csv.workspace = true
+infer.workspace = true
+tracing.workspace = true
diff --git a/crates/utopia-ingest/src/chunker.rs b/crates/utopia-ingest/src/chunker.rs
new file mode 100644
index 00000000..09575035
--- /dev/null
+++ b/crates/utopia-ingest/src/chunker.rs
@@ -0,0 +1,29 @@
+//! 分块:text-splitter 语义分块(段落/句子边界优先),字符预算 + 重叠。
+
+use text_splitter::{ChunkConfig, TextSplitter};
+
+#[derive(Debug, Clone)]
+pub struct ChunkPiece {
+ pub seq: i32,
+ pub text: String,
+ pub char_start: i32,
+ pub char_end: i32,
+}
+
+/// 默认预算:1200 字符(中文约等于 1000+ token),重叠 150。
+pub fn chunk_text(text: &str) -> Vec<ChunkPiece> {
+ let config = ChunkConfig::new(1200)
+ .with_overlap(150)
+ .expect("overlap < capacity");
+ let splitter = TextSplitter::new(config);
+ splitter
+ .chunk_indices(text)
+ .enumerate()
+ .map(|(i, (offset, chunk))| ChunkPiece {
+ seq: i as i32,
+ text: chunk.to_string(),
+ char_start: offset as i32,
+ char_end: (offset + chunk.len()) as i32,
+ })
+ .collect()
+}
diff --git a/crates/utopia-ingest/src/lib.rs b/crates/utopia-ingest/src/lib.rs
new file mode 100644
index 00000000..b3380448
--- /dev/null
+++ b/crates/utopia-ingest/src/lib.rs
@@ -0,0 +1,62 @@
+//! utopia-ingest: 解析矩阵 + 分块。
+//! 原则:文本层 Rust 原生解决(快、零依赖);扫描件/复杂版式后续走 docling sidecar。
+
+mod chunker;
+mod parsers;
+
+pub use chunker::{chunk_text, ChunkPiece};
+
+/// 解析产物:纯文本 + 可选结构信息。
+#[derive(Debug)]
+pub struct ParsedDoc {
+ pub text: String,
+}
+
+/// 支持的格式(P1):pdf / docx / xlsx·xls·ods / pptx / md / txt / html / csv / json / yaml / xml / log
+pub fn parse(filename: &str, bytes: &[u8]) -> anyhow::Result<ParsedDoc> {
+ let ext = filename
+ .rsplit('.')
+ .next()
+ .map(|s| s.to_ascii_lowercase())
+ .unwrap_or_default();
+
+ // 魔数探测优先于扩展名(扩展名可能撒谎)
+ let kind = infer::get(bytes).map(|t| t.extension()).unwrap_or("");
+
+ let text = match (kind, ext.as_str()) {
+ ("pdf", _) | (_, "pdf") => parsers::pdf(bytes)?,
+ ("docx", _) | (_, "docx") => parsers::docx(bytes)?,
+ ("xlsx", _) | (_, "xlsx") | (_, "xls") | (_, "ods") => parsers::spreadsheet(bytes)?,
+ ("pptx", _) | (_, "pptx") => parsers::pptx(bytes)?,
+ (_, "html") | (_, "htm") => parsers::html(bytes),
+ (_, "csv") | (_, "tsv") => parsers::csv_text(bytes, ext == "tsv")?,
+ // md/json/yaml/xml/log/txt 及一切未识别格式:按文本解码(编码探测覆盖 GBK 等)
+ _ => parsers::plain_text(bytes),
+ };
+
+ let text = normalize(&text);
+ if text.trim().is_empty() {
+ anyhow::bail!("No text could be extracted (possibly a scanned or empty file)");
+ }
+ Ok(ParsedDoc { text })
+}
+
+/// 压缩连续空白行,统一换行符。
+fn normalize(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut blank_run = 0;
+ for line in text.replace("\r\n", "\n").replace('\r', "\n").lines() {
+ let trimmed = line.trim_end();
+ if trimmed.is_empty() {
+ blank_run += 1;
+ if blank_run <= 1 {
+ out.push('\n');
+ }
+ } else {
+ blank_run = 0;
+ out.push_str(trimmed);
+ out.push('\n');
+ }
+ }
+ out
+}
diff --git a/crates/utopia-ingest/src/parsers.rs b/crates/utopia-ingest/src/parsers.rs
new file mode 100644
index 00000000..0084e61c
--- /dev/null
+++ b/crates/utopia-ingest/src/parsers.rs
@@ -0,0 +1,185 @@
+//! 各格式解析器。全部输出纯文本(结构用 markdown 风格标题保留)。
+
+use anyhow::Context;
+use quick_xml::events::Event;
+use quick_xml::Reader;
+use std::io::{Cursor, Read};
+
+/// 文本解码:chardetng 探测编码(覆盖 GBK/GB18030/BIG5 等中文常见编码)。
+pub fn plain_text(bytes: &[u8]) -> String {
+ use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
+ let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);
+ detector.feed(bytes, true);
+ let encoding = detector.guess(None, Utf8Detection::Allow);
+ let (text, _, _) = encoding.decode(bytes);
+ text.into_owned()
+}
+
+pub fn pdf(bytes: &[u8]) -> anyhow::Result<String> {
+ pdf_extract::extract_text_from_mem(bytes).context("PDF text-layer extraction failed")
+}
+
+/// docx: 解压 word/document.xml,取 w:t 文本、w:p 分段。
+pub fn docx(bytes: &[u8]) -> anyhow::Result<String> {
+ let xml = read_zip_entry(bytes, "word/document.xml").context("Malformed docx structure")?;
+ extract_xml_text(&xml, "w:t", "w:p")
+}
+
+/// pptx: 按页码顺序解析 ppt/slides/slideN.xml,取 a:t 文本。
+pub fn pptx(bytes: &[u8]) -> anyhow::Result<String> {
+ let mut archive =
+ zip::ZipArchive::new(Cursor::new(bytes.to_vec())).context("Failed to unzip pptx")?;
+ let mut slides: Vec<(u32, String)> = Vec::new();
+ for i in 0..archive.len() {
+ let name = archive.by_index(i)?.name().to_string();
+ if let Some(num) = name
+ .strip_prefix("ppt/slides/slide")
+ .and_then(|s| s.strip_suffix(".xml"))
+ .and_then(|s| s.parse::<u32>().ok())
+ {
+ slides.push((num, name));
+ }
+ }
+ slides.sort();
+
+ let mut out = String::new();
+ for (num, name) in slides {
+ let mut entry = archive.by_name(&name)?;
+ let mut xml = String::new();
+ entry.read_to_string(&mut xml)?;
+ let text = extract_xml_text(&xml, "a:t", "a:p")?;
+ if !text.trim().is_empty() {
+ out.push_str(&format!("\n## 第 {num} 页\n{text}\n"));
+ }
+ }
+ Ok(out)
+}
+
+/// xlsx / xls / ods: calamine 全格式读取,每 sheet 输出制表符表格(限前 2000 行)。
+pub fn spreadsheet(bytes: &[u8]) -> anyhow::Result<String> {
+ use calamine::{Data, Reader as _};
+ let mut workbook = calamine::open_workbook_auto_from_rs(Cursor::new(bytes.to_vec()))
+ .context("Failed to open spreadsheet")?;
+ let mut out = String::new();
+ for sheet_name in workbook.sheet_names() {
+ let Ok(range) = workbook.worksheet_range(&sheet_name) else {
+ continue;
+ };
+ if range.is_empty() {
+ continue;
+ }
+ out.push_str(&format!("\n# 工作表: {sheet_name}\n"));
+ for row in range.rows().take(2000) {
+ let line: Vec<String> = row
+ .iter()
+ .map(|c| match c {
+ Data::Empty => String::new(),
+ other => other.to_string(),
+ })
+ .collect();
+ if line.iter().any(|s| !s.is_empty()) {
+ out.push_str(&line.join("\t"));
+ out.push('\n');
+ }
+ }
+ }
+ Ok(out)
+}
+
+/// HTML: DOM 遍历取文本,跳过 script/style/noscript/head。
+pub fn html(bytes: &[u8]) -> String {
+ let raw = plain_text(bytes);
+ let doc = scraper::Html::parse_document(&raw);
+ let mut out = String::new();
+ if let Some(title) = doc
+ .select(&scraper::Selector::parse("title").unwrap())
+ .next()
+ {
+ out.push_str(&format!(
+ "# {}\n\n",
+ title.text().collect::<String>().trim()
+ ));
+ }
+ walk_html(doc.root_element(), &mut out);
+ out
+}
+
+fn walk_html(el: scraper::ElementRef, out: &mut String) {
+ const SKIP: &[&str] = &["script", "style", "noscript", "head", "svg", "template"];
+ const BLOCK: &[&str] = &[
+ "p", "div", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "br", "section", "article",
+ ];
+ for node in el.children() {
+ if let Some(child) = scraper::ElementRef::wrap(node) {
+ let tag = child.value().name();
+ if SKIP.contains(&tag) {
+ continue;
+ }
+ walk_html(child, out);
+ if BLOCK.contains(&tag) && !out.ends_with('\n') {
+ out.push('\n');
+ }
+ } else if let Some(text) = node.value().as_text() {
+ let t: &str = text;
+ if !t.trim().is_empty() {
+ out.push_str(t);
+ }
+ }
+ }
+}
+
+pub fn csv_text(bytes: &[u8], tsv: bool) -> anyhow::Result<String> {
+ let decoded = plain_text(bytes);
+ let mut reader = csv::ReaderBuilder::new()
+ .delimiter(if tsv { b'\t' } else { b',' })
+ .flexible(true)
+ .has_headers(false)
+ .from_reader(decoded.as_bytes());
+ let mut out = String::new();
+ for (i, record) in reader.records().enumerate() {
+ if i >= 10_000 {
+ break;
+ }
+ let record = record?;
+ out.push_str(&record.iter().collect::<Vec<_>>().join(" | "));
+ out.push('\n');
+ }
+ Ok(out)
+}
+
+// ---- 工具 ----
+
+fn read_zip_entry(bytes: &[u8], name: &str) -> anyhow::Result<String> {
+ let mut archive = zip::ZipArchive::new(Cursor::new(bytes.to_vec()))?;
+ let mut entry = archive.by_name(name)?;
+ let mut content = String::new();
+ entry.read_to_string(&mut content)?;
+ Ok(content)
+}
+
+/// 从 OOXML 里抽取 `text_tag`(如 w:t)内的文本,遇 `para_tag`(如 w:p)结束换行。
+fn extract_xml_text(xml: &str, text_tag: &str, para_tag: &str) -> anyhow::Result<String> {
+ let mut reader = Reader::from_str(xml);
+ let mut out = String::new();
+ let mut in_text = false;
+ loop {
+ match reader.read_event() {
+ Ok(Event::Start(e)) if e.name().as_ref() == text_tag => in_text = true,
+ Ok(Event::End(e)) => {
+ let name = e.name();
+ if name.as_ref() == text_tag {
+ in_text = false;
+ } else if name.as_ref() == para_tag {
+ out.push('\n');
+ }
+ }
+ Ok(Event::Text(t)) if in_text => {
+ out.push_str(&t.xml_content(quick_xml::XmlVersion::Implicit1_0));
+ }
+ Ok(Event::Eof) => break,
+ Err(e) => anyhow::bail!("XML parse error: {e}"),
+ _ => {}
+ }
+ }
+ Ok(out)
+}
diff --git a/crates/utopia-llm/Cargo.toml b/crates/utopia-llm/Cargo.toml
new file mode 100644
index 00000000..8dcbf269
--- /dev/null
+++ b/crates/utopia-llm/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "utopia-llm"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+reqwest.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+anyhow.workspace = true
+futures-util.workspace = true
+async-stream.workspace = true
+tracing.workspace = true
diff --git a/crates/utopia-llm/src/lib.rs b/crates/utopia-llm/src/lib.rs
new file mode 100644
index 00000000..3d3670c8
--- /dev/null
+++ b/crates/utopia-llm/src/lib.rs
@@ -0,0 +1,341 @@
+//! utopia-llm: OpenAI 兼容协议的薄客户端。
+//! 一套代码适配 DeepSeek / Qwen(DashScope 兼容模式) / GLM / OpenAI / Ollama / vLLM。
+
+use futures_util::{Stream, StreamExt};
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ChatMessage {
+ pub role: String,
+ pub content: String,
+}
+
+/// OpenAI 协议的工具调用(assistant 回合携带)。
+#[derive(Debug, Clone)]
+pub struct ToolCall {
+ pub id: String,
+ pub name: String,
+ /// JSON 字符串参数(协议原样透传)
+ pub arguments: String,
+}
+
+/// 工具对话的一个 assistant 回合:文本与工具调用至少其一。
+#[derive(Debug)]
+pub struct AssistantTurn {
+ pub content: Option<String>,
+ pub tool_calls: Vec<ToolCall>,
+}
+
+impl AssistantTurn {
+ /// 还原为 OpenAI 协议的 assistant 消息(回灌对话历史用)。
+ pub fn to_message(&self) -> serde_json::Value {
+ let mut msg = json!({ "role": "assistant", "content": self.content });
+ if !self.tool_calls.is_empty() {
+ msg["tool_calls"] = json!(self
+ .tool_calls
+ .iter()
+ .map(|c| json!({
+ "id": c.id,
+ "type": "function",
+ "function": { "name": c.name, "arguments": c.arguments },
+ }))
+ .collect::<Vec<_>>());
+ }
+ msg
+ }
+}
+
+/// 工具结果消息(role=tool)。
+pub fn tool_result_message(tool_call_id: &str, content: &str) -> serde_json::Value {
+ json!({ "role": "tool", "tool_call_id": tool_call_id, "content": content })
+}
+
+/// 带工具的流式回合事件。
+#[derive(Debug)]
+pub enum ToolStreamItem {
+ /// 增量正文(即时转发给前端)
+ Delta(String),
+ /// 流结束:完整回合(累积正文 + 归并后的工具调用)
+ Turn(AssistantTurn),
+}
+
+#[derive(Clone)]
+pub struct LlmClient {
+ http: reqwest::Client,
+ base_url: String,
+ api_key: Option<String>,
+ pub model: String,
+}
+
+impl LlmClient {
+ pub fn new(base_url: &str, api_key: Option<&str>, model: &str) -> Self {
+ Self {
+ http: reqwest::Client::new(),
+ base_url: base_url.trim_end_matches('/').to_string(),
+ api_key: api_key.map(String::from),
+ model: model.to_string(),
+ }
+ }
+
+ fn request(&self, path: &str) -> reqwest::RequestBuilder {
+ let mut req = self.http.post(format!("{}{path}", self.base_url));
+ if let Some(key) = &self.api_key {
+ req = req.bearer_auth(key);
+ }
+ req
+ }
+
+ /// 非流式对话(连通性测试等轻量场景)。
+ pub async fn chat(&self, messages: &[ChatMessage]) -> anyhow::Result<String> {
+ let resp = self
+ .request("/chat/completions")
+ .json(&json!({ "model": self.model, "messages": messages, "stream": false }))
+ .send()
+ .await?;
+ let status = resp.status();
+ let body: serde_json::Value = resp.json().await?;
+ if !status.is_success() {
+ anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
+ }
+ body["choices"][0]["message"]["content"]
+ .as_str()
+ .map(String::from)
+ .ok_or_else(|| anyhow::anyhow!("Unexpected LLM response shape: {body}"))
+ }
+
+ /// 工具对话(非流式):messages 为 OpenAI 协议原始 JSON
+ /// (支持 assistant.tool_calls 与 role=tool 回合),tools 为 function 定义数组。
+ pub async fn chat_tools(
+ &self,
+ messages: &[serde_json::Value],
+ tools: &serde_json::Value,
+ ) -> anyhow::Result<AssistantTurn> {
+ let resp = self
+ .request("/chat/completions")
+ .json(&json!({
+ "model": self.model,
+ "messages": messages,
+ "tools": tools,
+ "stream": false,
+ }))
+ .send()
+ .await?;
+ let status = resp.status();
+ let body: serde_json::Value = resp.json().await?;
+ if !status.is_success() {
+ anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
+ }
+ let msg = &body["choices"][0]["message"];
+ if msg.is_null() {
+ anyhow::bail!("Unexpected LLM response shape: {body}");
+ }
+ let content = msg["content"]
+ .as_str()
+ .map(String::from)
+ .filter(|s| !s.is_empty());
+ let tool_calls = msg["tool_calls"]
+ .as_array()
+ .map(|calls| {
+ calls
+ .iter()
+ .filter_map(|c| {
+ Some(ToolCall {
+ id: c["id"].as_str()?.to_string(),
+ name: c["function"]["name"].as_str()?.to_string(),
+ arguments: c["function"]["arguments"]
+ .as_str()
+ .unwrap_or("{}")
+ .to_string(),
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ Ok(AssistantTurn {
+ content,
+ tool_calls,
+ })
+ }
+
+ /// 工具对话(流式):正文增量即时产出,工具调用按 OpenAI 协议的
+ /// index 分片归并(id/name 首帧到达,arguments 逐帧续传),流末给出完整回合。
+ pub async fn chat_tools_stream(
+ &self,
+ messages: &[serde_json::Value],
+ tools: &serde_json::Value,
+ ) -> anyhow::Result<impl Stream<Item = anyhow::Result<ToolStreamItem>> + Send + use<>> {
+ let resp = self
+ .request("/chat/completions")
+ .json(&json!({
+ "model": self.model,
+ "messages": messages,
+ "tools": tools,
+ "stream": true,
+ }))
+ .send()
+ .await?;
+ if !resp.status().is_success() {
+ let status = resp.status();
+ let body: serde_json::Value = resp.json().await.unwrap_or_default();
+ anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
+ }
+
+ let mut bytes = resp.bytes_stream();
+ let stream = async_stream::try_stream! {
+ let mut buf = String::new();
+ let mut content = String::new();
+ let mut calls: Vec<ToolCall> = Vec::new();
+ let mut done = false;
+ 'outer: while let Some(part) = bytes.next().await {
+ let part = part?;
+ buf.push_str(&String::from_utf8_lossy(&part));
+ while let Some(pos) = buf.find("\n\n") {
+ let frame = buf[..pos].to_string();
+ buf.drain(..pos + 2);
+ for line in frame.lines() {
+ let Some(data) = line.strip_prefix("data:").map(str::trim) else {
+ continue;
+ };
+ if data == "[DONE]" {
+ done = true;
+ break 'outer;
+ }
+ let Ok(v) = serde_json::from_str::<serde_json::Value>(data) else {
+ continue;
+ };
+ let delta = &v["choices"][0]["delta"];
+ if let Some(text) = delta["content"].as_str() {
+ if !text.is_empty() {
+ content.push_str(text);
+ yield ToolStreamItem::Delta(text.to_string());
+ }
+ }
+ if let Some(tcs) = delta["tool_calls"].as_array() {
+ for tc in tcs {
+ let idx = tc["index"].as_u64().unwrap_or(0) as usize;
+ while calls.len() <= idx {
+ calls.push(ToolCall {
+ id: String::new(),
+ name: String::new(),
+ arguments: String::new(),
+ });
+ }
+ let slot = &mut calls[idx];
+ if let Some(id) = tc["id"].as_str() {
+ slot.id.push_str(id);
+ }
+ if let Some(n) = tc["function"]["name"].as_str() {
+ slot.name.push_str(n);
+ }
+ if let Some(a) = tc["function"]["arguments"].as_str() {
+ slot.arguments.push_str(a);
+ }
+ }
+ }
+ }
+ }
+ }
+ let _ = done;
+ calls.retain(|c| !c.name.is_empty());
+ let content = if content.is_empty() { None } else { Some(content) };
+ yield ToolStreamItem::Turn(AssistantTurn { content, tool_calls: calls });
+ };
+ Ok(stream)
+ }
+
+ /// 流式对话:产出增量文本片段。
+ pub async fn chat_stream(
+ &self,
+ messages: &[ChatMessage],
+ ) -> anyhow::Result<impl Stream<Item = anyhow::Result<String>> + Send + use<>> {
+ let messages = messages
+ .iter()
+ .map(|m| serde_json::to_value(m).unwrap_or_default())
+ .collect::<Vec<_>>();
+ self.chat_stream_raw(&messages).await
+ }
+
+ /// 流式对话(原始 JSON 消息,可携带工具回合上下文)。
+ pub async fn chat_stream_raw(
+ &self,
+ messages: &[serde_json::Value],
+ ) -> anyhow::Result<impl Stream<Item = anyhow::Result<String>> + Send + use<>> {
+ let resp = self
+ .request("/chat/completions")
+ .json(&json!({ "model": self.model, "messages": messages, "stream": true }))
+ .send()
+ .await?;
+ if !resp.status().is_success() {
+ let status = resp.status();
+ let body: serde_json::Value = resp.json().await.unwrap_or_default();
+ anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body));
+ }
+
+ let mut bytes = resp.bytes_stream();
+ let stream = async_stream::try_stream! {
+ let mut buf = String::new();
+ while let Some(part) = bytes.next().await {
+ let part = part?;
+ buf.push_str(&String::from_utf8_lossy(&part));
+ // SSE 帧以空行分隔;逐帧取出已完整到达的部分
+ while let Some(pos) = buf.find("\n\n") {
+ let frame = buf[..pos].to_string();
+ buf.drain(..pos + 2);
+ for line in frame.lines() {
+ let Some(data) = line.strip_prefix("data:").map(str::trim) else {
+ continue;
+ };
+ if data == "[DONE]" {
+ return;
+ }
+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(data) {
+ if let Some(delta) = v["choices"][0]["delta"]["content"].as_str() {
+ if !delta.is_empty() {
+ yield delta.to_string();
+ }
+ }
+ }
+ }
+ }
+ }
+ };
+ Ok(stream)
+ }
+
+ /// 批量 embedding。
+ pub async fn embed(&self, texts: &[String]) -> anyhow::Result<Vec<Vec<f32>>> {
+ let resp = self
+ .request("/embeddings")
+ .json(&json!({ "model": self.model, "input": texts }))
+ .send()
+ .await?;
+ let status = resp.status();
+ let body: serde_json::Value = resp.json().await?;
+ if !status.is_success() {
+ anyhow::bail!("Embedding request failed ({status}): {}", err_detail(&body));
+ }
+ let data = body["data"]
+ .as_array()
+ .ok_or_else(|| anyhow::anyhow!("Unexpected embedding response shape"))?;
+ let mut out = Vec::with_capacity(data.len());
+ for item in data {
+ let v = item["embedding"]
+ .as_array()
+ .ok_or_else(|| anyhow::anyhow!("Embedding 响应缺少向量"))?
+ .iter()
+ .filter_map(|x| x.as_f64().map(|f| f as f32))
+ .collect();
+ out.push(v);
+ }
+ Ok(out)
+ }
+}
+
+fn err_detail(body: &serde_json::Value) -> String {
+ body["error"]["message"]
+ .as_str()
+ .or_else(|| body["message"].as_str())
+ .unwrap_or("unknown error")
+ .to_string()
+}
diff --git a/crates/utopia-mcp/Cargo.toml b/crates/utopia-mcp/Cargo.toml
new file mode 100644
index 00000000..3e404620
--- /dev/null
+++ b/crates/utopia-mcp/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "utopia-mcp"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
diff --git a/crates/utopia-mcp/src/lib.rs b/crates/utopia-mcp/src/lib.rs
new file mode 100644
index 00000000..f599daef
--- /dev/null
+++ b/crates/utopia-mcp/src/lib.rs
@@ -0,0 +1,3 @@
+//! utopia-mcp: placeholder. MCP server exposing knowledge and agent memory as
+//! tools (add_memory / search_memory / get_entity_timeline).
+//! See the Roadmap in README.md.
diff --git a/crates/utopia-reason/Cargo.toml b/crates/utopia-reason/Cargo.toml
new file mode 100644
index 00000000..c5d73419
--- /dev/null
+++ b/crates/utopia-reason/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "utopia-reason"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
diff --git a/crates/utopia-reason/src/lib.rs b/crates/utopia-reason/src/lib.rs
new file mode 100644
index 00000000..386548c4
--- /dev/null
+++ b/crates/utopia-reason/src/lib.rs
@@ -0,0 +1,3 @@
+//! utopia-reason: placeholder. Temporal Datalog interpreter for derived facts
+//! with explanations, plus the ontology axiom compiler.
+//! See the Roadmap in README.md.
diff --git a/crates/utopia-search/Cargo.toml b/crates/utopia-search/Cargo.toml
new file mode 100644
index 00000000..38817bc1
--- /dev/null
+++ b/crates/utopia-search/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "utopia-search"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+tantivy.workspace = true
+tantivy-jieba.workspace = true
+anyhow.workspace = true
+tracing.workspace = true
diff --git a/crates/utopia-search/src/docs.rs b/crates/utopia-search/src/docs.rs
new file mode 100644
index 00000000..bab16559
--- /dev/null
+++ b/crates/utopia-search/src/docs.rs
@@ -0,0 +1,135 @@
+//! 内置文档(Charter)的内存索引:启动时从打包 markdown 建,进程生命周期内只读。
+//! 协议中立——chat 的 search_docs 工具臂与将来的 MCP 工具面共用这一个入口。
+
+use anyhow::Context;
+use tantivy::collector::TopDocs;
+use tantivy::query::{BooleanQuery, Occur, Query, TermQuery};
+use tantivy::schema::{
+ Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, STORED,
+};
+use tantivy::tokenizer::TextAnalyzer;
+use tantivy::{Index, IndexReader, TantivyDocument, Term};
+
+const JIEBA: &str = "jieba";
+
+/// 一节文档(按 h2 切分;anchor 与前端 Docs 页的标题锚点同法生成)。
+#[derive(Debug, Clone)]
+pub struct DocsSection {
+ pub slug: String,
+ pub title: String,
+ pub heading: String,
+ pub anchor: String,
+ pub body: String,
+}
+
+pub struct DocsIndex {
+ reader: IndexReader,
+ analyzer: TextAnalyzer,
+ f_slug: Field,
+ f_title: Field,
+ f_heading: Field,
+ f_anchor: Field,
+ f_body: Field,
+ f_text: Field,
+}
+
+impl DocsIndex {
+ pub fn build(sections: &[DocsSection]) -> anyhow::Result<Self> {
+ let mut schema_builder = Schema::builder();
+ let text_indexing = TextFieldIndexing::default()
+ .set_tokenizer(JIEBA)
+ .set_index_option(IndexRecordOption::WithFreqsAndPositions);
+ let f_slug = schema_builder.add_text_field("slug", STORED);
+ let f_title = schema_builder.add_text_field("title", STORED);
+ let f_heading = schema_builder.add_text_field("heading", STORED);
+ let f_anchor = schema_builder.add_text_field("anchor", STORED);
+ let f_body = schema_builder.add_text_field("body", STORED);
+ // 检索域 = 节标题 + 正文(标题词权重靠重复出现自然获得)
+ let f_text = schema_builder.add_text_field(
+ "text",
+ TextOptions::default().set_indexing_options(text_indexing),
+ );
+ let schema = schema_builder.build();
+
+ let index = Index::create_in_ram(schema);
+ index
+ .tokenizers()
+ .register(JIEBA, tantivy_jieba::JiebaTokenizer::new());
+
+ let mut writer = index.writer(16 * 1024 * 1024)?;
+ for s in sections {
+ let mut doc = TantivyDocument::default();
+ doc.add_text(f_slug, &s.slug);
+ doc.add_text(f_title, &s.title);
+ doc.add_text(f_heading, &s.heading);
+ doc.add_text(f_anchor, &s.anchor);
+ doc.add_text(f_body, &s.body);
+ doc.add_text(f_text, format!("{}\n{}", s.heading, s.body));
+ writer.add_document(doc)?;
+ }
+ writer.commit()?;
+
+ let reader = index.reader()?;
+ let analyzer = index
+ .tokenizers()
+ .get(JIEBA)
+ .context("jieba tokenizer 未注册")?;
+ Ok(Self {
+ reader,
+ analyzer,
+ f_slug,
+ f_title,
+ f_heading,
+ f_anchor,
+ f_body,
+ f_text,
+ })
+ }
+
+ /// BM25 检索。切词方式与 SearchIndex 一致(手工 OR 组合,避开 CJK 短语查询陷阱)。
+ pub fn search(&self, query: &str, limit: usize) -> anyhow::Result<Vec<DocsSection>> {
+ let mut analyzer = self.analyzer.clone();
+ let mut stream = analyzer.token_stream(query);
+ let mut term_queries: Vec<(Occur, Box<dyn Query>)> = Vec::new();
+ while stream.advance() {
+ let word = stream.token().text.trim().to_string();
+ if word.is_empty() || word.chars().all(|c| !c.is_alphanumeric()) {
+ continue;
+ }
+ term_queries.push((
+ Occur::Should,
+ Box::new(TermQuery::new(
+ Term::from_field_text(self.f_text, &word),
+ IndexRecordOption::WithFreqs,
+ )),
+ ));
+ }
+ if term_queries.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let searcher = self.reader.searcher();
+ let top = searcher.search(
+ &BooleanQuery::new(term_queries),
+ &TopDocs::with_limit(limit).order_by_score(),
+ )?;
+ let get = |doc: &TantivyDocument, f: Field| {
+ doc.get_first(f)
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string()
+ };
+ let mut hits = Vec::with_capacity(top.len());
+ for (_score, addr) in top {
+ let doc: TantivyDocument = searcher.doc(addr)?;
+ hits.push(DocsSection {
+ slug: get(&doc, self.f_slug),
+ title: get(&doc, self.f_title),
+ heading: get(&doc, self.f_heading),
+ anchor: get(&doc, self.f_anchor),
+ body: get(&doc, self.f_body),
+ });
+ }
+ Ok(hits)
+ }
+}
diff --git a/crates/utopia-search/src/lib.rs b/crates/utopia-search/src/lib.rs
new file mode 100644
index 00000000..5fa69c6d
--- /dev/null
+++ b/crates/utopia-search/src/lib.rs
@@ -0,0 +1,174 @@
+//! utopia-search: 内嵌 Tantivy 全文索引(jieba 中文分词)+ RRF 融合。
+//! 单索引多 KB:kb_id 作过滤字段;chunk 正文在 Postgres,索引里只存 id 映射。
+
+mod docs;
+pub use docs::{DocsIndex, DocsSection};
+
+use std::collections::HashMap;
+use std::path::Path;
+use std::sync::Mutex;
+
+use anyhow::Context;
+use tantivy::collector::TopDocs;
+use tantivy::query::{BooleanQuery, Occur, Query, TermQuery};
+use tantivy::schema::{
+ Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, STORED, STRING,
+};
+use tantivy::tokenizer::TextAnalyzer;
+use tantivy::{Index, IndexReader, IndexWriter, TantivyDocument, Term};
+
+const JIEBA: &str = "jieba";
+const WRITER_HEAP: usize = 64 * 1024 * 1024;
+
+pub struct SearchIndex {
+ writer: Mutex<IndexWriter>,
+ reader: IndexReader,
+ analyzer: TextAnalyzer,
+ f_chunk_id: Field,
+ f_kb_id: Field,
+ f_document_id: Field,
+ f_text: Field,
+}
+
+#[derive(Debug, Clone)]
+pub struct Hit {
+ pub chunk_id: String,
+ pub score: f32,
+}
+
+impl SearchIndex {
+ pub fn open(dir: &Path) -> anyhow::Result<Self> {
+ std::fs::create_dir_all(dir)?;
+
+ let mut schema_builder = Schema::builder();
+ let text_indexing = TextFieldIndexing::default()
+ .set_tokenizer(JIEBA)
+ .set_index_option(IndexRecordOption::WithFreqsAndPositions);
+ let f_chunk_id = schema_builder.add_text_field("chunk_id", STRING | STORED);
+ let f_kb_id = schema_builder.add_text_field("kb_id", STRING);
+ let f_document_id = schema_builder.add_text_field("document_id", STRING);
+ let f_text = schema_builder.add_text_field(
+ "text",
+ TextOptions::default().set_indexing_options(text_indexing),
+ );
+ let schema = schema_builder.build();
+
+ let mmap =
+ tantivy::directory::MmapDirectory::open(dir).context("Failed to open index dir")?;
+ let index =
+ Index::open_or_create(mmap, schema).context("Failed to open/create Tantivy index")?;
+ index
+ .tokenizers()
+ .register(JIEBA, tantivy_jieba::JiebaTokenizer::new());
+
+ let writer = index.writer(WRITER_HEAP)?;
+ let reader = index.reader()?;
+ let analyzer = index
+ .tokenizers()
+ .get(JIEBA)
+ .context("jieba tokenizer 未注册")?;
+
+ Ok(Self {
+ writer: Mutex::new(writer),
+ reader,
+ analyzer,
+ f_chunk_id,
+ f_kb_id,
+ f_document_id,
+ f_text,
+ })
+ }
+
+ /// 重建某文档的索引条目(先删后加,幂等),随后 commit。
+ pub fn reindex_document(
+ &self,
+ kb_id: &str,
+ document_id: &str,
+ chunks: &[(String, String)],
+ ) -> anyhow::Result<()> {
+ let mut writer = self.writer.lock().expect("writer 锁中毒");
+ writer.delete_term(Term::from_field_text(self.f_document_id, document_id));
+ for (chunk_id, text) in chunks {
+ let mut doc = TantivyDocument::default();
+ doc.add_text(self.f_chunk_id, chunk_id);
+ doc.add_text(self.f_kb_id, kb_id);
+ doc.add_text(self.f_document_id, document_id);
+ doc.add_text(self.f_text, text);
+ writer.add_document(doc)?;
+ }
+ writer.commit()?;
+ // 写后即可读:不等 reader 的异步重载窗口
+ self.reader.reload()?;
+ Ok(())
+ }
+
+ pub fn delete_document(&self, document_id: &str) -> anyhow::Result<()> {
+ let mut writer = self.writer.lock().expect("writer 锁中毒");
+ writer.delete_term(Term::from_field_text(self.f_document_id, document_id));
+ writer.commit()?;
+ self.reader.reload()?;
+ Ok(())
+ }
+
+ /// BM25 检索(限定 kb)。
+ /// 查询用与索引完全一致的 jieba analyzer 切词后按 OR 组合——
+ /// 不能走 QueryParser:CJK 整句会被当成短语查询(要求词连续出现),召回归零。
+ pub fn search(&self, kb_id: &str, query: &str, limit: usize) -> anyhow::Result<Vec<Hit>> {
+ let mut analyzer = self.analyzer.clone();
+ let mut stream = analyzer.token_stream(query);
+ let mut term_queries: Vec<(Occur, Box<dyn Query>)> = Vec::new();
+ while stream.advance() {
+ let token = stream.token();
+ let word = token.text.trim();
+ if word.is_empty() || word.chars().all(|c| !c.is_alphanumeric()) {
+ continue;
+ }
+ term_queries.push((
+ Occur::Should,
+ Box::new(TermQuery::new(
+ Term::from_field_text(self.f_text, word),
+ IndexRecordOption::WithFreqs,
+ )),
+ ));
+ }
+ if term_queries.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let kb_filter: Box<dyn Query> = Box::new(TermQuery::new(
+ Term::from_field_text(self.f_kb_id, kb_id),
+ IndexRecordOption::Basic,
+ ));
+ let text_query: Box<dyn Query> = Box::new(BooleanQuery::new(term_queries));
+ let combined = BooleanQuery::new(vec![(Occur::Must, kb_filter), (Occur::Must, text_query)]);
+
+ let searcher = self.reader.searcher();
+ let collector = TopDocs::with_limit(limit).order_by_score();
+ let top = searcher.search(&combined, &collector)?;
+ let mut hits = Vec::with_capacity(top.len());
+ for (score, addr) in top {
+ let doc: TantivyDocument = searcher.doc(addr)?;
+ if let Some(chunk_id) = doc.get_first(self.f_chunk_id).and_then(|v| v.as_str()) {
+ hits.push(Hit {
+ chunk_id: chunk_id.to_string(),
+ score,
+ });
+ }
+ }
+ Ok(hits)
+ }
+}
+
+/// Reciprocal Rank Fusion:融合多路召回的排名(k=60 为经验常数)。
+pub fn rrf_fuse(lists: &[Vec<String>], limit: usize) -> Vec<String> {
+ const K: f64 = 60.0;
+ let mut scores: HashMap<String, f64> = HashMap::new();
+ for list in lists {
+ for (rank, id) in list.iter().enumerate() {
+ *scores.entry(id.clone()).or_default() += 1.0 / (K + rank as f64 + 1.0);
+ }
+ }
+ let mut ranked: Vec<(String, f64)> = scores.into_iter().collect();
+ ranked.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
+ ranked.into_iter().take(limit).map(|(id, _)| id).collect()
+}
diff --git a/crates/utopia-server/Cargo.toml b/crates/utopia-server/Cargo.toml
new file mode 100644
index 00000000..e6374eb8
--- /dev/null
+++ b/crates/utopia-server/Cargo.toml
@@ -0,0 +1,40 @@
+[package]
+name = "utopia-server"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[[bin]]
+name = "utopia-server"
+path = "src/main.rs"
+
+[dependencies]
+utopia-core.workspace = true
+utopia-store.workspace = true
+utopia-ingest.workspace = true
+utopia-search.workspace = true
+utopia-llm.workspace = true
+utopia-extract = { path = "../utopia-extract" }
+sha2.workspace = true
+futures-util.workspace = true
+async-stream.workspace = true
+tokio.workspace = true
+axum.workspace = true
+axum-extra.workspace = true
+tower-http.workspace = true
+sqlx.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+anyhow.workspace = true
+uuid.workspace = true
+chrono.workspace = true
+argon2.workspace = true
+jsonwebtoken.workspace = true
+dotenvy.workspace = true
+tracing.workspace = true
+tracing-subscriber.workspace = true
+reqwest.workspace = true
+
+feed-rs.workspace = true
+async-trait = "0.1.92"
+sqlparser = "0.62.0"
diff --git a/crates/utopia-server/src/adjudication.rs b/crates/utopia-server/src/adjudication.rs
new file mode 100644
index 00000000..b778576f
--- /dev/null
+++ b/crates/utopia-server/src/adjudication.rs
@@ -0,0 +1,231 @@
+//! 实体消解攒批裁决任务:消费审核队列中 stage=adjudicating 的灰区对。
+//! 先查裁决缓存,缓存未命中的攒成一批(一次 LLM 调用裁多对);
+//! 高置信 same → 自动合并(可回滚),高置信 different → 自动保持分开,
+//! 其余转人工。未配模型时全部转人工——本任务失败或缺席都不影响抽取与查询。
+
+use crate::llm_util;
+use crate::state::AppState;
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+use utopia_core::models::ReviewItem;
+use utopia_core::AppError;
+use uuid::Uuid;
+
+const BATCH_SIZE: i64 = 12;
+const AUTO_CONF: f32 = 0.8;
+const MAX_ROUNDS: usize = 20;
+
+/// 缓存键:类型 + 双方名字 + 事实摘要(与实体 id 无关——重传文档不重复付费)。
+fn pair_key(item: &ReviewItem) -> String {
+ let side = |s: &utopia_core::models::ReviewSide| {
+ format!(
+ "{}|{}|{}",
+ s.name.to_lowercase(),
+ s.type_label,
+ s.top_facts.join(";")
+ )
+ };
+ let mut sides = [side(&item.left), side(&item.right)];
+ sides.sort();
+ let digest = Sha256::digest(sides.join("##").as_bytes());
+ digest.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+pub async fn adjudicate_entities(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
+ let settings = utopia_store::settings::get(&state.pool, kb.workspace_id).await?;
+ let client = settings.as_ref().and_then(llm_util::chat_client);
+ let model = settings
+ .as_ref()
+ .and_then(|s| s.chat_model.clone())
+ .unwrap_or_default();
+
+ let Some(client) = client else {
+ // 无模型可用:全部转人工,任务本身成功结束
+ let items =
+ utopia_store::resolution::pending_adjudications(&state.pool, kb_id, 500).await?;
+ for item in items {
+ utopia_store::resolution::escalate_review(
+ &state.pool,
+ item.id,
+ "chat model not configured — needs human review",
+ )
+ .await?;
+ }
+ state.emit_review(kb_id);
+ return Ok(());
+ };
+
+ for _ in 0..MAX_ROUNDS {
+ let items =
+ utopia_store::resolution::pending_adjudications(&state.pool, kb_id, BATCH_SIZE).await?;
+ if items.is_empty() {
+ break;
+ }
+
+ // 第一层:裁决缓存
+ let mut to_ask: Vec<(ReviewItem, String)> = Vec::new();
+ for item in items {
+ let key = pair_key(&item);
+ match utopia_store::resolution::get_verdict(&state.pool, kb_id, &key).await? {
+ Some((same, conf)) => {
+ apply_verdict(state, kb_id, &item, same, conf, "cached").await?
+ }
+ None => to_ask.push((item, key)),
+ }
+ }
+ if to_ask.is_empty() {
+ continue;
+ }
+
+ // 第二层:攒批 LLM 裁决
+ let pairs: Vec<utopia_extract::AdjudicationPair> = to_ask
+ .iter()
+ .map(|(item, _)| utopia_extract::AdjudicationPair {
+ left: utopia_extract::AdjudicationSide {
+ name: item.left.name.clone(),
+ type_label: item.left.type_label.clone(),
+ facts: item.left.top_facts.clone(),
+ },
+ right: utopia_extract::AdjudicationSide {
+ name: item.right.name.clone(),
+ type_label: item.right.type_label.clone(),
+ facts: item.right.top_facts.clone(),
+ },
+ })
+ .collect();
+ let messages = utopia_extract::build_adjudication_messages(&pairs);
+ // 调用/解析失败 → 任务按退避重试;重试耗尽后行停留在队列里,人工仍可定夺
+ let reply = client.chat(&messages).await?;
+ let verdicts = utopia_extract::parse_adjudication(&reply)?;
+ let by_i: HashMap<usize, &utopia_extract::AdjudicationVerdict> =
+ verdicts.iter().map(|v| (v.i, v)).collect();
+
+ for (idx, (item, key)) in to_ask.iter().enumerate() {
+ match by_i.get(&idx) {
+ Some(v) => {
+ let same = match v.verdict.as_str() {
+ "same" => Some(true),
+ "different" => Some(false),
+ _ => None,
+ };
+ let conf = v.confidence.unwrap_or(0.5).clamp(0.0, 1.0);
+ utopia_store::resolution::put_verdict(
+ &state.pool,
+ kb_id,
+ key,
+ same,
+ conf,
+ &model,
+ )
+ .await?;
+ apply_verdict(state, kb_id, item, same, conf, "adjudicated").await?;
+ }
+ None => {
+ utopia_store::resolution::escalate_review(
+ &state.pool,
+ item.id,
+ "adjudicator returned no verdict — needs human review",
+ )
+ .await?;
+ }
+ }
+ }
+ // 本轮裁决落库完毕,推给前端刷新审核队列
+ state.emit_review(kb_id);
+ }
+ Ok(())
+}
+
+async fn apply_verdict(
+ state: &AppState,
+ kb_id: Uuid,
+ item: &ReviewItem,
+ same: Option<bool>,
+ conf: f32,
+ via: &str,
+) -> anyhow::Result<()> {
+ match same {
+ Some(true) if conf >= AUTO_CONF => {
+ let (target, source) =
+ utopia_store::resolution::merge_direction(&state.pool, item.left.id, item.right.id)
+ .await?;
+ let reason = format!("auto-merge: {via} same (confidence {conf:.2})");
+ match utopia_store::resolution::merge_entities(
+ &state.pool,
+ kb_id,
+ source,
+ target,
+ None,
+ &reason,
+ )
+ .await
+ {
+ Ok(_) => {
+ utopia_store::resolution::close_review_auto(
+ &state.pool,
+ item.id,
+ "merged",
+ &reason,
+ )
+ .await?;
+ // 决策台账:AI 自动合并(actor 为空 = 系统)
+ let _ = utopia_store::audit::record_opt(
+ &state.pool,
+ Some(kb_id),
+ None,
+ "review.merge",
+ "review",
+ Some(item.id),
+ serde_json::json!({
+ "left": item.left.name, "right": item.right.name,
+ "score": item.score, "confidence": conf, "via": via,
+ }),
+ )
+ .await;
+ }
+ // 同批次连锁合并可能已吞掉其中一方:转人工而不是让任务失败
+ Err(AppError::Conflict(_)) | Err(AppError::NotFound) => {
+ utopia_store::resolution::escalate_review(
+ &state.pool,
+ item.id,
+ "entity changed during adjudication — needs human review",
+ )
+ .await?;
+ }
+ Err(e) => return Err(e.into()),
+ }
+ }
+ Some(false) if conf >= AUTO_CONF => {
+ utopia_store::resolution::close_review_auto(
+ &state.pool,
+ item.id,
+ "kept",
+ &format!("{via} different (confidence {conf:.2})"),
+ )
+ .await?;
+ let _ = utopia_store::audit::record_opt(
+ &state.pool,
+ Some(kb_id),
+ None,
+ "review.keep",
+ "review",
+ Some(item.id),
+ serde_json::json!({
+ "left": item.left.name, "right": item.right.name,
+ "score": item.score, "confidence": conf, "via": via,
+ }),
+ )
+ .await;
+ }
+ _ => {
+ utopia_store::resolution::escalate_review(
+ &state.pool,
+ item.id,
+ &format!("{via} unsure (confidence {conf:.2}) — needs human review"),
+ )
+ .await?;
+ }
+ }
+ Ok(())
+}
diff --git a/crates/utopia-server/src/api/admin_routes.rs b/crates/utopia-server/src/api/admin_routes.rs
new file mode 100644
index 00000000..04e044e4
--- /dev/null
+++ b/crates/utopia-server/src/api/admin_routes.rs
@@ -0,0 +1,103 @@
+//! 系统管理 API(仅系统管理员):部署配置 + 代开账号。
+
+use axum::extract::State;
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::{Role, User};
+use utopia_core::AppError;
+
+use crate::auth::{self, AuthUser};
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+fn require_admin(user: &User) -> Result<(), AppError> {
+ if user.is_admin {
+ Ok(())
+ } else {
+ Err(AppError::Forbidden)
+ }
+}
+
+pub async fn get_deployment(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let open = utopia_store::access::open_registration(&state.pool).await?;
+ let workers = utopia_store::access::worker_concurrency(&state.pool).await?;
+ Ok(Json(
+ json!({ "open_registration": open, "worker_concurrency": workers }),
+ ))
+}
+
+#[derive(Deserialize)]
+pub struct DeploymentReq {
+ pub open_registration: bool,
+ /// 任务 worker 并发数(1-32);缺省不改
+ #[serde(default)]
+ pub worker_concurrency: Option<i32>,
+}
+
+pub async fn put_deployment(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(req): Json<DeploymentReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ utopia_store::access::set_open_registration(&state.pool, req.open_registration).await?;
+ if let Some(n) = req.worker_concurrency {
+ utopia_store::access::set_worker_concurrency(&state.pool, n).await?;
+ // 热生效:调度循环每轮读这个值,无需重启
+ state
+ .worker_concurrency
+ .store(n as usize, std::sync::atomic::Ordering::Relaxed);
+ }
+ Ok(Json(json!({ "ok": true })))
+}
+
+#[derive(Deserialize)]
+pub struct CreateUserReq {
+ pub email: String,
+ pub display_name: String,
+ pub password: String,
+ /// 部署角色:admin | editor | viewer
+ #[serde(default)]
+ pub role: Option<String>,
+}
+
+/// 管理员代开账号(注册关闭后的唯一入口)。
+pub async fn create_user(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(req): Json<CreateUserReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ if !req.email.contains('@') || req.email.len() > 254 {
+ return Err(AppError::Validation("Invalid email address".into()).into());
+ }
+ if req.password.chars().count() < 8 {
+ return Err(AppError::Validation("Password must be at least 8 characters".into()).into());
+ }
+ if req.display_name.trim().is_empty() || req.display_name.chars().count() > 64 {
+ return Err(AppError::Validation("Display name must be 1-64 characters".into()).into());
+ }
+ let role = match req.role.as_deref().unwrap_or("editor") {
+ "admin" => Role::Admin,
+ "editor" => Role::Editor,
+ "viewer" => Role::Viewer,
+ _ => {
+ return Err(AppError::Validation("role must be admin, editor or viewer".into()).into())
+ }
+ };
+ let hash = auth::hash_password(&req.password)?;
+ let created = utopia_store::accounts::admin_create_user(
+ &state.pool,
+ req.email.trim(),
+ &hash,
+ req.display_name.trim(),
+ role,
+ )
+ .await?;
+ Ok(Json(json!({ "user": created })))
+}
diff --git a/crates/utopia-server/src/api/auth_routes.rs b/crates/utopia-server/src/api/auth_routes.rs
new file mode 100644
index 00000000..d8cfceaa
--- /dev/null
+++ b/crates/utopia-server/src/api/auth_routes.rs
@@ -0,0 +1,144 @@
+use axum::extract::State;
+use axum::Json;
+use axum_extra::extract::cookie::{Cookie, CookieJar};
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::{User, Workspace};
+use utopia_core::AppError;
+
+use crate::auth::{self, AuthUser};
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+#[derive(Deserialize)]
+pub struct RegisterReq {
+ pub email: String,
+ pub password: String,
+ pub display_name: String,
+ pub org_name: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct LoginReq {
+ pub email: String,
+ pub password: String,
+}
+
+fn validate_register(req: &RegisterReq) -> Result<(), AppError> {
+ if !req.email.contains('@') || req.email.len() > 254 {
+ return Err(AppError::Validation("Invalid email address".into()));
+ }
+ if req.password.chars().count() < 8 {
+ return Err(AppError::Validation(
+ "Password must be at least 8 characters".into(),
+ ));
+ }
+ if req.display_name.trim().is_empty() || req.display_name.chars().count() > 64 {
+ return Err(AppError::Validation(
+ "Display name must be 1-64 characters".into(),
+ ));
+ }
+ Ok(())
+}
+
+pub async fn register(
+ State(state): State<AppState>,
+ jar: CookieJar,
+ Json(req): Json<RegisterReq>,
+) -> ApiResult<(CookieJar, Json<serde_json::Value>)> {
+ validate_register(&req)?;
+ let hash = auth::hash_password(&req.password)?;
+ let org_name = req
+ .org_name
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+
+ // 注册开关:库内配置(/admin 可切)优先;建库前(首用户引导)总是放行
+ let open = utopia_store::access::open_registration(&state.pool)
+ .await
+ .unwrap_or(state.open_registration);
+ let (user, workspace): (User, Workspace) = utopia_store::accounts::register(
+ &state.pool,
+ req.email.trim(),
+ &hash,
+ req.display_name.trim(),
+ org_name,
+ open,
+ )
+ .await?;
+
+ let token = auth::issue_token(&state, user.id)?;
+ let jar = jar.add(auth::auth_cookie(token.clone()));
+ Ok((
+ jar,
+ Json(json!({ "user": user, "workspace": workspace, "token": token })),
+ ))
+}
+
+pub async fn login(
+ State(state): State<AppState>,
+ jar: CookieJar,
+ Json(req): Json<LoginReq>,
+) -> ApiResult<(CookieJar, Json<serde_json::Value>)> {
+ let user = utopia_store::accounts::find_user_by_email(&state.pool, req.email.trim())
+ .await?
+ .ok_or(AppError::Unauthorized)?;
+ if !auth::verify_password(&req.password, &user.password_hash) {
+ return Err(AppError::Unauthorized.into());
+ }
+ let token = auth::issue_token(&state, user.id)?;
+ let jar = jar.add(auth::auth_cookie(token.clone()));
+ Ok((jar, Json(json!({ "user": user, "token": token }))))
+}
+
+pub async fn logout(jar: CookieJar) -> (CookieJar, Json<serde_json::Value>) {
+ let jar = jar.remove(Cookie::from(auth::COOKIE_NAME));
+ (jar, Json(json!({ "ok": true })))
+}
+
+pub async fn me(AuthUser(user): AuthUser) -> Json<User> {
+ Json(user)
+}
+
+#[derive(Deserialize)]
+pub struct UpdateMeReq {
+ pub display_name: String,
+}
+
+/// 个人资料:改显示名。
+pub async fn update_me(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(req): Json<UpdateMeReq>,
+) -> ApiResult<Json<User>> {
+ let name = req.display_name.trim();
+ if name.is_empty() || name.chars().count() > 64 {
+ return Err(AppError::Validation("Display name must be 1-64 characters".into()).into());
+ }
+ let updated = utopia_store::accounts::update_display_name(&state.pool, user.id, name).await?;
+ Ok(Json(updated))
+}
+
+#[derive(Deserialize)]
+pub struct ChangePasswordReq {
+ pub current_password: String,
+ pub new_password: String,
+}
+
+/// 改密码:验旧密 → 哈希新密。旧密错误与"未登录"区分开,前端能给出准确提示。
+pub async fn change_password(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(req): Json<ChangePasswordReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ if !auth::verify_password(&req.current_password, &user.password_hash) {
+ return Err(AppError::Validation("Current password is incorrect".into()).into());
+ }
+ if req.new_password.chars().count() < 8 {
+ return Err(AppError::Validation("Password must be at least 8 characters".into()).into());
+ }
+ let hash = auth::hash_password(&req.new_password)?;
+ utopia_store::accounts::update_password(&state.pool, user.id, &hash).await?;
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/api/chat.rs b/crates/utopia-server/src/api/chat.rs
new file mode 100644
index 00000000..83132b6e
--- /dev/null
+++ b/crates/utopia-server/src/api/chat.rs
@@ -0,0 +1,829 @@
+//! Agentic 对话:模型自主调用工具(文档检索 / 实体查找 / 时态事实)收集证据后作答。
+//! 事件序列:step*(行动轨迹)| sources(引用清单,随检索增量更新)| delta*(增量文本)→ done | error。
+//! 模型不支持 tool-calling 时自动降级为一次性 RAG 注入。
+
+use axum::extract::{Path, State};
+use axum::response::sse::{Event, KeepAlive, Sse};
+use axum::Json;
+use futures_util::{Stream, StreamExt};
+use serde::Deserialize;
+use serde_json::json;
+use std::convert::Infallible;
+use utopia_core::models::{ChunkView, EntityFact, Role};
+use utopia_core::AppError;
+use utopia_llm::tool_result_message;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::llm_util;
+use crate::retrieval;
+use crate::state::AppState;
+
+const MAX_HISTORY: usize = 20;
+const MAX_ROUNDS: usize = 6;
+const SEARCH_TOP_K: usize = 6;
+const TOOL_CHUNK_CHARS: usize = 800;
+
+#[derive(Deserialize)]
+pub struct ChatReq {
+ /// 缺省 = 新建会话(SSE 首个 `conversation` 事件回传 id)
+ #[serde(default)]
+ pub conversation_id: Option<Uuid>,
+ pub message: String,
+}
+
+fn tools_schema(can_write: bool, data_source_names: &[String]) -> serde_json::Value {
+ let mut tools = base_tools();
+ if !data_source_names.is_empty() {
+ if let Some(arr) = tools.as_array_mut() {
+ arr.push(json!({
+ "type": "function",
+ "function": {
+ "name": "query_data",
+ "description": format!(
+ "Run a read-only SQL query against a mounted database. Available sources: \
+ {}. Search the source's schema document first (search_chunks) if unsure \
+ of tables/columns. Only a single SELECT/WITH statement is allowed; a \
+ LIMIT is enforced server-side; results come back as JSON lines. If the \
+ query errors, fix the SQL and retry once.",
+ data_source_names.join(", ")
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "data_source": {
+ "type": "string",
+ "description": "Name of the mounted data source to query."
+ },
+ "sql": {
+ "type": "string",
+ "description": "One SELECT/WITH statement (PostgreSQL dialect)."
+ },
+ "purpose": {
+ "type": "string",
+ "description": "One short phrase: what this query answers (shown to the user)."
+ }
+ },
+ "required": ["data_source", "sql"]
+ }
+ }
+ }));
+ }
+ }
+ if can_write {
+ if let Some(arr) = tools.as_array_mut() {
+ arr.push(json!({
+ "type": "function",
+ "function": {
+ "name": "remember",
+ "description": "Record one memory episode into the knowledge base's temporal \
+ memory. Use ONLY when the user explicitly asks to remember/record \
+ something, or clearly states a decision or fact to keep. The episode is \
+ extracted into the knowledge graph; if it contradicts an existing \
+ single-valued fact, the old fact's validity is closed automatically \
+ (never deleted). Do not use for casual conversation.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "The episode to remember, one self-contained \
+ statement (who/what, with names spelled out)."
+ },
+ "occurred_at": {
+ "type": "string",
+ "description": "Optional date the stated fact took effect \
+ (YYYY-MM-DD). Omit to use today."
+ }
+ },
+ "required": ["text"]
+ }
+ }
+ }));
+ }
+ }
+ tools
+}
+
+const MEMORY_PROMPT: &str = "\
+ Memory: you can persist knowledge with the remember tool. Use it when the user says \
+ \"remember/record this\" or states a decision meant to last. Confirm in your reply what \
+ was recorded. Never invent memories, and never call it for small talk.";
+
+fn base_tools() -> serde_json::Value {
+ json!([
+ {
+ "type": "function",
+ "function": {
+ "name": "search_chunks",
+ "description": "Full-text + semantic search over the knowledge base documents. \
+ Returns numbered source excerpts you can cite as [n].",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string", "description": "Search query, phrased in the corpus language." }
+ },
+ "required": ["query"]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "search_docs",
+ "description": "Search Utopia's own user manual (the Charter): how the platform \
+ itself works — sources and ingestion, sync semantics (missing markers, \
+ tombstones, versions), the knowledge graph and review flow, roles and \
+ permissions, settings. Use ONLY for questions about using or understanding \
+ Utopia itself, or to explain platform concepts that appear in other tool \
+ results (e.g. why a document is marked missing). NEVER use it to answer \
+ questions about the content stored in the knowledge base.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string", "description": "What to look up in the manual." }
+ },
+ "required": ["query"]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "find_entities",
+ "description": "Look up entities in the knowledge graph by (partial) name. \
+ Returns id, name, type and a disambiguator when several entities share a name.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "name": { "type": "string", "description": "Entity name or a fragment of it." }
+ },
+ "required": ["name"]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "entity_facts",
+ "description": "Facts about one entity from the bi-temporal knowledge graph: \
+ relations with validity ranges (from → to; 'now' = still ongoing). \
+ The best tool for who/when/history questions. Use after find_entities. \
+ Pass `at` to see the world as of that date (server-side filter) — \
+ always do this for \"who was X in <year/month>\" questions.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "entity_id": { "type": "string", "description": "Entity id (uuid) from find_entities." },
+ "at": {
+ "type": "string",
+ "description": "Optional as-of date (YYYY-MM-DD). Only facts valid on \
+ this date are returned. Omit for the full history."
+ }
+ },
+ "required": ["entity_id"]
+ }
+ }
+ }
+ ])
+}
+
+const SYSTEM_PROMPT: &str = "You are the assistant of Utopia, a temporal knowledge platform. \
+ You have tools: search_chunks (document search), find_entities and entity_facts (a \
+ bi-temporal knowledge graph where every relation carries a validity range), and \
+ search_docs (Utopia's own manual, the Charter).\n\
+ Boundary: search_docs answers questions about Utopia itself (features, ingestion, \
+ permissions, what fields like 'missing' or validity ranges mean); the other tools answer \
+ questions about the knowledge stored in it. Never mix the manual into answers about the \
+ user's data unless they asked about Utopia's behavior.\n\
+ \n\
+ Method:\n\
+ 1. For factual questions, ALWAYS gather evidence with tools before answering. Prefer the \
+ graph tools for questions about people/organizations/projects and time (\"who was X \
+ when\", \"what changed\"), search_chunks for content and detail questions. Combine both \
+ when useful.\n\
+ 2. Facts carry validity ranges (from → to). For \"as of <date>\" questions pass `at` to \
+ entity_facts and the server filters to that moment; for history questions omit `at` \
+ to see the full timeline. State dates in the answer.\n\
+ 3. Several entities can share one name — check the disambiguator and pick the right one; \
+ if genuinely ambiguous, ask the user which one they mean.\n\
+ 4. Stop calling tools as soon as you have enough evidence. Then answer concisely: cite \
+ document sources with [n] (numbers from search results) at the end of supported \
+ sentences. If the evidence is insufficient, say so explicitly — never fabricate.\n\
+ 5. Always respond in the same language as the user's question.";
+
+pub async fn chat(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<ChatReq>,
+) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
+ let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ // 写工具跟人走:editor 及以上的对话才带 remember,viewer 纯只读
+ // 挂载的数据源决定 query_data 是否入列(问数是读,viewer 亦可用)
+ let mounted_sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
+ // 语义层:人确认过的 指标/维度 → 数据资产 映射(置信 ≥0.75,与 Review 阈值互补),
+ // 直接进 system prompt——问数优先用确认口径,而不是每次从 schema 猜
+ let mappings = if mounted_sources.is_empty() {
+ Vec::new()
+ } else {
+ utopia_store::graph::confirmed_mappings(&state.pool, kb_id, 0.75, 30).await?
+ };
+ let can_write = utopia_store::access::kb_role(&state.pool, &user, &kb)
+ .await?
+ .is_some_and(|r| r >= Role::Editor);
+
+ const NO_MODEL: &str = "Chat model not configured. Go to Settings → Models.";
+ let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
+ .await?
+ .ok_or_else(|| AppError::Validation(NO_MODEL.into()))?;
+ let client =
+ llm_util::chat_client(&settings).ok_or_else(|| AppError::Validation(NO_MODEL.into()))?;
+
+ let query = req.message.trim().to_string();
+ if query.is_empty() {
+ return Err(AppError::Validation("Missing user message".into()).into());
+ }
+
+ // 会话持久化:有 id 则校验归属,无则以首句为题新建;用户消息即刻落库,
+ // 上下文由服务端从库里拼——前端只送新消息
+ let conversation_id = match req.conversation_id {
+ Some(id) => {
+ utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, id).await?;
+ id
+ }
+ None => utopia_store::conversations::create(&state.pool, kb_id, user.id, &query).await?,
+ };
+ utopia_store::conversations::append_message(
+ &state.pool,
+ conversation_id,
+ "user",
+ &query,
+ &json!([]),
+ &json!([]),
+ )
+ .await?;
+ let history: Vec<(String, String)> = utopia_store::conversations::recent_context(
+ &state.pool,
+ conversation_id,
+ MAX_HISTORY as i64,
+ )
+ .await?;
+ let workspace_id = kb.workspace_id;
+
+ let stream = async_stream::stream! {
+ let ds_names: Vec<String> = mounted_sources.iter().map(|d| d.name.clone()).collect();
+ let tools = tools_schema(can_write, &ds_names);
+ let mut system_prompt = if can_write {
+ format!("{SYSTEM_PROMPT}\n{MEMORY_PROMPT}")
+ } else {
+ SYSTEM_PROMPT.to_string()
+ };
+ if !ds_names.is_empty() {
+ system_prompt.push_str(&format!(
+ "\nData: query_data runs read-only SQL (PostgreSQL dialect) against: {}. \
+ For questions about numbers/metrics, search for the source's schema document \
+ first, then query. State units and the time range you used in the answer.",
+ ds_names.join(", ")
+ ));
+ if !mappings.is_empty() {
+ system_prompt.push_str(
+ "\nSemantic layer (confirmed definitions — use these instead of guessing from schema):",
+ );
+ for (name, def) in &mappings {
+ system_prompt.push_str(&format!("\n- {name}: {def}"));
+ }
+ }
+ }
+ let mut msgs: Vec<serde_json::Value> =
+ vec![json!({ "role": "system", "content": system_prompt })];
+ for (role, content) in &history {
+ msgs.push(json!({ "role": role, "content": content }));
+ }
+
+ // 会话 id 先行下发(新会话由此告知前端)
+ yield Ok(Event::default()
+ .event("conversation")
+ .data(json!({ "id": conversation_id }).to_string()));
+
+ // 引用清单:跨轮累积、去重、编号稳定。键 = chunk uuid 或 "charter:{slug}#{anchor}"
+ let mut source_ids: Vec<String> = Vec::new();
+ let mut sources: Vec<serde_json::Value> = Vec::new();
+ // 落库累积:assistant 全文与行动轨迹(历史回放用)
+ let mut answer_acc = String::new();
+ let mut steps_acc: Vec<serde_json::Value> = Vec::new();
+
+ let mut rounds = 0usize;
+ loop {
+ if rounds >= MAX_ROUNDS {
+ // 弹药耗尽:命令模型就现有证据作答(流式)
+ msgs.push(json!({
+ "role": "user",
+ "content": "(system) Tool budget exhausted. Answer now from the evidence gathered above.",
+ }));
+ match client.chat_stream_raw(&msgs).await {
+ Ok(deltas) => {
+ let mut deltas = std::pin::pin!(deltas);
+ while let Some(item) = deltas.next().await {
+ match item {
+ Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); }
+ Err(e) => { yield error_event(&e.to_string()); return; }
+ }
+ }
+ let _ = utopia_store::conversations::append_message(
+ &state.pool, conversation_id, "assistant", &answer_acc,
+ &serde_json::Value::Array(steps_acc.clone()),
+ &serde_json::Value::Array(sources.clone()),
+ ).await;
+ yield done_event();
+ }
+ Err(e) => yield error_event(&e.to_string()),
+ }
+ return;
+ }
+
+ // 主链路全程流式:正文增量即时转发,工具调用在流末归并到达
+ let deltas = match client.chat_tools_stream(&msgs, &tools).await {
+ Ok(s) => s,
+ Err(e) => {
+ if rounds == 0 {
+ // 模型可能不支持 tool-calling:降级为一次性 RAG 注入
+ tracing::warn!(error = %e, "tool-calling 不可用,降级为一次性 RAG");
+ let chunks =
+ retrieval::hybrid(&state, kb_id, workspace_id, &query, 8)
+ .await
+ .unwrap_or_default();
+ let legacy_sources: Vec<serde_json::Value> = chunks
+ .iter()
+ .enumerate()
+ .map(|(i, c)| source_json(i + 1, c))
+ .collect();
+ yield Ok(Event::default().event("sources").data(
+ serde_json::to_string(&legacy_sources)
+ .unwrap_or_else(|_| "[]".into()),
+ ));
+ let mut lmsgs =
+ vec![json!({ "role": "system", "content": legacy_system_prompt(&chunks) })];
+ for (role, content) in &history {
+ lmsgs.push(json!({ "role": role, "content": content }));
+ }
+ match client.chat_stream_raw(&lmsgs).await {
+ Ok(deltas) => {
+ let mut deltas = std::pin::pin!(deltas);
+ while let Some(item) = deltas.next().await {
+ match item {
+ Ok(text) => { answer_acc.push_str(&text); yield delta_event(&text); }
+ Err(e2) => { yield error_event(&e2.to_string()); return; }
+ }
+ }
+ let _ = utopia_store::conversations::append_message(
+ &state.pool, conversation_id, "assistant", &answer_acc,
+ &serde_json::Value::Array(steps_acc.clone()),
+ &serde_json::Value::Array(legacy_sources.clone()),
+ ).await;
+ yield done_event();
+ }
+ Err(e2) => yield error_event(&e2.to_string()),
+ }
+ return;
+ }
+ yield error_event(&e.to_string());
+ return;
+ }
+ };
+ let mut turn: Option<utopia_llm::AssistantTurn> = None;
+ {
+ let mut deltas = std::pin::pin!(deltas);
+ while let Some(item) = deltas.next().await {
+ match item {
+ Ok(utopia_llm::ToolStreamItem::Delta(text)) => {
+ answer_acc.push_str(&text);
+ yield delta_event(&text);
+ }
+ Ok(utopia_llm::ToolStreamItem::Turn(t)) => turn = Some(t),
+ Err(e) => {
+ yield error_event(&e.to_string());
+ return;
+ }
+ }
+ }
+ }
+ let Some(turn) = turn else {
+ yield error_event("LLM stream ended unexpectedly");
+ return;
+ };
+
+ if turn.tool_calls.is_empty() {
+ if answer_acc.is_empty() {
+ yield error_event("Model returned an empty answer");
+ } else {
+ let _ = utopia_store::conversations::append_message(
+ &state.pool, conversation_id, "assistant", &answer_acc,
+ &serde_json::Value::Array(steps_acc.clone()),
+ &serde_json::Value::Array(sources.clone()),
+ ).await;
+ yield done_event();
+ }
+ return;
+ }
+
+ // 工具轮带了叙述文本:与后续轮次的正文之间补一个段落分隔
+ if turn.content.is_some() && !answer_acc.is_empty() {
+ answer_acc.push_str("\n\n");
+ yield delta_event("\n\n");
+ }
+
+ msgs.push(turn.to_message());
+ for call in &turn.tool_calls {
+ let args: serde_json::Value =
+ serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({}));
+ let (result, step) = match call.name.as_str() {
+ "search_chunks" => {
+ let q = args["query"].as_str().unwrap_or(&query).to_string();
+ let chunks = retrieval::hybrid(&state, kb_id, workspace_id, &q, SEARCH_TOP_K)
+ .await
+ .unwrap_or_default();
+ let mut lines = Vec::new();
+ for c in &chunks {
+ let key = c.id.to_string();
+ let n = match source_ids.iter().position(|id| *id == key) {
+ Some(i) => i + 1,
+ None => {
+ source_ids.push(key);
+ sources.push(source_json(source_ids.len(), c));
+ source_ids.len()
+ }
+ };
+ lines.push(format!(
+ "[{n}] \"{}\" section {}:\n{}",
+ c.filename,
+ c.seq + 1,
+ truncate(&c.text, TOOL_CHUNK_CHARS)
+ ));
+ }
+ let text = if lines.is_empty() {
+ "No results.".to_string()
+ } else {
+ lines.join("\n\n")
+ };
+ (text, json!({ "kind": "search", "label": q, "detail": format!("{} sources", chunks.len()) }))
+ }
+ "search_docs" => {
+ let q = args["query"].as_str().unwrap_or(&query).to_string();
+ let hits = state.docs.search(&q, 4).unwrap_or_default();
+ let mut lines = Vec::new();
+ for h in &hits {
+ let key = format!("charter:{}#{}", h.slug, h.anchor);
+ let n = match source_ids.iter().position(|id| *id == key) {
+ Some(i) => i + 1,
+ None => {
+ source_ids.push(key);
+ sources.push(charter_source_json(source_ids.len(), h));
+ source_ids.len()
+ }
+ };
+ lines.push(format!(
+ "[{n}] Utopia Charter — {} › {}:\n{}",
+ h.title,
+ h.heading,
+ truncate(&h.body, 1600)
+ ));
+ }
+ let text = if lines.is_empty() {
+ "No matching manual sections.".to_string()
+ } else {
+ lines.join("\n\n")
+ };
+ (text, json!({ "kind": "docs", "label": q, "detail": format!("{} sections", hits.len()) }))
+ }
+ "find_entities" => {
+ let name = args["name"].as_str().unwrap_or("").to_string();
+ let hits = utopia_store::graph::search_entities(&state.pool, kb_id, &name, 8)
+ .await
+ .unwrap_or_default();
+ let text = if hits.is_empty() {
+ "No matching entities.".to_string()
+ } else {
+ hits.iter()
+ .map(|n| {
+ let dis = n
+ .disambiguator
+ .as_deref()
+ .map(|d| format!(" ({d})"))
+ .unwrap_or_default();
+ format!(
+ "{} | {}{} | {} | {} facts",
+ n.id, n.name, dis, n.type_label, n.degree
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ };
+ (text, json!({ "kind": "entity", "label": name, "detail": format!("{} matches", hits.len()) }))
+ }
+ "entity_facts" => {
+ let id = args["entity_id"].as_str().and_then(|s| s.parse::<Uuid>().ok());
+ // as-of 过滤:T 时刻有效 = 起点不晚于 T(或未知)且终点晚于 T(或开放)
+ let at = args["at"]
+ .as_str()
+ .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
+ .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc());
+ match id {
+ Some(id) => match utopia_store::graph::entity_detail(&state.pool, kb_id, id).await {
+ Ok((node, mut facts)) => {
+ if let Some(t) = at {
+ facts.retain(|f| {
+ f.valid_from.is_none_or(|from| from <= t)
+ && f.valid_to.is_none_or(|to| to > t)
+ });
+ }
+ let text = if facts.is_empty() {
+ match at {
+ Some(t) => format!(
+ "{}: no facts valid as of {}.",
+ node.name,
+ t.format("%Y-%m-%d")
+ ),
+ None => format!("{}: no recorded facts.", node.name),
+ }
+ } else {
+ facts.iter().map(fact_line).collect::<Vec<_>>().join("\n")
+ };
+ let detail = match at {
+ Some(t) => format!(
+ "{} facts as of {}",
+ facts.len(),
+ t.format("%Y-%m-%d")
+ ),
+ None => format!("{} facts", facts.len()),
+ };
+ (text, json!({ "kind": "facts", "label": node.name, "detail": detail }))
+ }
+ Err(_) => (
+ "Entity not found.".to_string(),
+ json!({ "kind": "facts", "label": "?", "detail": "not found" }),
+ ),
+ },
+ None => (
+ "Invalid entity_id (expected the uuid returned by find_entities)."
+ .to_string(),
+ json!({ "kind": "facts", "label": "?", "detail": "invalid id" }),
+ ),
+ }
+ }
+ "query_data" if !mounted_sources.is_empty() => {
+ let ds_name = args["data_source"].as_str().map(str::trim).unwrap_or("");
+ let sql = args["sql"].as_str().map(str::trim).unwrap_or("");
+ let purpose = args["purpose"].as_str().map(str::trim).unwrap_or("");
+ // 安全边界:只允许本 KB 挂载的源(凭据不出服务端)
+ let found = mounted_sources
+ .iter()
+ .find(|d| d.name.eq_ignore_ascii_case(ds_name));
+ let text = match found {
+ None => format!(
+ "Unknown data source '{ds_name}'. Mounted sources: {}",
+ mounted_sources
+ .iter()
+ .map(|d| d.name.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ ),
+ Some(ds) => {
+ match run_query(&state, ds.id, sql).await {
+ Ok(out) => out,
+ // 错误透传:模型可据此修正 SQL 重试
+ Err(e) => format!("Query failed: {e}"),
+ }
+ }
+ };
+ let detail = if purpose.is_empty() {
+ sql.chars().take(60).collect::<String>()
+ } else {
+ purpose.to_string()
+ };
+ (text, json!({ "kind": "query", "label": ds_name, "detail": detail }))
+ }
+ "remember" if can_write => {
+ let text = args["text"].as_str().map(str::trim).unwrap_or("");
+ let occurred_at = args["occurred_at"]
+ .as_str()
+ .and_then(|s| chrono::NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok())
+ .map(|d| d.and_hms_opt(12, 0, 0).unwrap().and_utc())
+ .unwrap_or_else(chrono::Utc::now);
+ if text.is_empty() {
+ (
+ "remember requires non-empty text.".to_string(),
+ json!({ "kind": "tool", "label": "remember", "detail": "empty" }),
+ )
+ } else {
+ match utopia_store::memory::append_episode(
+ &state.pool, kb_id, text, occurred_at,
+ )
+ .await
+ {
+ Ok((doc_id, _chunk)) => {
+ // 摄入(embedding/索引/增量抽取)异步走队列,不阻塞对话
+ let _ = utopia_store::jobs::enqueue(
+ &state.pool,
+ "memory_ingest",
+ json!({ "document_id": doc_id }),
+ )
+ .await;
+ state.emit_document(kb_id, doc_id);
+ (
+ format!(
+ "Recorded (effective {}): {text}",
+ occurred_at.format("%Y-%m-%d")
+ ),
+ json!({
+ "kind": "tool", "label": "remember",
+ "detail": text.chars().take(60).collect::<String>()
+ }),
+ )
+ }
+ Err(e) => (
+ format!("Failed to record: {e}"),
+ json!({ "kind": "tool", "label": "remember", "detail": "failed" }),
+ ),
+ }
+ }
+ }
+ other => (
+ format!("Unknown tool: {other}"),
+ json!({ "kind": "tool", "label": other, "detail": "unknown" }),
+ ),
+ };
+ steps_acc.push(step.clone());
+ yield Ok(Event::default()
+ .event("step")
+ .data(serde_json::to_string(&step).unwrap_or_default()));
+ if step["kind"] == "search" || step["kind"] == "docs" {
+ yield Ok(Event::default()
+ .event("sources")
+ .data(serde_json::to_string(&sources).unwrap_or_else(|_| "[]".into())));
+ }
+ msgs.push(tool_result_message(&call.id, &result));
+ }
+ rounds += 1;
+ }
+ };
+
+ Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
+}
+
+fn delta_event(text: &str) -> Result<Event, Infallible> {
+ Ok(Event::default()
+ .event("delta")
+ .data(serde_json::to_string(&json!({ "text": text })).unwrap_or_default()))
+}
+
+fn done_event() -> Result<Event, Infallible> {
+ Ok(Event::default().event("done").data("{}"))
+}
+
+fn error_event(message: &str) -> Result<Event, Infallible> {
+ Ok(Event::default().event("error").data(message))
+}
+
+fn source_json(n: usize, c: &ChunkView) -> serde_json::Value {
+ json!({
+ "n": n,
+ "chunk_id": c.id,
+ "document_id": c.document_id,
+ "filename": c.filename,
+ "excerpt": truncate(&c.text, 160),
+ })
+}
+
+/// Charter 引用:前端渲染成手册行,链到 /docs/{slug}#{anchor}。
+fn charter_source_json(n: usize, h: &utopia_search::DocsSection) -> serde_json::Value {
+ json!({
+ "n": n,
+ "kind": "charter",
+ "slug": h.slug,
+ "anchor": h.anchor,
+ "heading": h.heading,
+ "filename": h.title,
+ "excerpt": truncate(&h.body, 160),
+ })
+}
+
+/// 事实行:"works at → 星云科技 (2023-08 → now) [90%]",in 方向用 ←。
+/// 问数执行:安全闸(解析白名单)→ 引擎执行(只读会话 + 强制 LIMIT + 超时)→ JSON 行。
+async fn run_query(state: &AppState, ds_id: Uuid, sql: &str) -> anyhow::Result<String> {
+ let guarded = crate::query_engine::guard_sql(sql)?;
+ let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
+ let result = crate::query_engine::engine_for(&engine, &conn)?
+ .execute(&guarded)
+ .await?;
+ let mut out = String::new();
+ if result.rows.is_empty() {
+ out.push_str("(no rows)");
+ } else {
+ out.push_str(&result.rows.join("\n"));
+ out.push_str(&format!("\n({} rows", result.rows.len()));
+ if result.truncated {
+ out.push_str(&format!(
+ ", truncated at {} — aggregate in SQL for totals",
+ crate::query_engine::ROW_CAP
+ ));
+ }
+ out.push(')');
+ }
+ Ok(out)
+}
+
+fn fact_line(f: &EntityFact) -> String {
+ let other = f.other_name.as_deref().unwrap_or("?");
+ let core = if f.direction == "out" {
+ format!("{} → {}", f.predicate_label, other)
+ } else {
+ format!("{} ← {}", f.predicate_label, other)
+ };
+ let range = match (&f.valid_from, &f.valid_to) {
+ (Some(from), Some(to)) => {
+ format!(" ({} → {})", from.format("%Y-%m-%d"), to.format("%Y-%m-%d"))
+ }
+ (Some(from), None) => format!(" ({} → now)", from.format("%Y-%m-%d")),
+ (None, Some(to)) => format!(" (→ {})", to.format("%Y-%m-%d")),
+ (None, None) => String::new(),
+ };
+ format!("{core}{range} [{}%]", (f.confidence * 100.0).round() as i32)
+}
+
+/// 降级路径的系统提示(tool-calling 不可用时的一次性注入)。
+fn legacy_system_prompt(chunks: &[ChunkView]) -> String {
+ if chunks.is_empty() {
+ return "You are an enterprise knowledge base assistant. No relevant sources were \
+ retrieved for this question. Tell the user the knowledge base lacks material \
+ on this topic, answer cautiously from general knowledge, and clearly separate \
+ sourced statements from speculation. Always respond in the same language as \
+ the user's question."
+ .to_string();
+ }
+ let mut prompt = String::from(
+ "You are an enterprise knowledge base assistant. Answer strictly based on the \
+ numbered sources below. When a source supports a statement, append its citation \
+ number, e.g. [1] or [2], at the end of the sentence. If the sources are \
+ insufficient, say so explicitly — never fabricate. Always respond in the same \
+ language as the user's question.\n\n### Sources\n",
+ );
+ for (i, c) in chunks.iter().enumerate() {
+ prompt.push_str(&format!(
+ "\n[{}] \"{}\" section {}:\n{}\n",
+ i + 1,
+ c.filename,
+ c.seq + 1,
+ c.text
+ ));
+ }
+ prompt
+}
+
+fn truncate(text: &str, max_chars: usize) -> String {
+ let t = text.trim();
+ if t.chars().count() <= max_chars {
+ t.to_string()
+ } else {
+ let cut: String = t.chars().take(max_chars).collect();
+ format!("{cut}…")
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 会话管理(列表 / 回放 / 删除)
+// ---------------------------------------------------------------------------
+
+pub async fn list_conversations(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ let conversations = utopia_store::conversations::list(&state.pool, kb_id, user.id).await?;
+ Ok(Json(json!({ "conversations": conversations })))
+}
+
+/// 历史回放:消息含落库的行动轨迹(steps)与引用(sources)。
+pub async fn conversation_detail(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ utopia_store::conversations::require_owned(&state.pool, kb_id, user.id, conversation_id)
+ .await?;
+ let messages = utopia_store::conversations::messages(&state.pool, conversation_id).await?;
+ Ok(Json(json!({ "messages": messages })))
+}
+
+pub async fn delete_conversation(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, conversation_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ utopia_store::conversations::delete(&state.pool, kb_id, user.id, conversation_id).await?;
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/api/datasource_routes.rs b/crates/utopia-server/src/api/datasource_routes.rs
new file mode 100644
index 00000000..f1d77a4e
--- /dev/null
+++ b/crates/utopia-server/src/api/datasource_routes.rs
@@ -0,0 +1,249 @@
+//! 问数数据源:系统层注册(admin,凭据只进不出)+ 知识库层挂载(库 admin)。
+//! 挂载/手动刷新时把目标库的 schema 生成 markdown 摄入 KB(同 key 原地更新),
+//! Chat 写 SQL 前可检索到表结构。查询执行的安全闸在刀 2(query_data 工具)。
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use super::graph_routes::require_kb;
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+fn require_admin(user: &utopia_core::models::User) -> Result<(), AppError> {
+ if user.is_admin {
+ Ok(())
+ } else {
+ Err(AppError::Forbidden)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// 系统层:注册/测试/删除
+// ---------------------------------------------------------------------------
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let sources = utopia_store::datasources::list(&state.pool).await?;
+ Ok(Json(json!({ "data_sources": sources })))
+}
+
+#[derive(Deserialize)]
+pub struct CreateBody {
+ pub name: String,
+ #[serde(default = "default_engine")]
+ pub engine: String,
+ pub conn_string: String,
+}
+fn default_engine() -> String {
+ "postgres".into()
+}
+
+pub async fn create(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(body): Json<CreateBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let id = utopia_store::datasources::create(
+ &state.pool,
+ &body.name,
+ &body.engine,
+ &body.conn_string,
+ user.id,
+ )
+ .await?;
+ Ok(Json(json!({ "id": id })))
+}
+
+pub async fn delete(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ utopia_store::datasources::delete(&state.pool, id).await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn test(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, id).await?;
+ let ok = match crate::query_engine::engine_for(&engine, &conn) {
+ Ok(eng) => eng.test().await.is_ok(),
+ Err(_) => false,
+ };
+ utopia_store::datasources::record_test(&state.pool, id, ok).await?;
+ Ok(Json(json!({ "ok": ok })))
+}
+
+// ---------------------------------------------------------------------------
+// 知识库层:挂载/卸载/schema 刷新
+// ---------------------------------------------------------------------------
+
+pub async fn mounted(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let mounted = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
+ Ok(Json(json!({ "data_sources": mounted })))
+}
+
+/// 库 admin 从系统已注册的源里挑选挂载(列表给 name/summary,不含凭据)。
+pub async fn mountable(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Admin).await?;
+ let all = utopia_store::datasources::list(&state.pool).await?;
+ Ok(Json(json!({ "data_sources": all })))
+}
+
+pub async fn mount(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Admin).await?;
+ utopia_store::datasources::mount(&state.pool, kb_id, ds_id).await?;
+ // 挂载即摄取 schema:Chat 写 SQL 前能检索到表结构
+ let synced = sync_schema_doc(&state, kb_id, ds_id)
+ .await
+ .map_err(AppError::Other)?;
+ Ok(Json(json!({ "ok": true, "schema_tables": synced })))
+}
+
+pub async fn unmount(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Admin).await?;
+ utopia_store::datasources::unmount(&state.pool, kb_id, ds_id).await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn sync_schema(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Admin).await?;
+ let synced = sync_schema_doc(&state, kb_id, ds_id)
+ .await
+ .map_err(AppError::Other)?;
+ Ok(Json(json!({ "ok": true, "schema_tables": synced })))
+}
+
+/// Agentic 探索:后台任务读挂载源 schema,提议 指标/维度→字段 映射(低置信入 Review)。
+pub async fn explore(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Admin).await?;
+ if utopia_store::datasources::mounted(&state.pool, kb_id)
+ .await?
+ .is_empty()
+ {
+ return Err(AppError::Validation("No data sources mounted".into()).into());
+ }
+ utopia_store::jobs::enqueue(&state.pool, "explore_mappings", json!({ "kb_id": kb_id })).await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 拉 information_schema 生成 markdown,走三路判定摄入(同 key 原地更新)。
+/// 文档挂在 per-KB 的 "Data schemas" folder 来源下。
+async fn sync_schema_doc(state: &AppState, kb_id: Uuid, ds_id: Uuid) -> anyhow::Result<usize> {
+ const MAX_TABLES: usize = 200;
+ let name = utopia_store::datasources::list(&state.pool)
+ .await?
+ .into_iter()
+ .find(|d| d.id == ds_id)
+ .map(|d| d.name)
+ .ok_or_else(|| anyhow::anyhow!("Data source not found"))?;
+ let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
+ let cols = crate::query_engine::engine_for(&engine, &conn)?
+ .fetch_schema()
+ .await?;
+
+ let mut md = format!(
+ "# Data source: {name}\n\nTables and columns available for SQL queries against this source.\n"
+ );
+ let mut current = String::new();
+ let mut tables = 0usize;
+ for c in &cols {
+ let key = format!("{}.{}", c.schema, c.table);
+ if key != current {
+ if tables >= MAX_TABLES {
+ md.push_str("\n(further tables omitted)\n");
+ break;
+ }
+ current = key.clone();
+ tables += 1;
+ md.push_str(&format!("\n## {key}\n"));
+ }
+ md.push_str(&format!(
+ "- {} ({}){}\n",
+ c.column,
+ c.data_type,
+ c.comment
+ .as_deref()
+ .map(|x| format!(" — {x}"))
+ .unwrap_or_default()
+ ));
+ }
+
+ // per-KB "Data schemas" 容器来源(folder:纯容器语义)
+ let folder = match sqlx::query_as::<_, (Uuid,)>(
+ "SELECT id FROM sources WHERE kb_id = $1 AND kind = 'folder' AND name = 'Data schemas'",
+ )
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await?
+ {
+ Some((id,)) => id,
+ None => {
+ utopia_store::sources::create(
+ &state.pool,
+ kb_id,
+ "folder",
+ "Data schemas",
+ &serde_json::json!({}),
+ Some("database"),
+ None,
+ None,
+ )
+ .await?
+ .id
+ }
+ };
+ crate::ingest_sources::ingest_item(
+ state,
+ kb_id,
+ folder,
+ &format!("datasource:{ds_id}:schema"),
+ &format!("{name}-schema.md"),
+ "text/markdown",
+ md.as_bytes(),
+ None,
+ )
+ .await?;
+ state.emit_source(kb_id);
+ Ok(tables)
+}
diff --git a/crates/utopia-server/src/api/documents_routes.rs b/crates/utopia-server/src/api/documents_routes.rs
new file mode 100644
index 00000000..6255100b
--- /dev/null
+++ b/crates/utopia-server/src/api/documents_routes.rs
@@ -0,0 +1,192 @@
+use axum::extract::{Multipart, Path, Query, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use sha2::{Digest, Sha256};
+use utopia_core::models::{Document, Role};
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+#[derive(Deserialize)]
+pub struct UploadQuery {
+ /// 目标 folder 来源:上传直接归入该文件夹(仅 kind=folder 接受上传)
+ #[serde(default)]
+ pub source: Option<Uuid>,
+}
+
+/// 批量上传(multipart,可多文件)。重复内容(同 KB 同 sha256)跳过。
+pub async fn upload(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Query(q): Query<UploadQuery>,
+ mut multipart: Multipart,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?;
+ let target_source = match q.source {
+ Some(sid) => {
+ let src = utopia_store::sources::get(&state.pool, sid).await?;
+ if src.kb_id != kb_id || src.kind != "folder" {
+ return Err(AppError::Validation(
+ "Uploads can only target a folder source in this knowledge base".into(),
+ )
+ .into());
+ }
+ Some(sid)
+ }
+ None => None,
+ };
+
+ let mut created: Vec<Document> = Vec::new();
+ let mut skipped: Vec<serde_json::Value> = Vec::new();
+
+ while let Some(field) = multipart
+ .next_field()
+ .await
+ .map_err(|e| AppError::Validation(format!("Malformed upload: {e}")))?
+ {
+ let Some(filename) = field.file_name().map(String::from) else {
+ continue;
+ };
+ let mime = field
+ .content_type()
+ .unwrap_or("application/octet-stream")
+ .to_string();
+ let bytes = field
+ .bytes()
+ .await
+ .map_err(|e| AppError::Validation(format!("Failed to read upload: {e}")))?;
+ if bytes.is_empty() {
+ skipped.push(json!({ "filename": filename, "reason": "empty file" }));
+ continue;
+ }
+
+ let sha256 = hex(&Sha256::digest(&bytes));
+ state
+ .blob
+ .put(&sha256, &bytes)
+ .await
+ .map_err(AppError::Other)?;
+
+ match utopia_store::documents::create(
+ &state.pool,
+ kb_id,
+ &filename,
+ &mime,
+ bytes.len() as i64,
+ &sha256,
+ target_source,
+ None,
+ None,
+ )
+ .await
+ {
+ Ok(doc) => {
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "process_document",
+ json!({ "document_id": doc.id }),
+ )
+ .await?;
+ created.push(doc);
+ }
+ Err(AppError::Conflict(_)) => {
+ skipped.push(json!({ "filename": filename, "reason": "duplicate content" }));
+ }
+ Err(e) => return Err(e.into()),
+ }
+ }
+
+ if created.is_empty() && skipped.is_empty() {
+ return Err(AppError::Validation("No files received".into()).into());
+ }
+ Ok(Json(json!({ "created": created, "skipped": skipped })))
+}
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<Vec<Document>>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+ let docs = utopia_store::documents::list(&state.pool, kb_id).await?;
+ Ok(Json(docs))
+}
+
+/// 文档详情 + 全部分块(文档查看器用)。
+pub async fn detail(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, id).await?;
+ utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Viewer).await?;
+ let chunks = utopia_store::documents::chunks_full(&state.pool, id).await?;
+ Ok(Json(json!({ "document": doc, "chunks": chunks })))
+}
+
+/// 反向证据链:文档各分块抽出的事实(文档查看器右栏)。
+pub async fn extractions(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, id).await?;
+ utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Viewer).await?;
+ let facts = utopia_store::graph::document_extractions(&state.pool, id).await?;
+ Ok(Json(json!({ "facts": facts })))
+}
+
+pub async fn delete(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, id).await?;
+ utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?;
+
+ utopia_store::documents::delete(&state.pool, id).await?;
+ let search = state.search.clone();
+ let did = id.to_string();
+ tokio::task::spawn_blocking(move || search.delete_document(&did))
+ .await
+ .map_err(|e| AppError::Other(e.into()))?
+ .map_err(AppError::Other)?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(doc.kb_id),
+ user.id,
+ "document.deleted",
+ "document",
+ Some(id),
+ json!({ "filename": doc.filename }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 重新处理(解析器升级/失败重试)。
+pub async fn reprocess(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, id).await?;
+ utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?;
+ utopia_store::documents::set_status(&state.pool, id, "pending").await?;
+ let job_id = utopia_store::jobs::enqueue(
+ &state.pool,
+ "process_document",
+ json!({ "document_id": id }),
+ )
+ .await?;
+ Ok(Json(json!({ "job_id": job_id })))
+}
+
+fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
diff --git a/crates/utopia-server/src/api/events_routes.rs b/crates/utopia-server/src/api/events_routes.rs
new file mode 100644
index 00000000..8763afcc
--- /dev/null
+++ b/crates/utopia-server/src/api/events_routes.rs
@@ -0,0 +1,40 @@
+//! KB 事件流(SSE):文档摄入/抽取状态与审核队列变化的实时推送。
+//! 前端收到事件只做 react-query 失效重取——事件本身不带业务数据,天然幂等。
+
+use axum::extract::{Path, State};
+use axum::response::sse::{Event, KeepAlive, Sse};
+use futures_util::Stream;
+use std::convert::Infallible;
+use tokio::sync::broadcast;
+use utopia_core::models::Role;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+pub async fn kb_events(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Sse<impl Stream<Item = Result<Event, Infallible>>>> {
+ utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+
+ let mut rx = state.events.subscribe();
+ let stream = async_stream::stream! {
+ loop {
+ match rx.recv().await {
+ Ok(ev) if ev.kb_id == kb_id => {
+ yield Ok(Event::default()
+ .event(ev.kind)
+ .data(serde_json::to_string(&ev).unwrap_or_else(|_| "{}".into())));
+ }
+ Ok(_) => continue,
+ // 消费落后被跳帧:无所谓,事件只是"该刷新了"的信号
+ Err(broadcast::error::RecvError::Lagged(_)) => continue,
+ Err(broadcast::error::RecvError::Closed) => return,
+ }
+ }
+ };
+ Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
+}
diff --git a/crates/utopia-server/src/api/graph_routes.rs b/crates/utopia-server/src/api/graph_routes.rs
new file mode 100644
index 00000000..0fb62ed2
--- /dev/null
+++ b/crates/utopia-server/src/api/graph_routes.rs
@@ -0,0 +1,133 @@
+use axum::extract::{Path, Query, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+pub(super) async fn require_kb(
+ state: &AppState,
+ user: &utopia_core::models::User,
+ kb_id: Uuid,
+ min: Role,
+) -> Result<utopia_core::models::KnowledgeBase, AppError> {
+ utopia_store::access::require_kb(&state.pool, user, kb_id, min).await
+}
+
+/// `at`:可选 as-of 日期(YYYY-MM-DD 或 RFC3339)——服务端时间旅行。
+fn parse_at(raw: Option<&str>) -> Result<Option<chrono::DateTime<chrono::Utc>>, AppError> {
+ let Some(s) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
+ return Ok(None);
+ };
+ if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
+ return Ok(Some(d.and_hms_opt(0, 0, 0).unwrap().and_utc()));
+ }
+ chrono::DateTime::parse_from_rfc3339(s)
+ .map(|t| Some(t.with_timezone(&chrono::Utc)))
+ .map_err(|_| AppError::Validation("Invalid `at` (expected YYYY-MM-DD or RFC3339)".into()))
+}
+
+#[derive(Deserialize)]
+pub struct OverviewQuery {
+ #[serde(default)]
+ pub at: Option<String>,
+}
+
+pub async fn overview(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Query(q): Query<OverviewQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let at = parse_at(q.at.as_deref())?;
+ let (nodes, edges) = utopia_store::graph::overview(&state.pool, kb_id, 150, at).await?;
+ Ok(Json(json!({ "nodes": nodes, "edges": edges })))
+}
+
+#[derive(Deserialize)]
+pub struct NeighborhoodQuery {
+ pub entity: Uuid,
+ #[serde(default)]
+ pub hops: Option<u8>,
+ #[serde(default)]
+ pub at: Option<String>,
+}
+
+pub async fn neighborhood(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Query(q): Query<NeighborhoodQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let at = parse_at(q.at.as_deref())?;
+ let (nodes, edges) =
+ utopia_store::graph::neighborhood(&state.pool, kb_id, q.entity, q.hops.unwrap_or(2), at)
+ .await?;
+ Ok(Json(json!({ "nodes": nodes, "edges": edges })))
+}
+
+#[derive(Deserialize)]
+pub struct EntitySearchQuery {
+ pub q: String,
+}
+
+pub async fn search_entities(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Query(query): Query<EntitySearchQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ if query.q.trim().is_empty() {
+ return Ok(Json(json!({ "entities": [] })));
+ }
+ let entities = utopia_store::graph::search_entities(&state.pool, kb_id, &query.q, 10).await?;
+ Ok(Json(json!({ "entities": entities })))
+}
+
+pub async fn entity_detail(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, entity_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let (entity, facts) = utopia_store::graph::entity_detail(&state.pool, kb_id, entity_id).await?;
+ Ok(Json(json!({ "entity": entity, "facts": facts })))
+}
+
+pub async fn fact_evidence(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, fact_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let evidence = utopia_store::graph::fact_evidence(&state.pool, fact_id).await?;
+ Ok(Json(json!({ "evidence": evidence })))
+}
+
+/// 手动触发抽取(failed 重试 / 补配模型后补抽)。
+pub async fn extract(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(document_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+ require_kb(&state, &user, doc.kb_id, Role::Editor).await?;
+ // 手动触发 = 强制全量:清掉增量跳过标记,重抽每一块
+ utopia_store::documents::clear_extraction_marks(&state.pool, document_id).await?;
+ utopia_store::documents::set_graph_status(&state.pool, document_id, "queued").await?;
+ let job_id = utopia_store::jobs::enqueue(
+ &state.pool,
+ "extract_document",
+ json!({ "document_id": document_id }),
+ )
+ .await?;
+ Ok(Json(json!({ "job_id": job_id })))
+}
diff --git a/crates/utopia-server/src/api/kbs.rs b/crates/utopia-server/src/api/kbs.rs
new file mode 100644
index 00000000..cdb06e80
--- /dev/null
+++ b/crates/utopia-server/src/api/kbs.rs
@@ -0,0 +1,251 @@
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::{KnowledgeBase, Role, User};
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+#[derive(Deserialize)]
+pub struct CreateKbReq {
+ pub name: String,
+ #[serde(default)]
+ pub kind: Option<String>,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub visibility: Option<String>,
+}
+
+#[derive(Deserialize)]
+pub struct UpdateKbReq {
+ pub name: Option<String>,
+ pub description: Option<String>,
+ pub visibility: Option<String>,
+}
+
+/// 用户可见的 KB 列表(restricted 库仅矩阵成员与系统管理员可见)。
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+) -> ApiResult<Json<Vec<KnowledgeBase>>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer)
+ .await?;
+ let list =
+ utopia_store::kbs::list_visible(&state.pool, workspace_id, user.id, user.is_admin).await?;
+ Ok(Json(list))
+}
+
+/// 建库:部署管理员(工作区 Admin+ 或系统管理员)。创建者自动进入矩阵为 admin。
+pub async fn create(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+ Json(req): Json<CreateKbReq>,
+) -> ApiResult<Json<KnowledgeBase>> {
+ let name = req.name.trim();
+ if name.is_empty() || name.chars().count() > 64 {
+ return Err(AppError::Validation("Name must be 1-64 characters".into()).into());
+ }
+ let kind = req.kind.as_deref().unwrap_or("knowledge");
+ if !matches!(kind, "knowledge" | "memory") {
+ return Err(AppError::Validation("kind must be 'knowledge' or 'memory'".into()).into());
+ }
+ // 建库是部署管理动作(入口在 System settings):系统管理员或工作区 Admin+。
+ // 用户自建库前端默认 restricted,不污染全员切换器;General 由系统初建保持 open
+ let ws_role =
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer)
+ .await?;
+ if !user.is_admin && ws_role < Role::Admin {
+ return Err(AppError::Forbidden.into());
+ }
+ let kb = utopia_store::kbs::create(
+ &state.pool,
+ workspace_id,
+ name,
+ kind,
+ req.description.as_deref(),
+ )
+ .await?;
+ if let Some(v) = req.visibility.as_deref() {
+ utopia_store::kbs::update(&state.pool, kb.id, None, None, Some(v)).await?;
+ }
+ utopia_store::access::set_kb_member(&state.pool, kb.id, user.id, "admin", Some(user.id))
+ .await?;
+ let kb = utopia_store::kbs::get(&state.pool, kb.id).await?;
+ Ok(Json(kb))
+}
+
+/// 我的知识库全景(账户层):可见库 + 我的角色 + 加入信息 + 概览统计。
+pub async fn my_kbs(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer)
+ .await?;
+ let kbs =
+ utopia_store::kbs::list_visible(&state.pool, workspace_id, user.id, user.is_admin).await?;
+ let ids: Vec<Uuid> = kbs.iter().map(|k| k.id).collect();
+ let infos = utopia_store::access::my_kb_infos(&state.pool, &ids, user.id).await?;
+ let mut rows = Vec::with_capacity(kbs.len());
+ for kb in &kbs {
+ let info = infos.iter().find(|i| i.kb_id == kb.id);
+ let role = utopia_store::access::kb_role(&state.pool, &user, kb).await?;
+ rows.push(json!({
+ "kb": kb,
+ "my_role": role.map(|r| r.as_str()),
+ "joined_at": info.and_then(|i| i.joined_at),
+ "added_by_name": info.and_then(|i| i.added_by_name.clone()),
+ "doc_count": info.map(|i| i.doc_count).unwrap_or(0),
+ "member_count": info.map(|i| i.member_count).unwrap_or(0),
+ }));
+ }
+ Ok(Json(json!({ "kbs": rows })))
+}
+
+async fn kb_with_role(
+ state: &AppState,
+ user: &User,
+ kb_id: Uuid,
+ min: Role,
+) -> Result<KnowledgeBase, AppError> {
+ utopia_store::access::require_kb(&state.pool, user, kb_id, min).await
+}
+
+pub async fn get_one(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<KnowledgeBase>> {
+ let kb = kb_with_role(&state, &user, id, Role::Viewer).await?;
+ Ok(Json(kb))
+}
+
+/// 库设置(名称/描述/可见性):库 admin 起步。
+pub async fn update(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+ Json(req): Json<UpdateKbReq>,
+) -> ApiResult<Json<KnowledgeBase>> {
+ kb_with_role(&state, &user, id, Role::Admin).await?;
+ let kb = utopia_store::kbs::update(
+ &state.pool,
+ id,
+ req.name.as_deref().map(str::trim),
+ req.description.as_deref(),
+ req.visibility.as_deref(),
+ )
+ .await?;
+ // 审计只记不阻断
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(id),
+ user.id,
+ "kb.updated",
+ "kb",
+ Some(id),
+ json!({ "name": req.name, "visibility": req.visibility }),
+ )
+ .await;
+ Ok(Json(kb))
+}
+
+pub async fn delete(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let kb = kb_with_role(&state, &user, id, Role::Admin).await?;
+ utopia_store::kbs::delete(&state.pool, id).await?;
+ // kb_id 置 NULL:库已级联删除,事件留在部署层(actor 与库名在 detail)
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "kb.deleted",
+ "kb",
+ Some(id),
+ json!({ "name": kb.name }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+// ---------------------------------------------------------------------------
+// KB 成员矩阵(库自己的 Settings → Members)
+// ---------------------------------------------------------------------------
+
+pub async fn members(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ kb_with_role(&state, &user, id, Role::Admin).await?;
+ let members = utopia_store::access::kb_members(&state.pool, id).await?;
+ Ok(Json(json!({ "members": members })))
+}
+
+#[derive(Deserialize)]
+pub struct SetMemberReq {
+ /// viewer | editor | admin
+ pub role: String,
+}
+
+pub async fn set_member(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((id, user_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<SetMemberReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ kb_with_role(&state, &user, id, Role::Admin).await?;
+ utopia_store::access::set_kb_member(&state.pool, id, user_id, &req.role, Some(user.id)).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(id),
+ user.id,
+ "kb.member_set",
+ "user",
+ Some(user_id),
+ json!({ "role": req.role }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn remove_member(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((id, user_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ kb_with_role(&state, &user, id, Role::Admin).await?;
+ utopia_store::access::remove_kb_member(&state.pool, id, user_id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(id),
+ user.id,
+ "kb.member_removed",
+ "user",
+ Some(user_id),
+ json!({}),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 库级审计日志(Admin 起步;纯审计展示)。
+pub async fn audit_log(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ kb_with_role(&state, &user, id, Role::Admin).await?;
+ let events = utopia_store::audit::list_for_kb(&state.pool, id, 100).await?;
+ Ok(Json(json!({ "events": events })))
+}
diff --git a/crates/utopia-server/src/api/members_routes.rs b/crates/utopia-server/src/api/members_routes.rs
new file mode 100644
index 00000000..0c1e45b7
--- /dev/null
+++ b/crates/utopia-server/src/api/members_routes.rs
@@ -0,0 +1,100 @@
+//! 工作区成员管理。
+//! 规则:查看成员 = viewer+;改角色/移除 = admin+;涉及 owner 角色的授予/剥夺 = 仅 owner;
+//! 永远保证工作区至少剩一个 owner。
+
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::{MemberView, OrgUser, Role};
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+) -> ApiResult<Json<Vec<MemberView>>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Viewer)
+ .await?;
+ Ok(Json(
+ utopia_store::members::list(&state.pool, workspace_id).await?,
+ ))
+}
+
+/// 部署内全部用户(供成员选人器;同一公司内可见)。
+pub async fn org_users(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<Vec<OrgUser>>> {
+ Ok(Json(
+ utopia_store::members::org_users(&state.pool, user.org_id).await?,
+ ))
+}
+
+#[derive(Deserialize)]
+pub struct SetRoleReq {
+ pub role: String,
+}
+
+pub async fn set_role(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((workspace_id, target_id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<SetRoleReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let new_role = Role::parse(&req.role).ok_or_else(|| {
+ AppError::Validation("Role must be one of owner/admin/editor/viewer".into())
+ })?;
+ let caller_role =
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Admin)
+ .await?;
+
+ let target_role =
+ utopia_store::members::current_role(&state.pool, workspace_id, target_id).await?;
+
+ // owner 角色的授予或剥夺,只有 owner 能做
+ let touches_owner = new_role == Role::Owner || target_role == Some(Role::Owner);
+ if touches_owner && caller_role != Role::Owner {
+ return Err(AppError::Forbidden.into());
+ }
+ // 不能把最后一个 owner 降级
+ if target_role == Some(Role::Owner)
+ && new_role != Role::Owner
+ && utopia_store::members::owner_count(&state.pool, workspace_id).await? <= 1
+ {
+ return Err(AppError::Validation("Cannot demote the last owner".into()).into());
+ }
+
+ utopia_store::members::set_role(&state.pool, workspace_id, target_id, new_role).await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn remove(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((workspace_id, target_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let caller_role =
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Admin)
+ .await?;
+ let target_role = utopia_store::members::current_role(&state.pool, workspace_id, target_id)
+ .await?
+ .ok_or(AppError::NotFound)?;
+
+ if target_role == Role::Owner {
+ if caller_role != Role::Owner {
+ return Err(AppError::Forbidden.into());
+ }
+ if utopia_store::members::owner_count(&state.pool, workspace_id).await? <= 1 {
+ return Err(AppError::Validation("Cannot remove the last owner".into()).into());
+ }
+ }
+
+ utopia_store::members::remove(&state.pool, workspace_id, target_id).await?;
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
new file mode 100644
index 00000000..3131b081
--- /dev/null
+++ b/crates/utopia-server/src/api/mod.rs
@@ -0,0 +1,278 @@
+mod admin_routes;
+mod auth_routes;
+mod chat;
+mod datasource_routes;
+mod documents_routes;
+mod events_routes;
+mod graph_routes;
+mod kbs;
+mod members_routes;
+mod ontology_routes;
+mod review_routes;
+mod search_routes;
+mod settings_routes;
+mod sources_routes;
+mod workspaces;
+
+use axum::extract::DefaultBodyLimit;
+use axum::http::{header, HeaderValue, Method};
+use axum::routing::{get, patch, post};
+use axum::{Json, Router};
+use serde_json::json;
+use tower_http::cors::CorsLayer;
+use tower_http::services::{ServeDir, ServeFile};
+use tower_http::trace::TraceLayer;
+use utopia_core::config::AppConfig;
+
+use crate::state::AppState;
+
+const MAX_UPLOAD_BYTES: usize = 100 * 1024 * 1024;
+
+pub fn router(state: AppState, cfg: &AppConfig) -> Router {
+ let api = Router::new()
+ .route("/health", get(health))
+ .route("/auth/register", post(auth_routes::register))
+ .route("/auth/login", post(auth_routes::login))
+ .route("/auth/logout", post(auth_routes::logout))
+ .route(
+ "/auth/me",
+ get(auth_routes::me).patch(auth_routes::update_me),
+ )
+ .route("/auth/password", post(auth_routes::change_password))
+ .route(
+ "/workspaces",
+ get(workspaces::list).post(workspaces::create),
+ )
+ .route(
+ "/workspaces/{id}",
+ get(workspaces::get_one)
+ .patch(workspaces::rename)
+ .delete(workspaces::delete),
+ )
+ .route("/workspaces/{id}/kbs", get(kbs::list).post(kbs::create))
+ .route("/workspaces/{id}/my-kbs", get(kbs::my_kbs))
+ .route(
+ "/workspaces/{id}/settings",
+ get(settings_routes::get).put(settings_routes::put),
+ )
+ .route(
+ "/workspaces/{id}/settings/test",
+ post(settings_routes::test),
+ )
+ .route("/workspaces/{id}/members", get(members_routes::list))
+ .route(
+ "/workspaces/{id}/members/{user_id}",
+ axum::routing::put(members_routes::set_role).delete(members_routes::remove),
+ )
+ .route("/users", get(members_routes::org_users))
+ .route(
+ "/kbs/{id}",
+ patch(kbs::update).get(kbs::get_one).delete(kbs::delete),
+ )
+ .route("/kbs/{id}/members", get(kbs::members))
+ .route("/kbs/{id}/audit", get(kbs::audit_log))
+ .route(
+ "/kbs/{id}/members/{user_id}",
+ axum::routing::put(kbs::set_member).delete(kbs::remove_member),
+ )
+ .route(
+ "/admin/deployment",
+ get(admin_routes::get_deployment).put(admin_routes::put_deployment),
+ )
+ .route("/admin/users", post(admin_routes::create_user))
+ .route(
+ "/admin/data-sources",
+ get(datasource_routes::list).post(datasource_routes::create),
+ )
+ .route(
+ "/admin/data-sources/{id}",
+ axum::routing::delete(datasource_routes::delete),
+ )
+ .route(
+ "/admin/data-sources/{id}/test",
+ post(datasource_routes::test),
+ )
+ .route("/kbs/{id}/data-sources", get(datasource_routes::mounted))
+ .route(
+ "/kbs/{id}/data-sources/available",
+ get(datasource_routes::mountable),
+ )
+ .route(
+ "/kbs/{id}/data-sources/{ds_id}",
+ axum::routing::put(datasource_routes::mount).delete(datasource_routes::unmount),
+ )
+ .route(
+ "/kbs/{id}/data-sources/{ds_id}/sync-schema",
+ post(datasource_routes::sync_schema),
+ )
+ .route(
+ "/kbs/{id}/data-sources/explore",
+ post(datasource_routes::explore),
+ )
+ .route(
+ "/kbs/{id}/documents",
+ get(documents_routes::list)
+ .post(documents_routes::upload)
+ .layer(DefaultBodyLimit::max(MAX_UPLOAD_BYTES)),
+ )
+ .route("/kbs/{id}/ontology", get(ontology_routes::get))
+ .route(
+ "/kbs/{id}/ontology/entity-types",
+ post(ontology_routes::create_entity_type),
+ )
+ .route(
+ "/kbs/{id}/ontology/entity-types/{type_id}",
+ patch(ontology_routes::update_entity_type).delete(ontology_routes::delete_entity_type),
+ )
+ .route(
+ "/kbs/{id}/ontology/entity-types/{type_id}/entities",
+ get(ontology_routes::list_entity_instances),
+ )
+ .route(
+ "/kbs/{id}/ontology/relation-types",
+ post(ontology_routes::create_relation_type),
+ )
+ .route(
+ "/kbs/{id}/ontology/relation-types/{type_id}",
+ patch(ontology_routes::update_relation_type)
+ .delete(ontology_routes::delete_relation_type),
+ )
+ .route(
+ "/kbs/{id}/ontology/misses/dismiss",
+ post(ontology_routes::dismiss_miss),
+ )
+ .route("/kbs/{id}/ontology/suggest", post(ontology_routes::suggest))
+ .route("/kbs/{id}/search", post(search_routes::search))
+ .route("/kbs/{id}/chat", post(chat::chat))
+ .route("/kbs/{id}/conversations", get(chat::list_conversations))
+ .route(
+ "/kbs/{id}/conversations/{conversation_id}",
+ get(chat::conversation_detail).delete(chat::delete_conversation),
+ )
+ .route(
+ "/documents/{id}",
+ get(documents_routes::detail).delete(documents_routes::delete),
+ )
+ .route("/documents/{id}/extract", post(graph_routes::extract))
+ .route("/kbs/{id}/graph/overview", get(graph_routes::overview))
+ .route(
+ "/kbs/{id}/graph/neighborhood",
+ get(graph_routes::neighborhood),
+ )
+ .route("/kbs/{id}/entities", get(graph_routes::search_entities))
+ .route(
+ "/kbs/{id}/entities/{entity_id}",
+ get(graph_routes::entity_detail),
+ )
+ .route(
+ "/kbs/{id}/facts/{fact_id}/evidence",
+ get(graph_routes::fact_evidence),
+ )
+ .route("/kbs/{id}/events", get(events_routes::kb_events))
+ .route(
+ "/kbs/{id}/sources",
+ get(sources_routes::list).post(sources_routes::create),
+ )
+ .route(
+ "/kbs/{id}/sources/{source_id}",
+ patch(sources_routes::update).delete(sources_routes::delete),
+ )
+ .route(
+ "/kbs/{id}/sources/{source_id}/sync",
+ post(sources_routes::sync_now),
+ )
+ .route(
+ "/kbs/{id}/sources/{source_id}/runs",
+ get(sources_routes::runs),
+ )
+ .route(
+ "/kbs/{id}/sources/{source_id}/missing/cleanup",
+ post(sources_routes::cleanup_missing),
+ )
+ .route(
+ "/documents/{id}/extractions",
+ get(documents_routes::extractions),
+ )
+ .route("/kbs/{id}/ingest", post(sources_routes::ingest))
+ // api 来源推送:来源专属密钥认证(Bearer),无会话
+ .route("/sources/{source_id}/ingest", post(sources_routes::push))
+ .route(
+ "/kbs/{id}/sources/{source_id}/token",
+ get(sources_routes::get_token),
+ )
+ .route(
+ "/kbs/{id}/sources/{source_id}/rotate-token",
+ post(sources_routes::rotate_token),
+ )
+ .route("/kbs/{id}/review", get(review_routes::list))
+ .route("/kbs/{id}/review/history", get(review_routes::history))
+ .route("/kbs/{id}/review/{review_id}", post(review_routes::decide))
+ .route(
+ "/kbs/{id}/facts/{fact_id}/confirm",
+ post(review_routes::confirm_fact),
+ )
+ .route(
+ "/kbs/{id}/facts/{fact_id}/reject",
+ post(review_routes::reject_fact),
+ )
+ .route(
+ "/kbs/{id}/facts/{fact_id}/close",
+ post(review_routes::close_fact),
+ )
+ .route(
+ "/kbs/{id}/merges/{merge_id}/revert",
+ post(review_routes::revert_merge),
+ )
+ .route(
+ "/kbs/{id}/conflicts/{conflict_id}",
+ post(review_routes::resolve_conflict),
+ )
+ .route(
+ "/kbs/{id}/entities/merge",
+ post(review_routes::manual_merge),
+ )
+ .route(
+ "/documents/{id}/reprocess",
+ post(documents_routes::reprocess),
+ )
+ .route("/jobs/noop", post(jobs_noop))
+ .with_state(state);
+
+ // 开发环境 CORS:Vite dev server 携带 cookie 跨端口访问
+ let cors = CorsLayer::new()
+ .allow_origin("http://localhost:5173".parse::<HeaderValue>().unwrap())
+ .allow_methods([
+ Method::GET,
+ Method::POST,
+ Method::PATCH,
+ Method::DELETE,
+ Method::PUT,
+ ])
+ .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
+ .allow_credentials(true);
+
+ let mut app = Router::new().nest("/api/v1", api).layer(cors);
+
+ // SPA 托管:产物存在则挂载,history fallback 到 index.html
+ let index = std::path::Path::new(&cfg.web_dist).join("index.html");
+ if index.exists() {
+ let serve = ServeDir::new(&cfg.web_dist).fallback(ServeFile::new(index));
+ app = app.fallback_service(serve);
+ tracing::info!("已托管前端产物: {}", cfg.web_dist);
+ }
+
+ app.layer(TraceLayer::new_for_http())
+}
+
+async fn health() -> Json<serde_json::Value> {
+ Json(json!({ "status": "ok", "name": "utopia", "version": env!("CARGO_PKG_VERSION") }))
+}
+
+/// P0 队列验证端点:入队一个 noop 任务(后续里程碑移除)。
+async fn jobs_noop(
+ axum::extract::State(state): axum::extract::State<AppState>,
+ _user: crate::auth::AuthUser,
+) -> crate::error::ApiResult<Json<serde_json::Value>> {
+ let id = utopia_store::jobs::enqueue(&state.pool, "noop", json!({})).await?;
+ Ok(Json(json!({ "job_id": id })))
+}
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
new file mode 100644
index 00000000..9c1ef898
--- /dev/null
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -0,0 +1,383 @@
+//! 本体编辑器 API:类型/关系 CRUD + 未匹配统计 + LLM 扩展建议。
+//! 查看 = viewer;修改 = editor(本体直接影响后续抽取的白名单)。
+
+use axum::extract::{Path, Query, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use utopia_core::AppError;
+use utopia_llm::ChatMessage;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::llm_util;
+use crate::state::AppState;
+
+async fn require_kb(
+ state: &AppState,
+ user: &utopia_core::models::User,
+ kb_id: Uuid,
+ min: Role,
+) -> Result<utopia_core::models::KnowledgeBase, AppError> {
+ utopia_store::access::require_kb(&state.pool, user, kb_id, min).await
+}
+
+pub async fn get(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ utopia_store::graph::ensure_default_ontology(&state.pool, kb_id).await?;
+ let entity_types = utopia_store::ontology::entity_type_views(&state.pool, kb_id).await?;
+ let relation_types = utopia_store::ontology::relation_type_views(&state.pool, kb_id).await?;
+ let misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
+ Ok(Json(json!({
+ "entity_types": entity_types,
+ "relation_types": relation_types,
+ "misses": misses,
+ })))
+}
+
+#[derive(Deserialize)]
+pub struct InstancesQuery {
+ #[serde(default)]
+ pub page: i64,
+ #[serde(default = "default_per")]
+ pub per: i64,
+}
+
+fn default_per() -> i64 {
+ 12
+}
+
+/// 某个类下的实体实例列表(详情区右侧,分页)。
+pub async fn list_entity_instances(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, type_id)): Path<(Uuid, Uuid)>,
+ Query(q): Query<InstancesQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let per = q.per.clamp(1, 100);
+ let page = q.page.max(0);
+ let (rows, total) =
+ utopia_store::ontology::entity_instances(&state.pool, kb_id, type_id, per, page * per)
+ .await?;
+ Ok(Json(json!({ "entities": rows, "total": total })))
+}
+
+#[derive(Deserialize)]
+pub struct EntityTypeReq {
+ pub key: Option<String>,
+ pub label: String,
+ #[serde(default)]
+ pub color: Option<String>,
+ /// circle | square
+ #[serde(default)]
+ pub shape: Option<String>,
+ #[serde(default)]
+ pub parent_id: Option<Uuid>,
+ /// 语义指引,注入抽取 prompt
+ #[serde(default)]
+ pub description: Option<String>,
+}
+
+pub async fn create_entity_type(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<EntityTypeReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let key = req
+ .key
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .ok_or_else(|| AppError::Validation("key is required".into()))?;
+ let id = utopia_store::ontology::create_entity_type(
+ &state.pool,
+ kb_id,
+ key,
+ req.label.trim(),
+ req.color.as_deref().unwrap_or("#8ea5bd"),
+ req.shape.as_deref().unwrap_or("circle"),
+ req.parent_id,
+ req.description.as_deref().unwrap_or("").trim(),
+ )
+ .await?;
+ // 审计只记不阻断
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "entity_type.created",
+ "entity_type",
+ Some(id),
+ json!({ "key": key, "label": req.label.trim() }),
+ )
+ .await;
+ Ok(Json(json!({ "id": id })))
+}
+
+pub async fn update_entity_type(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<EntityTypeReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ utopia_store::ontology::update_entity_type(
+ &state.pool,
+ kb_id,
+ id,
+ req.label.trim(),
+ req.color.as_deref().unwrap_or("#8ea5bd"),
+ req.shape.as_deref().unwrap_or("circle"),
+ req.parent_id,
+ req.description.as_deref().unwrap_or("").trim(),
+ )
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "entity_type.updated",
+ "entity_type",
+ Some(id),
+ json!({ "label": req.label.trim(), "color": req.color, "shape": req.shape,
+ "description": req.description }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn delete_entity_type(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ utopia_store::ontology::delete_entity_type(&state.pool, kb_id, id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "entity_type.deleted",
+ "entity_type",
+ Some(id),
+ json!({}),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+#[derive(Deserialize)]
+pub struct RelationTypeReq {
+ pub key: Option<String>,
+ pub label: String,
+ #[serde(default = "default_temporal")]
+ pub temporal: String,
+ #[serde(default)]
+ pub functional: bool,
+ #[serde(default)]
+ pub inverse_functional: bool,
+ #[serde(default)]
+ pub description: Option<String>,
+ /// relation | attribute(创建时定死,更新时忽略)
+ #[serde(default)]
+ pub kind: Option<String>,
+ /// attribute 专用:所属类
+ #[serde(default)]
+ pub domain_type_id: Option<Uuid>,
+ /// attribute 专用:text | number | date | bool
+ #[serde(default)]
+ pub datatype: Option<String>,
+ #[serde(default)]
+ pub unit: Option<String>,
+}
+
+fn default_temporal() -> String {
+ "state".into()
+}
+
+pub async fn create_relation_type(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<RelationTypeReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let key = req
+ .key
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .ok_or_else(|| AppError::Validation("key is required".into()))?;
+ let kind = req.kind.as_deref().unwrap_or("relation");
+ let id = utopia_store::ontology::create_relation_type(
+ &state.pool,
+ kb_id,
+ key,
+ req.label.trim(),
+ &req.temporal,
+ req.functional,
+ req.inverse_functional,
+ req.description.as_deref().unwrap_or("").trim(),
+ kind,
+ req.domain_type_id,
+ req.datatype.as_deref(),
+ req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ )
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "relation_type.created",
+ "relation_type",
+ Some(id),
+ json!({ "key": key, "label": req.label.trim(), "temporal": req.temporal, "kind": kind }),
+ )
+ .await;
+ Ok(Json(json!({ "id": id })))
+}
+
+pub async fn update_relation_type(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, id)): Path<(Uuid, Uuid)>,
+ Json(req): Json<RelationTypeReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ utopia_store::ontology::update_relation_type(
+ &state.pool,
+ kb_id,
+ id,
+ req.label.trim(),
+ &req.temporal,
+ req.functional,
+ req.inverse_functional,
+ req.description.as_deref().unwrap_or("").trim(),
+ req.datatype.as_deref(),
+ req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),
+ )
+ .await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "relation_type.updated",
+ "relation_type",
+ Some(id),
+ json!({ "label": req.label.trim(), "temporal": req.temporal,
+ "functional": req.functional, "inverse_functional": req.inverse_functional,
+ "description": req.description }),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn delete_relation_type(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ utopia_store::ontology::delete_relation_type(&state.pool, kb_id, id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "relation_type.deleted",
+ "relation_type",
+ Some(id),
+ json!({}),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+#[derive(Deserialize)]
+pub struct DismissMissReq {
+ pub kind: String,
+ pub key: String,
+}
+
+pub async fn dismiss_miss(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<DismissMissReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ utopia_store::ontology::clear_miss(&state.pool, kb_id, &req.kind, &req.key).await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// LLM 本体扩展建议:现有本体 + 未匹配统计 → 提案(人审后经 create 端点合入)。
+pub async fn suggest(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let kb = require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
+ .await?
+ .ok_or_else(|| AppError::Validation("Chat model not configured".into()))?;
+ let client = llm_util::chat_client(&settings)
+ .ok_or_else(|| AppError::Validation("Chat model not configured".into()))?;
+
+ let entity_types = utopia_store::ontology::entity_type_views(&state.pool, kb_id).await?;
+ let relation_types = utopia_store::ontology::relation_type_views(&state.pool, kb_id).await?;
+ let misses = utopia_store::ontology::list_misses(&state.pool, kb_id).await?;
+ if misses.is_empty() {
+ return Ok(Json(json!({ "entity_types": [], "relation_types": [] })));
+ }
+
+ let current_et: Vec<String> = entity_types.iter().map(|t| t.key.clone()).collect();
+ let current_rt: Vec<String> = relation_types.iter().map(|r| r.key.clone()).collect();
+ let miss_lines: Vec<String> = misses
+ .iter()
+ .map(|m| {
+ format!(
+ "- [{}] \"{}\" seen {} times, e.g. {}",
+ m.kind,
+ m.key,
+ m.count,
+ m.example.as_deref().unwrap_or("-")
+ )
+ })
+ .collect();
+
+ let prompt = format!(
+ "You are an ontology engineer. A knowledge graph has this ontology:\n\
+ Entity type keys: {}\n\
+ Relation type keys: {}\n\
+ \n\
+ During extraction, the LLM repeatedly produced types/relations OUTSIDE this ontology:\n{}\n\
+ \n\
+ Propose ontology extensions that would cover these misses. Merge near-duplicates. \
+ Only propose what is clearly warranted by the misses. Output exactly one JSON object:\n\
+ {{\"entity_types\":[{{\"key\":\"snake_case\",\"label\":\"Display Name\",\"reason\":\"...\"}}],\n\
+ \"relation_types\":[{{\"key\":\"snake_case\",\"label\":\"display label\",\"temporal\":\"state|event|eternal\",\"functional\":false,\"reason\":\"...\"}}]}}",
+ current_et.join(", "),
+ current_rt.join(", "),
+ miss_lines.join("\n")
+ );
+
+ let reply = client
+ .chat(&[ChatMessage {
+ role: "user".into(),
+ content: prompt,
+ }])
+ .await
+ .map_err(AppError::Other)?;
+ let block = utopia_extract::json_block(&reply).map_err(AppError::Other)?;
+ let proposals: serde_json::Value =
+ serde_json::from_str(&block).map_err(|e| AppError::Other(e.into()))?;
+ Ok(Json(proposals))
+}
diff --git a/crates/utopia-server/src/api/review_routes.rs b/crates/utopia-server/src/api/review_routes.rs
new file mode 100644
index 00000000..78f73af7
--- /dev/null
+++ b/crates/utopia-server/src/api/review_routes.rs
@@ -0,0 +1,386 @@
+//! 审核队列 API:消解疑似重复对 + 低置信事实 + 合并日志/回滚。
+
+use axum::extract::{Path, Query, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use uuid::Uuid;
+
+use super::graph_routes::require_kb;
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+const LOW_CONFIDENCE_BELOW: f32 = 0.75;
+
+/// 冲突双方的三元组快照:(旧主语, 旧宾语, 新主语, 新宾语, 谓词标签)。
+type ConflictSnapshot = (String, Option<String>, String, Option<String>, String);
+
+/// 事实快照(决策台账用):reject 后事实从图里消失,台账必须自包含展示文本。
+/// 一律在动作执行前取。
+async fn fact_snapshot(state: &AppState, kb_id: Uuid, fact_id: Uuid) -> Option<serde_json::Value> {
+ // 宾语可能是实体或字面值;结构化字面值优先取 summary(与队列卡片同一显示口径)
+ let row: Option<(String, String, Option<String>, f32)> = sqlx::query_as(
+ "SELECT s.canonical_name, r.label,
+ COALESCE(o.canonical_name, f.object_value ->> 'summary',
+ f.object_value #>> '{}'), f.confidence
+ FROM facts f
+ JOIN entities s ON s.id = f.subject_id
+ JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o ON o.id = f.object_id
+ WHERE f.id = $1 AND f.kb_id = $2",
+ )
+ .bind(fact_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .ok()
+ .flatten();
+ row.map(|(s, p, o, c)| json!({ "subject": s, "predicate": p, "object": o, "confidence": c }))
+}
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let reviews = utopia_store::resolution::list_reviews(&state.pool, kb_id).await?;
+ let facts =
+ utopia_store::graph::low_confidence_facts(&state.pool, kb_id, LOW_CONFIDENCE_BELOW, 100)
+ .await?;
+ let merges = utopia_store::resolution::list_merges(&state.pool, kb_id, 30).await?;
+ let conflicts = utopia_store::temporal::list_conflicts(&state.pool, kb_id).await?;
+ let unconfirmed = utopia_store::graph::stale_facts(&state.pool, kb_id, 100).await?;
+ Ok(Json(json!({
+ "reviews": reviews, "facts": facts, "merges": merges,
+ "conflicts": conflicts, "unconfirmed": unconfirmed
+ })))
+}
+
+#[derive(Deserialize)]
+pub struct CloseFactBody {
+ pub valid_to: chrono::DateTime<chrono::Utc>,
+}
+
+/// 人工闭合一条事实的有效区间("这事在某时结束了")——走作废+改写,
+/// 与自动闭合同一机制,账本可回放。
+pub async fn close_fact(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, fact_id)): Path<(Uuid, Uuid)>,
+ Json(body): Json<CloseFactBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ // 归属与状态校验:本 KB 的、未作废、开放区间的事实才可闭合
+ let ok: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM facts
+ WHERE id = $1 AND kb_id = $2 AND invalidated_at IS NULL AND valid_to IS NULL",
+ )
+ .bind(fact_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .map_err(utopia_core::AppError::Db)?;
+ if ok.is_none() {
+ return Err(utopia_core::AppError::NotFound.into());
+ }
+ let snap = fact_snapshot(&state, kb_id, fact_id).await;
+ utopia_store::temporal::close_superseded(&state.pool, fact_id, body.valid_to).await?;
+ if let Some(mut d) = snap {
+ d["valid_to"] = json!(body.valid_to.to_rfc3339());
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "fact.close",
+ "fact",
+ Some(fact_id),
+ d,
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+#[derive(Deserialize)]
+pub struct ConflictBody {
+ /// close | keep | reject_new
+ pub action: String,
+ /// close 且新事实无起点时必填
+ #[serde(default)]
+ pub close_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+/// 时态冲突裁决(S3:自动闭合拿不准的那些)。
+pub async fn resolve_conflict(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, conflict_id)): Path<(Uuid, Uuid)>,
+ Json(body): Json<ConflictBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ // 快照双方三元组:裁决会作废/改写事实,先抄后动
+ let snap: Option<ConflictSnapshot> = sqlx::query_as(
+ "SELECT os.canonical_name, oo.canonical_name, ns.canonical_name, no_.canonical_name,
+ r.label
+ FROM fact_conflicts c
+ JOIN facts fo ON fo.id = c.old_fact_id
+ JOIN facts fn_ ON fn_.id = c.new_fact_id
+ JOIN entities os ON os.id = fo.subject_id
+ LEFT JOIN entities oo ON oo.id = fo.object_id
+ JOIN entities ns ON ns.id = fn_.subject_id
+ LEFT JOIN entities no_ ON no_.id = fn_.object_id
+ JOIN relation_types r ON r.id = fo.predicate_id
+ WHERE c.id = $1 AND c.kb_id = $2",
+ )
+ .bind(conflict_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .ok()
+ .flatten();
+ utopia_store::temporal::resolve_conflict(
+ &state.pool,
+ kb_id,
+ conflict_id,
+ &body.action,
+ body.close_at,
+ )
+ .await?;
+ if let Some((os, oo, ns, no, pred)) = snap {
+ let action = match body.action.as_str() {
+ "close" => "conflict.close_old",
+ "keep" => "conflict.keep_both",
+ _ => "conflict.reject_new",
+ };
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ action,
+ "conflict",
+ Some(conflict_id),
+ json!({
+ "predicate": pred,
+ "old_subject": os, "old_object": oo,
+ "new_subject": ns, "new_object": no,
+ "close_at": body.close_at.map(|t| t.to_rfc3339()),
+ }),
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+#[derive(Deserialize)]
+pub struct DecideBody {
+ /// merge | keep
+ pub action: String,
+}
+
+pub async fn decide(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, review_id)): Path<(Uuid, Uuid)>,
+ Json(body): Json<DecideBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let snap: Option<(String, String, f32)> = sqlx::query_as(
+ "SELECT a.canonical_name, b.canonical_name, rr.score
+ FROM resolution_reviews rr
+ JOIN entities a ON a.id = rr.left_id
+ JOIN entities b ON b.id = rr.right_id
+ WHERE rr.id = $1 AND rr.kb_id = $2",
+ )
+ .bind(review_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .ok()
+ .flatten();
+ utopia_store::resolution::decide_review(&state.pool, kb_id, review_id, &body.action, user.id)
+ .await?;
+ if let Some((l, r, score)) = snap {
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ if body.action == "merge" {
+ "review.merge"
+ } else {
+ "review.keep"
+ },
+ "review",
+ Some(review_id),
+ json!({ "left": l, "right": r, "score": score }),
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn confirm_fact(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, fact_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let snap = fact_snapshot(&state, kb_id, fact_id).await;
+ utopia_store::graph::confirm_fact(&state.pool, kb_id, fact_id).await?;
+ if let Some(d) = snap {
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "fact.confirm",
+ "fact",
+ Some(fact_id),
+ d,
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn reject_fact(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, fact_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let snap = fact_snapshot(&state, kb_id, fact_id).await;
+ utopia_store::graph::reject_fact(&state.pool, kb_id, fact_id).await?;
+ if let Some(d) = snap {
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "fact.reject",
+ "fact",
+ Some(fact_id),
+ d,
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+pub async fn revert_merge(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, merge_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let snap: Option<(String, String)> = sqlx::query_as(
+ "SELECT s.canonical_name, t.canonical_name
+ FROM entity_merges m
+ JOIN entities s ON s.id = m.source_id
+ JOIN entities t ON t.id = m.target_id
+ WHERE m.id = $1 AND m.kb_id = $2",
+ )
+ .bind(merge_id)
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await
+ .ok()
+ .flatten();
+ utopia_store::resolution::revert_merge(&state.pool, kb_id, merge_id).await?;
+ if let Some((s, t)) = snap {
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "merge.revert",
+ "merge",
+ Some(merge_id),
+ json!({ "source": s, "target": t }),
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "ok": true })))
+}
+
+#[derive(Deserialize)]
+pub struct ManualMergeBody {
+ pub source: Uuid,
+ pub target: Uuid,
+}
+
+/// 手动合并(实体面板"Merge into…"入口)。
+pub async fn manual_merge(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(body): Json<ManualMergeBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let snap: Option<(String,)> = sqlx::query_as(
+ "SELECT s.canonical_name || ' → ' || t.canonical_name
+ FROM entities s, entities t WHERE s.id = $1 AND t.id = $2",
+ )
+ .bind(body.source)
+ .bind(body.target)
+ .fetch_optional(&state.pool)
+ .await
+ .ok()
+ .flatten();
+ let merge_id = utopia_store::resolution::merge_entities(
+ &state.pool,
+ kb_id,
+ body.source,
+ body.target,
+ Some(user.id),
+ "manual merge",
+ )
+ .await?;
+ if let Some((pair,)) = snap {
+ let (s, t) = pair.split_once(" → ").unwrap_or((pair.as_str(), ""));
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "merge.manual",
+ "merge",
+ Some(merge_id),
+ json!({ "source": s, "target": t }),
+ )
+ .await;
+ }
+ state.emit_review(kb_id);
+ Ok(Json(json!({ "merge_id": merge_id })))
+}
+
+#[derive(Deserialize)]
+pub struct HistoryQuery {
+ #[serde(default)]
+ pub page: i64,
+ #[serde(default = "default_history_per")]
+ pub per: i64,
+}
+
+fn default_history_per() -> i64 {
+ 20
+}
+
+/// 决策台账:review 域的审计事件,服务端分页。
+pub async fn history(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Query(q): Query<HistoryQuery>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let per = q.per.clamp(1, 100);
+ let page = q.page.max(0);
+ let (events, total) =
+ utopia_store::audit::review_history(&state.pool, kb_id, per, page * per).await?;
+ Ok(Json(json!({ "events": events, "total": total })))
+}
diff --git a/crates/utopia-server/src/api/search_routes.rs b/crates/utopia-server/src/api/search_routes.rs
new file mode 100644
index 00000000..84854524
--- /dev/null
+++ b/crates/utopia-server/src/api/search_routes.rs
@@ -0,0 +1,36 @@
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::retrieval;
+use crate::state::AppState;
+
+#[derive(Deserialize)]
+pub struct SearchReq {
+ pub q: String,
+ #[serde(default)]
+ pub top_k: Option<usize>,
+}
+
+pub async fn search(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(req): Json<SearchReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let q = req.q.trim();
+ if q.is_empty() {
+ return Err(AppError::Validation("Search query cannot be empty".into()).into());
+ }
+ let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?;
+
+ let top_k = req.top_k.unwrap_or(10).min(50);
+ let chunks = retrieval::hybrid(&state, kb_id, kb.workspace_id, q, top_k).await?;
+ Ok(Json(json!({ "results": chunks })))
+}
diff --git a/crates/utopia-server/src/api/settings_routes.rs b/crates/utopia-server/src/api/settings_routes.rs
new file mode 100644
index 00000000..917d18f6
--- /dev/null
+++ b/crates/utopia-server/src/api/settings_routes.rs
@@ -0,0 +1,116 @@
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use utopia_llm::ChatMessage;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::llm_util;
+use crate::state::AppState;
+
+/// GET:脱敏视图(密钥只回传是否已配置)。
+pub async fn get(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Admin).await?;
+ let s = utopia_store::settings::get(&state.pool, workspace_id).await?;
+ Ok(Json(match s {
+ None => json!({}),
+ Some(s) => json!({
+ "chat_base_url": s.chat_base_url,
+ "chat_model": s.chat_model,
+ "has_chat_key": s.chat_api_key.as_deref().is_some_and(|k| !k.is_empty()),
+ "embed_base_url": s.embed_base_url,
+ "embed_model": s.embed_model,
+ "embed_dim": s.embed_dim,
+ "has_embed_key": s.embed_api_key.as_deref().is_some_and(|k| !k.is_empty()),
+ }),
+ }))
+}
+
+#[derive(Deserialize)]
+pub struct PutSettingsReq {
+ pub chat_base_url: Option<String>,
+ /// None 或空串 = 保留旧密钥
+ pub chat_api_key: Option<String>,
+ pub chat_model: Option<String>,
+ pub embed_base_url: Option<String>,
+ pub embed_api_key: Option<String>,
+ pub embed_model: Option<String>,
+ pub embed_dim: Option<i32>,
+}
+
+pub async fn put(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+ Json(req): Json<PutSettingsReq>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Admin).await?;
+ let nonempty = |v: &Option<String>| -> Option<String> {
+ v.as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(String::from)
+ };
+ utopia_store::settings::upsert(
+ &state.pool,
+ workspace_id,
+ nonempty(&req.chat_base_url).as_deref(),
+ nonempty(&req.chat_api_key).as_deref(),
+ nonempty(&req.chat_model).as_deref(),
+ nonempty(&req.embed_base_url).as_deref(),
+ nonempty(&req.embed_api_key).as_deref(),
+ nonempty(&req.embed_model).as_deref(),
+ req.embed_dim,
+ )
+ .await?;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 连通性测试:对话发一条最小消息;embedding 试算一条并返回维度。
+pub async fn test(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(workspace_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, workspace_id, Role::Admin).await?;
+ let Some(s) = utopia_store::settings::get(&state.pool, workspace_id).await? else {
+ return Ok(Json(
+ json!({ "chat": { "ok": false, "error": "Not configured" },
+ "embed": { "ok": false, "error": "Not configured" } }),
+ ));
+ };
+
+ let chat_result = match llm_util::chat_client(&s) {
+ None => json!({ "ok": false, "error": "Not configured" }),
+ Some(client) => {
+ let msg = [ChatMessage {
+ role: "user".into(),
+ content: "Reply with exactly one word: OK".into(),
+ }];
+ match client.chat(&msg).await {
+ Ok(reply) => {
+ json!({ "ok": true, "reply": reply.chars().take(50).collect::<String>() })
+ }
+ Err(e) => json!({ "ok": false, "error": e.to_string() }),
+ }
+ }
+ };
+
+ let embed_result = match llm_util::embed_client(&s) {
+ None => json!({ "ok": false, "error": "Not configured" }),
+ Some(client) => match client.embed(&["connectivity test".to_string()]).await {
+ Ok(v) if !v.is_empty() => json!({ "ok": true, "dim": v[0].len() }),
+ Ok(_) => json!({ "ok": false, "error": "Empty response" }),
+ Err(e) => json!({ "ok": false, "error": e.to_string() }),
+ },
+ };
+
+ Ok(Json(json!({ "chat": chat_result, "embed": embed_result })))
+}
diff --git a/crates/utopia-server/src/api/sources_routes.rs b/crates/utopia-server/src/api/sources_routes.rs
new file mode 100644
index 00000000..253feac5
--- /dev/null
+++ b/crates/utopia-server/src/api/sources_routes.rs
@@ -0,0 +1,443 @@
+//! 来源管理 API + 文本推送摄入(ingest)。
+
+use axum::extract::{Path, State};
+use axum::http::HeaderMap;
+use axum::Json;
+use chrono::{DateTime, Utc};
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::Role;
+use uuid::Uuid;
+
+use super::graph_routes::require_kb;
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+/// 生成 api 来源的推送密钥。
+fn new_ingest_token() -> String {
+ format!("utp_{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
+}
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let sources = utopia_store::sources::list(&state.pool, kb_id).await?;
+ Ok(Json(json!({ "sources": sources })))
+}
+
+#[derive(Deserialize)]
+pub struct CreateBody {
+ pub kind: String,
+ pub name: String,
+ #[serde(default)]
+ pub config: serde_json::Value,
+ #[serde(default)]
+ pub icon: Option<String>,
+ #[serde(default)]
+ pub sync_interval_minutes: Option<i32>,
+ /// 标准 5 段 cron(与 interval 互斥,二者传其一)
+ #[serde(default)]
+ pub sync_cron: Option<String>,
+}
+
+pub async fn create(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(body): Json<CreateBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let source = utopia_store::sources::create(
+ &state.pool,
+ kb_id,
+ &body.kind,
+ &body.name,
+ &body.config,
+ body.icon.as_deref(),
+ body.sync_interval_minutes,
+ body.sync_cron.as_deref(),
+ )
+ .await?;
+ // 拉取型来源建好立即同步一次(有配置即产出,无需等下一个调度周期)
+ if matches!(source.kind.as_str(), "url" | "rss" | "custom") {
+ let _ = utopia_store::sources::mark_queued(&state.pool, source.id).await;
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "sync_source",
+ json!({ "source_id": source.id }),
+ )
+ .await?;
+ }
+ // api 来源:生成专属推送密钥(此后可随时经 get_token 查看)
+ let mut ingest_token: Option<String> = None;
+ if source.kind == "api" {
+ let token = new_ingest_token();
+ utopia_store::sources::set_ingest_token(&state.pool, source.id, &token).await?;
+ ingest_token = Some(token);
+ }
+ state.emit_source(kb_id);
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "source.created",
+ "source",
+ Some(source.id),
+ json!({ "kind": source.kind, "name": source.name }),
+ )
+ .await;
+ Ok(Json(
+ json!({ "source": mask_secrets(source), "ingest_token": ingest_token }),
+ ))
+}
+
+/// 查看 api 来源的推送密钥(Editor;列表响应从不携带,查看走这里)。
+pub async fn get_token(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let source = utopia_store::sources::get(&state.pool, source_id).await?;
+ if source.kb_id != kb_id || source.kind != "api" {
+ return Err(utopia_core::AppError::NotFound.into());
+ }
+ Ok(Json(json!({ "ingest_token": source.ingest_token })))
+}
+
+/// 轮换 api 来源的推送密钥:旧密钥立即失效。
+pub async fn rotate_token(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let source = utopia_store::sources::get(&state.pool, source_id).await?;
+ if source.kb_id != kb_id || source.kind != "api" {
+ return Err(utopia_core::AppError::NotFound.into());
+ }
+ let token = new_ingest_token();
+ utopia_store::sources::set_ingest_token(&state.pool, source_id, &token).await?;
+ Ok(Json(json!({ "ingest_token": token })))
+}
+
+/// 响应前剔除凭据(auth_header 只进不出)。
+fn mask_secrets(mut source: utopia_core::models::Source) -> utopia_core::models::Source {
+ if let Some(obj) = source.config.as_object_mut() {
+ obj.remove("auth_header");
+ }
+ source
+}
+
+#[derive(Deserialize)]
+pub struct UpdateBody {
+ pub name: Option<String>,
+ pub config: Option<serde_json::Value>,
+ pub icon: Option<String>,
+ /// 出现 schedule 字段即整体覆盖调度(interval 与 cron 互斥;两者皆 null = 关闭定时)
+ #[serde(default)]
+ pub schedule: Option<ScheduleBody>,
+}
+
+#[derive(Deserialize)]
+pub struct ScheduleBody {
+ #[serde(default)]
+ pub sync_interval_minutes: Option<i32>,
+ #[serde(default)]
+ pub sync_cron: Option<String>,
+}
+
+pub async fn update(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+ Json(body): Json<UpdateBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ // 凭据只进不出:响应从不回显 auth_header,表单留空 = 保留库里原值
+ let mut config = body.config;
+ if let Some(cfg) = config.as_mut() {
+ let blank = cfg
+ .get("auth_header")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .is_none_or(|s| s.is_empty());
+ if blank {
+ if let Some(obj) = cfg.as_object_mut() {
+ obj.remove("auth_header");
+ let existing = utopia_store::sources::get(&state.pool, source_id).await?;
+ if let Some(prev) = existing.config.get("auth_header").and_then(|v| v.as_str()) {
+ obj.insert("auth_header".into(), json!(prev));
+ }
+ }
+ }
+ }
+ let source = utopia_store::sources::update(
+ &state.pool,
+ source_id,
+ body.name.as_deref(),
+ config.as_ref(),
+ body.icon.as_deref(),
+ body.schedule
+ .map(|s| (s.sync_interval_minutes, s.sync_cron)),
+ )
+ .await?;
+ state.emit_source(kb_id);
+ // 审计不落凭据:config 只记除 auth_header 外的键
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "source.updated",
+ "source",
+ Some(source_id),
+ json!({ "name": body.name, "config_changed": config.is_some() }),
+ )
+ .await;
+ Ok(Json(json!({ "source": mask_secrets(source) })))
+}
+
+/// 批量删除该来源下所有"不在来源中"的文档(url 对账 / custom 墓碑标出的)。
+pub async fn cleanup_missing(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let ids = utopia_store::documents::list_missing(&state.pool, source_id).await?;
+ for id in &ids {
+ utopia_store::documents::delete(&state.pool, *id).await?;
+ let search = state.search.clone();
+ let did = id.to_string();
+ tokio::task::spawn_blocking(move || search.delete_document(&did))
+ .await
+ .map_err(|e| utopia_core::AppError::Other(e.into()))?
+ .map_err(utopia_core::AppError::Other)?;
+ }
+ state.emit_source(kb_id);
+ Ok(Json(json!({ "deleted": ids.len() })))
+}
+
+pub async fn delete(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ // Memory 来源常驻:记忆空间不因来源整理而蒸发(记忆文档本身可在 Library 删除)
+ let source = utopia_store::sources::get(&state.pool, source_id).await?;
+ if source.kind == utopia_store::memory::MEMORY_SOURCE_KIND {
+ return Err(
+ utopia_core::AppError::Validation("The Memory source is permanent.".into()).into(),
+ );
+ }
+ utopia_store::sources::delete(&state.pool, source_id).await?;
+ state.emit_source(kb_id);
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ Some(kb_id),
+ user.id,
+ "source.deleted",
+ "source",
+ Some(source_id),
+ json!({}),
+ )
+ .await;
+ Ok(Json(json!({ "ok": true })))
+}
+
+/// 同步运行历史(渠道审计)。
+pub async fn runs(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Viewer).await?;
+ let runs = utopia_store::sources::list_runs(&state.pool, source_id, 20).await?;
+ Ok(Json(json!({ "runs": runs })))
+}
+
+pub async fn sync_now(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ let queued = utopia_store::sources::mark_queued(&state.pool, source_id).await?;
+ if queued {
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "sync_source",
+ json!({ "source_id": source_id }),
+ )
+ .await?;
+ state.emit_source(kb_id);
+ }
+ Ok(Json(json!({ "queued": queued })))
+}
+
+#[derive(Deserialize)]
+pub struct IngestBody {
+ pub filename: String,
+ pub content: String,
+ #[serde(default)]
+ pub doc_time: Option<DateTime<Utc>>,
+ /// 调用方的逻辑文档 ID:同 ID 再推 = 更新同一文档(原地替换 + 版本记录)。
+ /// 不传则以 filename 为身份。
+ #[serde(default)]
+ pub external_id: Option<String>,
+ /// 墓碑:true = 按身份标记"不在来源中"(不删除;仅 api 来源推送支持)。
+ /// 此时 content 可省略;再次正常推送同身份会摘掉标记。
+ #[serde(default)]
+ pub deleted: bool,
+}
+
+fn action_str(action: crate::ingest_sources::IngestAction) -> &'static str {
+ match action {
+ crate::ingest_sources::IngestAction::Created => "created",
+ crate::ingest_sources::IngestAction::Updated => "updated",
+ crate::ingest_sources::IngestAction::Moved => "moved",
+ crate::ingest_sources::IngestAction::Unchanged => "unchanged",
+ crate::ingest_sources::IngestAction::Tombstoned => "marked_missing",
+ }
+}
+
+/// KB 级文本推送(会话认证):普通上传语义——落入 Uploads,无身份追踪。
+/// 需要"同 ID 再推 = 更新"语义时,建一个 api 来源用它的密钥推送。
+pub async fn ingest(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(kb_id): Path<Uuid>,
+ Json(body): Json<IngestBody>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_kb(&state, &user, kb_id, Role::Editor).await?;
+ if body.deleted {
+ return Err(utopia_core::AppError::Validation(
+ "tombstones need identity tracking — push to an api source instead".into(),
+ )
+ .into());
+ }
+ if body.filename.trim().is_empty() || body.content.trim().is_empty() {
+ return Err(
+ utopia_core::AppError::Validation("filename and content are required".into()).into(),
+ );
+ }
+ let action = crate::ingest_sources::ingest_upload(
+ &state,
+ kb_id,
+ body.filename.trim(),
+ "text/plain",
+ body.content.as_bytes(),
+ body.doc_time,
+ )
+ .await
+ .map_err(utopia_core::AppError::Other)?;
+ Ok(Json(json!({ "action": action_str(action) })))
+}
+
+/// 认证之后的推送处理:解析 + 校验 + 摄入/墓碑。错误一律返回文字(记进 run)。
+async fn handle_push(
+ state: &AppState,
+ source: &utopia_core::models::Source,
+ bytes: &[u8],
+) -> Result<crate::ingest_sources::IngestAction, String> {
+ let body: IngestBody =
+ serde_json::from_slice(bytes).map_err(|e| format!("Invalid JSON payload: {e}"))?;
+ let identity = body
+ .external_id
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| body.filename.trim())
+ .to_string();
+ if identity.is_empty() {
+ return Err("external_id or filename is required".into());
+ }
+ let key = format!("api:{identity}");
+
+ // 墓碑:标记"不在来源中"(与 custom 的 deleted[] 同一条路径),content 可省略
+ if body.deleted {
+ utopia_store::documents::mark_missing_keys(&state.pool, source.id, &[key])
+ .await
+ .map_err(|e| e.to_string())?;
+ return Ok(crate::ingest_sources::IngestAction::Tombstoned);
+ }
+
+ if body.filename.trim().is_empty() || body.content.trim().is_empty() {
+ return Err("filename and content are required".into());
+ }
+ let action = crate::ingest_sources::ingest_item(
+ state,
+ source.kb_id,
+ source.id,
+ &key,
+ body.filename.trim(),
+ "text/plain",
+ body.content.as_bytes(),
+ body.doc_time,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ // 失而复得:曾被墓碑标记的身份再次正常推送,摘掉 missing 标记
+ utopia_store::documents::clear_missing_keys(&state.pool, source.id, &[key])
+ .await
+ .map_err(|e| e.to_string())?;
+ Ok(action)
+}
+
+/// api 来源推送(来源专属密钥认证,无会话):三路身份语义——
+/// 新 external_id → 新增;同 ID 同内容 → 无操作;同 ID 新内容 → 原地更新 + 版本记录。
+/// 认证通过后每次推送都记一条 run(含格式错误——集成调试全靠它);
+/// 未认证请求不写任何记录(不给匿名流量制造落库路径)。
+pub async fn push(
+ State(state): State<AppState>,
+ Path(source_id): Path<Uuid>,
+ headers: HeaderMap,
+ bytes: axum::body::Bytes,
+) -> ApiResult<Json<serde_json::Value>> {
+ let source = utopia_store::sources::get(&state.pool, source_id).await?;
+ if source.kind != "api" {
+ return Err(utopia_core::AppError::NotFound.into());
+ }
+ // Bearer 密钥校验
+ let token = headers
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .ok_or(utopia_core::AppError::Unauthorized)?;
+ if source.ingest_token.as_deref() != Some(token) {
+ return Err(utopia_core::AppError::Unauthorized.into());
+ }
+
+ let run = utopia_store::sources::start_run(&state.pool, source.id).await?;
+ match handle_push(&state, &source, &bytes).await {
+ Ok(action) => {
+ let (created, updated) = match action {
+ crate::ingest_sources::IngestAction::Created => (1, 0),
+ crate::ingest_sources::IngestAction::Updated
+ | crate::ingest_sources::IngestAction::Moved => (0, 1),
+ crate::ingest_sources::IngestAction::Unchanged
+ | crate::ingest_sources::IngestAction::Tombstoned => (0, 0),
+ };
+ utopia_store::sources::finish_run(&state.pool, run, source.id, None, created, updated)
+ .await?;
+ // 来源行同步反映"上一次推送":操作条/左栏状态点直接可用
+ utopia_store::sources::finish_sync(&state.pool, source.id, None, created).await?;
+ state.emit_source(source.kb_id);
+ Ok(Json(json!({ "action": action_str(action) })))
+ }
+ Err(msg) => {
+ utopia_store::sources::finish_run(&state.pool, run, source.id, Some(&msg), 0, 0)
+ .await?;
+ utopia_store::sources::finish_sync(&state.pool, source.id, Some(&msg), 0).await?;
+ state.emit_source(source.kb_id);
+ Err(utopia_core::AppError::Validation(msg).into())
+ }
+ }
+}
diff --git a/crates/utopia-server/src/api/workspaces.rs b/crates/utopia-server/src/api/workspaces.rs
new file mode 100644
index 00000000..e9ab62da
--- /dev/null
+++ b/crates/utopia-server/src/api/workspaces.rs
@@ -0,0 +1,75 @@
+use axum::extract::{Path, State};
+use axum::Json;
+use serde::Deserialize;
+use serde_json::json;
+use utopia_core::models::{Role, Workspace};
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::auth::AuthUser;
+use crate::error::ApiResult;
+use crate::state::AppState;
+
+#[derive(Deserialize)]
+pub struct NameReq {
+ pub name: String,
+}
+
+fn validate_name(name: &str) -> Result<&str, AppError> {
+ let name = name.trim();
+ if name.is_empty() || name.chars().count() > 64 {
+ return Err(AppError::Validation("Name must be 1-64 characters".into()));
+ }
+ Ok(name)
+}
+
+pub async fn list(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+) -> ApiResult<Json<Vec<Workspace>>> {
+ let list = utopia_store::workspaces::list_for_user(&state.pool, user.id).await?;
+ Ok(Json(list))
+}
+
+pub async fn create(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Json(req): Json<NameReq>,
+) -> ApiResult<Json<Workspace>> {
+ let name = validate_name(&req.name)?;
+ let ws = utopia_store::workspaces::create(&state.pool, user.org_id, user.id, name).await?;
+ Ok(Json(ws))
+}
+
+pub async fn get_one(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ let role =
+ utopia_store::workspaces::require_role(&state.pool, user.id, id, Role::Viewer).await?;
+ let ws = utopia_store::workspaces::get(&state.pool, id).await?;
+ Ok(Json(json!({ "workspace": ws, "role": role })))
+}
+
+pub async fn rename(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+ Json(req): Json<NameReq>,
+) -> ApiResult<Json<Workspace>> {
+ let name = validate_name(&req.name)?;
+ utopia_store::workspaces::require_role(&state.pool, user.id, id, Role::Admin).await?;
+ let ws = utopia_store::workspaces::rename(&state.pool, id, name).await?;
+ Ok(Json(ws))
+}
+
+pub async fn delete(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(id): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ utopia_store::workspaces::require_role(&state.pool, user.id, id, Role::Owner).await?;
+ utopia_store::workspaces::delete(&state.pool, id).await?;
+ Ok(Json(json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/auth.rs b/crates/utopia-server/src/auth.rs
new file mode 100644
index 00000000..48b35c79
--- /dev/null
+++ b/crates/utopia-server/src/auth.rs
@@ -0,0 +1,108 @@
+//! 认证:argon2 密码哈希 + JWT(HttpOnly Cookie,同时接受 Bearer)。
+//! Cookie 本身是会话 cookie,过期由 JWT 的 exp 控制(7 天)。
+
+use argon2::password_hash::rand_core::OsRng;
+use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
+use argon2::Argon2;
+use axum::extract::FromRequestParts;
+use axum::http::request::Parts;
+use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
+use chrono::Utc;
+use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
+use serde::{Deserialize, Serialize};
+use utopia_core::models::User;
+use utopia_core::AppError;
+use uuid::Uuid;
+
+use crate::error::ApiErr;
+use crate::state::AppState;
+
+pub const COOKIE_NAME: &str = "utopia_token";
+const TOKEN_TTL_DAYS: i64 = 7;
+
+#[derive(Debug, Serialize, Deserialize)]
+struct Claims {
+ sub: Uuid,
+ exp: i64,
+}
+
+pub fn hash_password(password: &str) -> Result<String, AppError> {
+ let salt = SaltString::generate(&mut OsRng);
+ Argon2::default()
+ .hash_password(password.as_bytes(), &salt)
+ .map(|h| h.to_string())
+ .map_err(|e| AppError::Other(anyhow::anyhow!("Password hashing failed: {e}")))
+}
+
+pub fn verify_password(password: &str, hash: &str) -> bool {
+ PasswordHash::new(hash)
+ .map(|parsed| {
+ Argon2::default()
+ .verify_password(password.as_bytes(), &parsed)
+ .is_ok()
+ })
+ .unwrap_or(false)
+}
+
+pub fn issue_token(state: &AppState, user_id: Uuid) -> Result<String, AppError> {
+ let claims = Claims {
+ sub: user_id,
+ exp: (Utc::now() + chrono::Duration::days(TOKEN_TTL_DAYS)).timestamp(),
+ };
+ encode(
+ &Header::default(),
+ &claims,
+ &EncodingKey::from_secret(state.jwt_secret.as_bytes()),
+ )
+ .map_err(|e| AppError::Other(anyhow::anyhow!("Token issuance failed: {e}")))
+}
+
+pub fn auth_cookie(token: String) -> Cookie<'static> {
+ Cookie::build((COOKIE_NAME, token))
+ .path("/")
+ .http_only(true)
+ .same_site(SameSite::Lax)
+ .build()
+}
+
+fn decode_user_id(state: &AppState, token: &str) -> Result<Uuid, AppError> {
+ let data = decode::<Claims>(
+ token,
+ &DecodingKey::from_secret(state.jwt_secret.as_bytes()),
+ &Validation::default(),
+ )
+ .map_err(|_| AppError::Unauthorized)?;
+ Ok(data.claims.sub)
+}
+
+/// 已登录用户提取器:Cookie `utopia_token` 或 `Authorization: Bearer`。
+pub struct AuthUser(pub User);
+
+impl FromRequestParts<AppState> for AuthUser {
+ type Rejection = ApiErr;
+
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &AppState,
+ ) -> Result<Self, Self::Rejection> {
+ let jar = CookieJar::from_headers(&parts.headers);
+ let token = jar
+ .get(COOKIE_NAME)
+ .map(|c| c.value().to_string())
+ .or_else(|| {
+ parts
+ .headers
+ .get(axum::http::header::AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .map(|v| v.to_string())
+ })
+ .ok_or(AppError::Unauthorized)?;
+
+ let user_id = decode_user_id(state, &token)?;
+ let user = utopia_store::accounts::find_user_by_id(&state.pool, user_id)
+ .await?
+ .ok_or(AppError::Unauthorized)?;
+ Ok(AuthUser(user))
+ }
+}
diff --git a/crates/utopia-server/src/blob.rs b/crates/utopia-server/src/blob.rs
new file mode 100644
index 00000000..cef08a1b
--- /dev/null
+++ b/crates/utopia-server/src/blob.rs
@@ -0,0 +1,52 @@
+//! BlobStore:原始文件字节的存取接缝。
+//!
+//! 内容寻址——key 就是文件内容的 sha256,接口里没有"路径"概念:本地是分桶前的
+//! 平铺目录、对象存储是 object key,任何 KV 都能实现。幂等、去重、不可变
+//! (内容变了指纹就变,旧版永不覆盖——"版本回放有料"的物质基础)全部由
+//! "内容即地址"免费获得。
+//!
+//! 现阶段唯一实现是本地磁盘(data/files/{sha256})。将来接对象存储/网盘
+//! (P5 连接器、多实例部署共享存储)只需新增实现,摄入/上传/解析/回放的
+//! 调用方一行不改。配置入口 UTOPIA_BLOB_BACKEND 预留,当前仅接受 "local"。
+
+use std::path::PathBuf;
+
+#[async_trait::async_trait]
+pub trait BlobStore: Send + Sync {
+ /// 幂等写入:同指纹已存在即跳过。
+ async fn put(&self, sha256: &str, bytes: &[u8]) -> anyhow::Result<()>;
+ async fn get(&self, sha256: &str) -> anyhow::Result<Vec<u8>>;
+ #[allow(dead_code)] // 接口完整性:回放/GC 路径的将来消费者
+ async fn exists(&self, sha256: &str) -> anyhow::Result<bool>;
+}
+
+/// 本地磁盘实现:`{dir}/{sha256}` 平铺存放(与历史行为逐字节一致)。
+pub struct LocalBlobStore {
+ dir: PathBuf,
+}
+
+impl LocalBlobStore {
+ pub fn new(dir: PathBuf) -> Self {
+ Self { dir }
+ }
+}
+
+#[async_trait::async_trait]
+impl BlobStore for LocalBlobStore {
+ async fn put(&self, sha256: &str, bytes: &[u8]) -> anyhow::Result<()> {
+ tokio::fs::create_dir_all(&self.dir).await?;
+ let path = self.dir.join(sha256);
+ if !path.exists() {
+ tokio::fs::write(&path, bytes).await?;
+ }
+ Ok(())
+ }
+
+ async fn get(&self, sha256: &str) -> anyhow::Result<Vec<u8>> {
+ Ok(tokio::fs::read(self.dir.join(sha256)).await?)
+ }
+
+ async fn exists(&self, sha256: &str) -> anyhow::Result<bool> {
+ Ok(self.dir.join(sha256).exists())
+ }
+}
diff --git a/crates/utopia-server/src/docs_corpus.rs b/crates/utopia-server/src/docs_corpus.rs
new file mode 100644
index 00000000..f5fcfffc
--- /dev/null
+++ b/crates/utopia-server/src/docs_corpus.rs
@@ -0,0 +1,103 @@
+//! Charter 语料:与前端 Docs 页同一批 markdown(单一事实来源,随二进制升级)。
+//! 新增文章 = 前端 Docs.tsx 清单加一行 + 这里 ARTICLES 加一行。
+
+use utopia_search::{DocsIndex, DocsSection};
+
+/// (slug, 标题, 正文)。slug 必须与前端 DOCS 清单一致(引用链接 /docs/{slug} 才对得上)。
+const ARTICLES: &[(&str, &str, &str)] = &[(
+ "ingest",
+ "Ingest interfaces",
+ include_str!("../../../web/src/docs/ingest.md"),
+)];
+
+/// 启动时建索引;语料是编译期常量,失败即程序错误,响亮地死。
+pub fn build_index() -> DocsIndex {
+ DocsIndex::build(&sections()).expect("Charter 文档索引构建失败")
+}
+
+/// 按 h2 切节:一节一条索引记录,命中返回具体小节而不是整篇。
+/// h2 之前的引言归入"标题节"(anchor 为空,链接落到文章顶部)。
+fn sections() -> Vec<DocsSection> {
+ let mut out = Vec::new();
+ for (slug, title, body) in ARTICLES {
+ let mut heading = (*title).to_string();
+ let mut anchor = String::new();
+ let mut buf: Vec<&str> = Vec::new();
+ let mut flush = |heading: &str, anchor: &str, buf: &mut Vec<&str>| {
+ let text = buf.join("\n").trim().to_string();
+ if !text.is_empty() {
+ out.push(DocsSection {
+ slug: (*slug).to_string(),
+ title: (*title).to_string(),
+ heading: heading.to_string(),
+ anchor: anchor.to_string(),
+ body: text,
+ });
+ }
+ buf.clear();
+ };
+ for line in body.lines() {
+ if let Some(h) = line.strip_prefix("## ") {
+ flush(&heading, &anchor, &mut buf);
+ // 与前端 tocOf 同法清洗:去掉行内 code/强调符号
+ heading = h.replace(['`', '*'], "").trim().to_string();
+ anchor = slugify(&heading);
+ } else if !line.starts_with("# ") {
+ buf.push(line);
+ }
+ }
+ flush(&heading, &anchor, &mut buf);
+ }
+ out
+}
+
+/// 与前端 Docs.tsx 的 slugify 逐字对齐(锚点跳转依赖两边一致):
+/// 小写后,[a-z0-9一-龥] 之外的连续串折成单个 '-',再去掉首尾 '-'。
+fn slugify(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut dash = false;
+ for c in s.to_lowercase().chars() {
+ let keep =
+ c.is_ascii_lowercase() || c.is_ascii_digit() || ('\u{4e00}'..='\u{9fa5}').contains(&c);
+ if keep {
+ if dash && !out.is_empty() {
+ out.push('-');
+ }
+ dash = false;
+ out.push(c);
+ } else {
+ dash = true;
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn slugify_matches_frontend() {
+ assert_eq!(slugify("Choosing between them"), "choosing-between-them");
+ assert_eq!(
+ slugify("Custom source — the pull interface"),
+ "custom-source-the-pull-interface"
+ );
+ assert_eq!(
+ slugify("API source — the push interface"),
+ "api-source-the-push-interface"
+ );
+ assert_eq!(slugify("共享语义 Shared"), "共享语义-shared");
+ }
+
+ #[test]
+ fn ingest_splits_into_sections() {
+ let secs = sections();
+ assert!(secs.len() >= 4, "ingest.md 应切出引言 + 3 个以上小节");
+ assert!(secs.iter().any(|s| s.anchor == "shared-semantics"));
+ // 引言节:anchor 空,heading 用文章标题
+ assert!(secs
+ .iter()
+ .any(|s| s.anchor.is_empty() && s.heading == "Ingest interfaces"));
+ }
+}
diff --git a/crates/utopia-server/src/error.rs b/crates/utopia-server/src/error.rs
new file mode 100644
index 00000000..f9e426fb
--- /dev/null
+++ b/crates/utopia-server/src/error.rs
@@ -0,0 +1,43 @@
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::Json;
+use serde_json::json;
+use utopia_core::AppError;
+
+/// axum 响应包装(orphan rule:IntoResponse 不能直接实现在 core 类型上)。
+pub struct ApiErr(pub AppError);
+
+impl<E: Into<AppError>> From<E> for ApiErr {
+ fn from(e: E) -> Self {
+ ApiErr(e.into())
+ }
+}
+
+pub type ApiResult<T> = Result<T, ApiErr>;
+
+impl IntoResponse for ApiErr {
+ fn into_response(self) -> Response {
+ let (status, message) = match &self.0 {
+ AppError::NotFound => (StatusCode::NOT_FOUND, self.0.to_string()),
+ AppError::Unauthorized => (StatusCode::UNAUTHORIZED, self.0.to_string()),
+ AppError::Forbidden => (StatusCode::FORBIDDEN, self.0.to_string()),
+ AppError::Conflict(m) => (StatusCode::CONFLICT, m.clone()),
+ AppError::Validation(m) => (StatusCode::UNPROCESSABLE_ENTITY, m.clone()),
+ AppError::Db(e) => {
+ tracing::error!(error = %e, "database error");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "Internal server error".into(),
+ )
+ }
+ AppError::Other(e) => {
+ tracing::error!(error = %e, "internal error");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "Internal server error".into(),
+ )
+ }
+ };
+ (status, Json(json!({ "error": message }))).into_response()
+ }
+}
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
new file mode 100644
index 00000000..a06d5a6c
--- /dev/null
+++ b/crates/utopia-server/src/extraction.rs
@@ -0,0 +1,462 @@
+//! 图谱抽取任务:逐分块调用 LLM → 实体消解 v2 → 事实 + 证据写入账本。
+//! 与摄入管道分离(两段式可用):索引完成即可搜可问,抽取慢慢跑。
+//! 消解灰区只入审核队列并触发独立的攒批裁决任务——LLM 裁决永不阻塞本任务。
+
+use crate::llm_util;
+use crate::state::AppState;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+const MIN_CONFIDENCE: f32 = 0.6;
+
+pub async fn extract_document(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
+ match run(state, document_id).await {
+ Ok(()) => Ok(()),
+ Err(e) => {
+ let _ =
+ utopia_store::documents::set_graph_status(&state.pool, document_id, "failed").await;
+ if let Ok(doc) = utopia_store::documents::get(&state.pool, document_id).await {
+ state.emit_document(doc.kb_id, document_id);
+ }
+ Err(e)
+ }
+ }
+}
+
+/// mention → 实体 id。同一文档内同名同类型直接复用(单文档语境里罕有同名不同人,
+/// 也把消解调用摊薄到每个名字一次);跨文档歧义由 resolve_mention 的画像比对处理。
+async fn resolve(
+ state: &AppState,
+ kb_id: Uuid,
+ type_id: Uuid,
+ name: &str,
+ ctx: Option<&[f32]>,
+ doc_cache: &mut HashMap<(Uuid, String), Uuid>,
+ needs_adjudication: &mut bool,
+) -> anyhow::Result<Uuid> {
+ let key = (
+ type_id,
+ utopia_store::resolution::normalize_name(name).to_lowercase(),
+ );
+ if let Some(id) = doc_cache.get(&key) {
+ return Ok(*id);
+ }
+ let r =
+ utopia_store::resolution::resolve_mention(&state.pool, kb_id, type_id, name, ctx).await?;
+ // 疑似重复对(同名灰区 / 类型漂移)入审核队列,攒批裁决任务收尾统一触发
+ for review in &r.reviews {
+ utopia_store::resolution::create_review(
+ &state.pool,
+ kb_id,
+ r.entity_id,
+ review.other_id,
+ review.score,
+ &review.reason,
+ )
+ .await?;
+ *needs_adjudication = true;
+ }
+ doc_cache.insert(key, r.entity_id);
+ Ok(r.entity_id)
+}
+
+async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
+ let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+ let kb = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
+ let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("Chat model not configured; cannot extract"))?;
+ let client = llm_util::chat_client(&settings)
+ .ok_or_else(|| anyhow::anyhow!("Chat model not configured; cannot extract"))?;
+
+ utopia_store::documents::set_graph_status(&state.pool, document_id, "extracting").await?;
+ state.emit_document(doc.kb_id, document_id);
+ utopia_store::graph::ensure_default_ontology(&state.pool, doc.kb_id).await?;
+
+ let etypes = utopia_store::graph::entity_types(&state.pool, doc.kb_id).await?;
+ let rtypes = utopia_store::graph::relation_types(&state.pool, doc.kb_id).await?;
+ let type_pairs: Vec<(String, String, String)> = etypes
+ .iter()
+ .map(|t| (t.key.clone(), t.label.clone(), t.description.clone()))
+ .collect();
+ // 关系与属性分道:属性走字面值通道,不进关系清单
+ let rel_pairs: Vec<(String, String, String)> = rtypes
+ .iter()
+ .filter(|r| r.kind != "attribute")
+ .map(|r| (r.key.clone(), r.label.clone(), r.description.clone()))
+ .collect();
+ let type_ids: HashMap<&str, Uuid> = etypes.iter().map(|t| (t.key.as_str(), t.id)).collect();
+ let rel_ids: HashMap<&str, Uuid> = rtypes.iter().map(|r| (r.key.as_str(), r.id)).collect();
+ // 时态对账只对带唯一性约束的状态关系生效(本体元数据):(functional, inverse_functional, temporal)
+ let rel_meta: HashMap<Uuid, (bool, bool, String)> = rtypes
+ .iter()
+ .map(|r| {
+ (
+ r.id,
+ (r.functional, r.inverse_functional, r.temporal.clone()),
+ )
+ })
+ .collect();
+ // 属性元数据(按 key 查)与提示词清单("person.salary (number, CNY): 月薪")。
+ // 没定义属性时清单为空,提示词一字不变
+ let type_key_by_id: HashMap<Uuid, &str> =
+ etypes.iter().map(|t| (t.id, t.key.as_str())).collect();
+ let type_parent: HashMap<Uuid, Option<Uuid>> =
+ etypes.iter().map(|t| (t.id, t.parent_id)).collect();
+ let attr_meta: HashMap<&str, &utopia_core::models::RelationType> = rtypes
+ .iter()
+ .filter(|r| r.kind == "attribute")
+ .map(|r| (r.key.as_str(), r))
+ .collect();
+ let attr_lines: Vec<String> = rtypes
+ .iter()
+ .filter(|r| r.kind == "attribute")
+ .filter_map(|r| {
+ let class_key = type_key_by_id.get(&r.domain_type_id?)?;
+ let dt = r.datatype.as_deref().unwrap_or("text");
+ let spec = match &r.unit {
+ Some(u) if !u.is_empty() => format!("{dt}, {u}"),
+ _ => dt.to_string(),
+ };
+ let d = r.description.trim();
+ Some(if d.is_empty() {
+ format!("- {class_key}.{} ({spec})", r.key)
+ } else {
+ format!("- {class_key}.{} ({spec}): {d}", r.key)
+ })
+ })
+ .collect();
+ // 属性 domain 允许子类:主语类型沿 parent 链上溯命中 domain 即可
+ let type_matches_domain = |mut ty: Uuid, domain: Uuid| -> bool {
+ for _ in 0..10 {
+ if ty == domain {
+ return true;
+ }
+ match type_parent.get(&ty).copied().flatten() {
+ Some(p) => ty = p,
+ None => return false,
+ }
+ }
+ false
+ };
+ let concept_type = *type_ids
+ .get("concept")
+ .ok_or_else(|| anyhow::anyhow!("Ontology missing the 'concept' type"))?;
+ let related_rel = rel_ids.get("related_to").copied();
+
+ let doc_time = doc.doc_time.map(|t| t.format("%Y-%m-%d").to_string());
+ let chunks = utopia_store::documents::chunks_for_extraction(&state.pool, document_id).await?;
+
+ let mut doc_cache: HashMap<(Uuid, String), Uuid> = HashMap::new();
+ let mut needs_adjudication = false;
+ let mut conflicts_found = false;
+ let mut fact_count = 0usize;
+ // 不设分块上限:静默截断等于丢知识,长文档的成本由部署者自己权衡
+ // (成本优化走 prompt 前缀缓存与更新时 chunk 级跳过,而非丢数据)
+ for chunk in chunks.iter() {
+ let ctx: Option<&[f32]> = chunk.embedding.as_ref().map(|v| v.as_slice());
+ let messages = utopia_extract::build_messages(
+ &type_pairs,
+ &rel_pairs,
+ &attr_lines,
+ doc_time.as_deref(),
+ &doc.filename,
+ &chunk.text,
+ );
+ let reply = match client.chat(&messages).await {
+ Ok(r) => r,
+ Err(e) => {
+ tracing::warn!(%document_id, seq = chunk.seq, error = %e, "抽取调用失败,跳过该分块");
+ continue;
+ }
+ };
+ let extraction = match utopia_extract::parse_response(&reply) {
+ Ok(x) => x,
+ Err(e) => {
+ tracing::warn!(%document_id, seq = chunk.seq, error = %e, "抽取结果解析失败,跳过该分块");
+ continue;
+ }
+ };
+
+ // 实体消解:名称 → 实体 id(本分块的事实按原文名字连线)
+ let mut entity_ids: HashMap<String, Uuid> = HashMap::new();
+ // 名称 → 声明类型(属性 domain 校验用:salary 不能挂在 Organization 上)
+ let mut entity_type_of: HashMap<String, Uuid> = HashMap::new();
+ for e in &extraction.entities {
+ let name = e.name.trim();
+ if name.is_empty() || name.chars().count() > 100 {
+ continue;
+ }
+ let type_id = match type_ids.get(e.type_key.as_str()) {
+ Some(id) => *id,
+ None => {
+ // 白名单外类型:降级 concept,并记入未匹配统计(本体扩展的信号)
+ let _ = utopia_store::ontology::record_miss(
+ &state.pool,
+ doc.kb_id,
+ "entity_type",
+ &e.type_key,
+ Some(name),
+ )
+ .await;
+ concept_type
+ }
+ };
+ let id = resolve(
+ state,
+ doc.kb_id,
+ type_id,
+ name,
+ ctx,
+ &mut doc_cache,
+ &mut needs_adjudication,
+ )
+ .await?;
+ entity_ids.insert(name.to_string(), id);
+ entity_type_of.insert(name.to_string(), type_id);
+ }
+
+ for f in &extraction.facts {
+ let confidence = f.confidence.unwrap_or(0.7).clamp(0.0, 1.0);
+ if confidence < MIN_CONFIDENCE {
+ continue;
+ }
+ let from = f.valid_from.as_deref().and_then(utopia_extract::parse_time);
+ let to = f.valid_to.as_deref().and_then(utopia_extract::parse_time);
+ let precision = from.map(|(_, p)| p).unwrap_or("day");
+
+ // 属性事实:谓词命中属性 → 字面值通道。datatype 校验失败宁缺勿脏;
+ // domain 校验(含子类上溯)挡住"把 salary 挂到 Organization"这类张冠李戴。
+ // 模型偶尔照抄清单里的 "person.salary" 全限定名——剥掉类前缀再查一次
+ let attr_hit = attr_meta.get(f.predicate.as_str()).or_else(|| {
+ f.predicate
+ .rsplit_once('.')
+ .and_then(|(_, k)| attr_meta.get(k))
+ });
+ if let Some(attr) = attr_hit {
+ let subject_name = f.subject.trim();
+ let Some((&subject_id, &subject_type)) = entity_ids
+ .get(subject_name)
+ .zip(entity_type_of.get(subject_name))
+ else {
+ continue; // 主语没在 entities 里声明:类型不明,属性不落
+ };
+ let Some(domain) = attr.domain_type_id else {
+ continue;
+ };
+ if !type_matches_domain(subject_type, domain) {
+ continue;
+ }
+ let raw = match (&f.value, &f.object) {
+ (Some(v), _) => v.clone(),
+ // 模型偶尔把值放进 object:宽容接住
+ (None, Some(o)) if !o.trim().is_empty() => {
+ serde_json::Value::String(o.trim().to_string())
+ }
+ _ => continue,
+ };
+ let datatype = attr.datatype.as_deref().unwrap_or("text");
+ let Some(normalized) = utopia_extract::normalize_attr_value(datatype, &raw) else {
+ tracing::debug!(%document_id, attr = attr.key, ?raw, "属性值不合 datatype,跳过");
+ continue;
+ };
+ let mut object_value = serde_json::json!({ "value": normalized });
+ if let Some(u) = attr.unit.as_deref().filter(|u| !u.is_empty()) {
+ // 单位随事实落笔:类型上的单位以后改了,旧值仍按记录时的单位读
+ object_value["unit"] = serde_json::json!(u);
+ }
+ let (fact_id, created) = utopia_store::graph::insert_value_fact(
+ &state.pool,
+ doc.kb_id,
+ subject_id,
+ attr.id,
+ &object_value,
+ from.map(|(t, _)| t),
+ to.map(|(t, _)| t),
+ precision,
+ confidence,
+ )
+ .await?;
+ utopia_store::graph::add_evidence(
+ &state.pool,
+ fact_id,
+ chunk.id,
+ f.quote.as_deref(),
+ )
+ .await?;
+ if !created {
+ continue;
+ }
+ fact_count += 1;
+ // 单值属性 = functional:新值闭合旧值(属性历史由此而来)
+ if attr.functional && attr.temporal == "state" {
+ let report = utopia_store::temporal::reconcile_new_fact(
+ &state.pool,
+ doc.kb_id,
+ fact_id,
+ subject_id,
+ attr.id,
+ None,
+ Some(&object_value),
+ utopia_store::temporal::Uniqueness::SubjectSide,
+ from.map(|(t, _)| t),
+ to.map(|(t, _)| t),
+ confidence,
+ )
+ .await?;
+ if report.conflicts > 0 {
+ conflicts_found = true;
+ }
+ }
+ continue;
+ }
+
+ // 关系事实:宾语必填
+ let Some(object_name) = f.object.as_deref().map(str::trim).filter(|s| !s.is_empty())
+ else {
+ continue;
+ };
+ // 主宾未在 entities 中声明时,按 concept 兜底消解(模型偶尔漏报)
+ let subject_id = match entity_ids.get(f.subject.trim()) {
+ Some(id) => *id,
+ None => {
+ resolve(
+ state,
+ doc.kb_id,
+ concept_type,
+ f.subject.trim(),
+ ctx,
+ &mut doc_cache,
+ &mut needs_adjudication,
+ )
+ .await?
+ }
+ };
+ let object_id = match entity_ids.get(object_name) {
+ Some(id) => *id,
+ None => {
+ resolve(
+ state,
+ doc.kb_id,
+ concept_type,
+ object_name,
+ ctx,
+ &mut doc_cache,
+ &mut needs_adjudication,
+ )
+ .await?
+ }
+ };
+ if subject_id == object_id {
+ continue;
+ }
+ // 未知关系降级为 related_to,并记入未匹配统计
+ let predicate_id = match rel_ids.get(f.predicate.as_str()) {
+ Some(id) => *id,
+ None => {
+ let _ = utopia_store::ontology::record_miss(
+ &state.pool,
+ doc.kb_id,
+ "relation_type",
+ &f.predicate,
+ Some(&format!("{} → {}", f.subject, object_name)),
+ )
+ .await;
+ match related_rel {
+ Some(id) => id,
+ None => continue,
+ }
+ }
+ };
+
+ {
+ let (fact_id, created) = utopia_store::graph::insert_fact(
+ &state.pool,
+ doc.kb_id,
+ subject_id,
+ predicate_id,
+ object_id,
+ from.map(|(t, _)| t),
+ to.map(|(t, _)| t),
+ precision,
+ confidence,
+ )
+ .await?;
+ // 重复观察也要挂证据:多来源相互印证,任一来源删除后事实不孤儿化
+ utopia_store::graph::add_evidence(
+ &state.pool,
+ fact_id,
+ chunk.id,
+ f.quote.as_deref(),
+ )
+ .await?;
+ if !created {
+ continue;
+ }
+ fact_count += 1;
+ // 时态对账:带唯一性约束的状态关系落新事实即检测矛盾(纯规则点查,
+ // 自动闭合走"作废+改写",拿不准进 fact_conflicts 人裁)
+ if let Some((func, inv_func, temporal)) = rel_meta.get(&predicate_id) {
+ if temporal == "state" {
+ let mut directions = Vec::new();
+ if *func {
+ directions.push(utopia_store::temporal::Uniqueness::SubjectSide);
+ }
+ if *inv_func {
+ directions.push(utopia_store::temporal::Uniqueness::ObjectSide);
+ }
+ for dir in directions {
+ let report = utopia_store::temporal::reconcile_new_fact(
+ &state.pool,
+ doc.kb_id,
+ fact_id,
+ subject_id,
+ predicate_id,
+ Some(object_id),
+ None,
+ dir,
+ from.map(|(t, _)| t),
+ to.map(|(t, _)| t),
+ confidence,
+ )
+ .await?;
+ if report.conflicts > 0 {
+ conflicts_found = true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // 本块抽取完成即打标:更新时被认领的块携带标记跳过;中断的抽取可续跑
+ // (LLM 调用/解析失败的块在上方 continue 掉,不打标,下次重试)
+ utopia_store::documents::mark_chunk_extracted(&state.pool, chunk.id).await?;
+ }
+
+ // 消歧后缀在实体创建时算会早于其事实写入——收尾时对本文档涉及的名字统一刷新
+ let names: std::collections::HashSet<&str> =
+ doc_cache.keys().map(|(_, name)| name.as_str()).collect();
+ for name in names {
+ utopia_store::resolution::refresh_disambiguators(&state.pool, doc.kb_id, name).await?;
+ }
+
+ utopia_store::documents::set_graph_status(&state.pool, document_id, "done").await?;
+ state.emit_document(doc.kb_id, document_id);
+
+ // 灰区对进了审核队列 → 触发攒批裁决任务(独立后台跑,抽取本身到此已完成)
+ if needs_adjudication {
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "adjudicate_entities",
+ serde_json::json!({ "kb_id": doc.kb_id }),
+ )
+ .await?;
+ }
+ if needs_adjudication || conflicts_found {
+ state.emit_review(doc.kb_id);
+ }
+
+ tracing::info!(%document_id, facts = fact_count, "图谱抽取完成");
+ Ok(())
+}
diff --git a/crates/utopia-server/src/ingest_sources.rs b/crates/utopia-server/src/ingest_sources.rs
new file mode 100644
index 00000000..f11bcc59
--- /dev/null
+++ b/crates/utopia-server/src/ingest_sources.rs
@@ -0,0 +1,574 @@
+//! 来源同步任务:url(网页抓取)/ rss(订阅,pubDate → doc_time)。
+//! 全部走 sha256 去重(重复内容静默跳过),新文档进标准摄入管道(process_document)。
+//! folder 是纯容器(上传入内),api 是推送型——两者无拉取语义。
+
+use crate::state::AppState;
+use chrono::{DateTime, Utc};
+use sha2::{Digest, Sha256};
+use utopia_core::models::Source;
+use uuid::Uuid;
+
+/// 单次同步的新文档上限(防超长 feed/URL 列表拖垮任务)
+const MAX_NEW_PER_SYNC: usize = 200;
+
+/// 单次同步的产出统计(Moved/Unchanged 不计)。
+#[derive(Debug, Default, Clone, Copy)]
+pub struct SyncStats {
+ pub created: usize,
+ pub updated: usize,
+}
+
+impl SyncStats {
+ fn absorb(&mut self, action: IngestAction) {
+ match action {
+ IngestAction::Created => self.created += 1,
+ IngestAction::Updated => self.updated += 1,
+ _ => {}
+ }
+ }
+ fn total(&self) -> usize {
+ self.created + self.updated
+ }
+}
+
+pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<()> {
+ let source = utopia_store::sources::get(&state.pool, source_id).await?;
+ utopia_store::sources::mark_running(&state.pool, source_id).await?;
+ let run_id = utopia_store::sources::start_run(&state.pool, source_id).await?;
+ state.emit_source(source.kb_id);
+
+ let outcome = match source.kind.as_str() {
+ "url" => sync_urls(state, &source).await,
+ "rss" => sync_rss(state, &source).await,
+ "custom" => sync_custom(state, &source).await,
+ // folder / api 无拉取语义
+ _ => Ok(SyncStats::default()),
+ };
+
+ match outcome {
+ Ok(stats) => {
+ utopia_store::sources::finish_run(
+ &state.pool,
+ run_id,
+ source_id,
+ None,
+ stats.created as i32,
+ stats.updated as i32,
+ )
+ .await?;
+ utopia_store::sources::finish_sync(&state.pool, source_id, None, stats.total() as i32)
+ .await?;
+ state.emit_source(source.kb_id);
+ tracing::info!(%source_id, kind = %source.kind, created = stats.created, updated = stats.updated, "来源同步完成");
+ Ok(())
+ }
+ Err(e) => {
+ utopia_store::sources::finish_run(
+ &state.pool,
+ run_id,
+ source_id,
+ Some(&e.to_string()),
+ 0,
+ 0,
+ )
+ .await?;
+ utopia_store::sources::finish_sync(&state.pool, source_id, Some(&e.to_string()), 0)
+ .await?;
+ state.emit_source(source.kb_id);
+ Err(e)
+ }
+ }
+}
+
+/// 三路判定的结果。
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum IngestAction {
+ Created,
+ Updated,
+ Moved,
+ Unchanged,
+ /// 墓碑:标记"不在来源中"(不删除文档,删不删由用户在 UI 决定)
+ Tombstoned,
+}
+
+async fn write_blob(state: &AppState, sha256: &str, bytes: &[u8]) -> anyhow::Result<()> {
+ state.blob.put(sha256, bytes).await
+}
+
+fn sha_hex(bytes: &[u8]) -> String {
+ Sha256::digest(bytes)
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect()
+}
+
+/// 普通上传语义的推送(KB 级 /ingest → Uploads):无来源、无身份键,
+/// 不做三路判定——KB 内已有同内容时视为无操作,其余一律新建。
+pub async fn ingest_upload(
+ state: &AppState,
+ kb_id: Uuid,
+ filename: &str,
+ mime: &str,
+ bytes: &[u8],
+ doc_time: Option<DateTime<Utc>>,
+) -> anyhow::Result<IngestAction> {
+ if bytes.is_empty() {
+ return Ok(IngestAction::Unchanged);
+ }
+ let sha256 = sha_hex(bytes);
+ write_blob(state, &sha256, bytes).await?;
+ match utopia_store::documents::create(
+ &state.pool,
+ kb_id,
+ filename,
+ mime,
+ bytes.len() as i64,
+ &sha256,
+ None,
+ doc_time,
+ None,
+ )
+ .await
+ {
+ Ok(doc) => {
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "process_document",
+ serde_json::json!({ "document_id": doc.id }),
+ )
+ .await?;
+ state.emit_document(kb_id, doc.id);
+ Ok(IngestAction::Created)
+ }
+ Err(utopia_core::AppError::Conflict(_)) => Ok(IngestAction::Unchanged),
+ Err(e) => Err(e.into()),
+ }
+}
+
+/// 身份感知摄入:按 (source, external_key) 三路判定——
+/// 新增(建文档)/ 变更(原地替换 + 版本记录 + 重跑管道)/ 未变(跳过);
+/// 同内容换路径识别为移动(只改身份,不重跑)。external_key 为 URI 形态
+/// (file:/// 相对路径、页面 URL、rss guid、api:{id}),出处自描述,
+/// 也为 P5 SPARQL 投影的文档 IRI 提前对齐。
+#[allow(clippy::too_many_arguments)]
+pub async fn ingest_item(
+ state: &AppState,
+ kb_id: Uuid,
+ source_id: Uuid,
+ external_key: &str,
+ filename: &str,
+ mime: &str,
+ bytes: &[u8],
+ doc_time: Option<DateTime<Utc>>,
+) -> anyhow::Result<IngestAction> {
+ if bytes.is_empty() {
+ return Ok(IngestAction::Unchanged);
+ }
+ let sha256 = sha_hex(bytes);
+
+ // 主判定:逻辑身份;兜底:迁移前的历史文档(无 key)按文件名认领并补键
+ let mut existing =
+ utopia_store::documents::find_by_external_key(&state.pool, source_id, external_key).await?;
+ if existing.is_none() {
+ if let Some(legacy) =
+ utopia_store::documents::find_legacy_by_filename(&state.pool, source_id, filename)
+ .await?
+ {
+ utopia_store::documents::adopt_external_key(&state.pool, legacy.id, external_key)
+ .await?;
+ // 认领时把旧内容记为版本 1(此前没有版本记录)
+ utopia_store::documents::record_version(
+ &state.pool,
+ legacy.id,
+ &legacy.sha256,
+ legacy.size_bytes,
+ )
+ .await?;
+ existing = Some(legacy);
+ }
+ }
+
+ if let Some(doc) = existing {
+ if doc.sha256 == sha256 {
+ return Ok(IngestAction::Unchanged);
+ }
+ // 变更:原地替换,旧版本入 document_versions(blob 内容寻址不删,回放有料)
+ write_blob(state, &sha256, bytes).await?;
+ utopia_store::documents::replace_content(
+ &state.pool,
+ doc.id,
+ filename,
+ mime,
+ bytes.len() as i64,
+ &sha256,
+ doc_time,
+ )
+ .await?;
+ utopia_store::documents::record_version(&state.pool, doc.id, &sha256, bytes.len() as i64)
+ .await?;
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "process_document",
+ serde_json::json!({ "document_id": doc.id }),
+ )
+ .await?;
+ state.emit_document(kb_id, doc.id);
+ return Ok(IngestAction::Updated);
+ }
+
+ // 同内容出现在新路径:识别为移动/改名,不重跑管道
+ if let Some(doc) =
+ utopia_store::documents::find_by_source_sha(&state.pool, source_id, &sha256).await?
+ {
+ utopia_store::documents::update_location(&state.pool, doc.id, filename, external_key)
+ .await?;
+ state.emit_document(kb_id, doc.id);
+ return Ok(IngestAction::Moved);
+ }
+
+ write_blob(state, &sha256, bytes).await?;
+ match utopia_store::documents::create(
+ &state.pool,
+ kb_id,
+ filename,
+ mime,
+ bytes.len() as i64,
+ &sha256,
+ Some(source_id),
+ doc_time,
+ Some(external_key),
+ )
+ .await
+ {
+ Ok(doc) => {
+ utopia_store::documents::record_version(
+ &state.pool,
+ doc.id,
+ &sha256,
+ bytes.len() as i64,
+ )
+ .await?;
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "process_document",
+ serde_json::json!({ "document_id": doc.id }),
+ )
+ .await?;
+ state.emit_document(kb_id, doc.id);
+ Ok(IngestAction::Created)
+ }
+ // KB 内已有同内容(如手动上传过同一文件):不重复摄入
+ Err(utopia_core::AppError::Conflict(_)) => Ok(IngestAction::Unchanged),
+ Err(e) => Err(e.into()),
+ }
+}
+
+async fn sync_urls(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
+ let urls: Vec<String> = source.config["urls"]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(String::from)
+ .collect()
+ })
+ .unwrap_or_default();
+ if urls.is_empty() {
+ anyhow::bail!("url source is missing config.urls (a list of page URLs)");
+ }
+
+ let http = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .build()?;
+ let mut stats = SyncStats::default();
+ let mut last_err: Option<String> = None;
+ for url in urls.iter().take(MAX_NEW_PER_SYNC) {
+ match fetch_page(&http, url).await {
+ Ok((filename, mime, bytes)) => {
+ // 逻辑身份 = URL 本身:页面内容变了就原地替换(历史进版本表)
+ let action = ingest_item(
+ state,
+ source.kb_id,
+ source.id,
+ url,
+ &filename,
+ &mime,
+ &bytes,
+ None,
+ )
+ .await?;
+ stats.absorb(action);
+ }
+ Err(e) => {
+ tracing::warn!(%url, error = %e, "抓取失败");
+ last_err = Some(format!("{url}: {e}"));
+ }
+ }
+ }
+ // 部分失败:有产出则视为成功(错误进日志),全军覆没才报错
+ if stats.total() == 0 {
+ if let Some(err) = last_err {
+ anyhow::bail!("{err}");
+ }
+ }
+ // 配置列表即全集:不在列表里的文档标"不在来源中"(抓取失败不算——它仍被配置着)
+ utopia_store::documents::reconcile_missing(&state.pool, source.id, &urls)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+ Ok(stats)
+}
+
+async fn fetch_page(
+ http: &reqwest::Client,
+ url: &str,
+) -> anyhow::Result<(String, String, Vec<u8>)> {
+ let resp = http.get(url).send().await?;
+ if !resp.status().is_success() {
+ anyhow::bail!("HTTP {}", resp.status());
+ }
+ let mime = resp
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("text/html")
+ .split(';')
+ .next()
+ .unwrap_or("text/html")
+ .to_string();
+ let bytes = resp.bytes().await?.to_vec();
+ let filename = filename_from_url(url, &mime);
+ Ok((filename, mime, bytes))
+}
+
+fn filename_from_url(url: &str, mime: &str) -> String {
+ let stripped = url
+ .trim_start_matches("https://")
+ .trim_start_matches("http://")
+ .trim_end_matches('/');
+ let mut slug: String = stripped
+ .chars()
+ .map(|c| {
+ if c.is_alphanumeric() || c == '.' || c == '-' {
+ c
+ } else {
+ '-'
+ }
+ })
+ .collect();
+ slug.truncate(120);
+ let has_ext = slug
+ .rsplit('.')
+ .next()
+ .map(|e| e.len() <= 5)
+ .unwrap_or(false)
+ && slug.contains('.')
+ && !slug.ends_with('.');
+ if !has_ext || mime.contains("html") {
+ format!("{slug}.html")
+ } else {
+ slug
+ }
+}
+
+async fn sync_rss(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
+ let feed_url = source.config["feed_url"]
+ .as_str()
+ .filter(|s| !s.trim().is_empty())
+ .ok_or_else(|| anyhow::anyhow!("rss source is missing config.feed_url"))?;
+
+ let http = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .build()?;
+ let resp = http.get(feed_url).send().await?;
+ if !resp.status().is_success() {
+ anyhow::bail!("HTTP {} fetching feed", resp.status());
+ }
+ let bytes = resp.bytes().await?;
+ let feed = feed_rs::parser::parse(&bytes[..])
+ .map_err(|e| anyhow::anyhow!("Failed to parse feed: {e}"))?;
+
+ let mut stats = SyncStats::default();
+ for entry in feed.entries.iter().take(MAX_NEW_PER_SYNC) {
+ let title = entry
+ .title
+ .as_ref()
+ .map(|t| t.content.clone())
+ .unwrap_or_else(|| "untitled".into());
+ let link = entry
+ .links
+ .first()
+ .map(|l| l.href.clone())
+ .unwrap_or_default();
+ // 逻辑身份:feed 规范的 guid(通常已是 permalink/urn),缺失时退条目链接
+ let key = if !entry.id.trim().is_empty() {
+ entry.id.trim().to_string()
+ } else if !link.is_empty() {
+ link.clone()
+ } else {
+ format!("entry:{}", sha_hex(title.as_bytes()))
+ };
+ let body = entry
+ .content
+ .as_ref()
+ .and_then(|c| c.body.clone())
+ .or_else(|| entry.summary.as_ref().map(|s| s.content.clone()))
+ .unwrap_or_default();
+ // 条目发布时间 → 文档时间:时态抽取吃到真实时间戳(本平台的差异化正在于此)
+ let doc_time = entry.published.or(entry.updated);
+
+ let html = format!(
+ "<html><head><title>{}</title></head><body><h1>{}</h1>\n<p><a href=\"{}\">{}</a></p>\n{}</body></html>",
+ title, title, link, link, body
+ );
+ let mut slug: String = title
+ .chars()
+ .map(|c| if c.is_alphanumeric() { c } else { '-' })
+ .collect();
+ slug.truncate(80);
+ let filename = format!("{slug}.html");
+
+ let action = ingest_item(
+ state,
+ source.kb_id,
+ source.id,
+ &key,
+ &filename,
+ "text/html",
+ html.as_bytes(),
+ doc_time,
+ )
+ .await?;
+ stats.absorb(action);
+ }
+ Ok(stats)
+}
+
+/// 自定义拉取器 —— Utopia Ingest Interface:
+/// `GET {endpoint}?since=<上次同步 RFC3339>`(首次同步不带 since;可配 Authorization 头),
+/// 响应 `{"items":[{"id":"稳定唯一ID","title":"文档名","content":"正文(纯文本/Markdown/HTML)",
+/// "doc_time":"RFC3339 可选","mime":"text/markdown 可选"}]}`。
+/// id → external_key(custom:{id}),三路判定生效:同 id 同内容跳过、新内容原地更新。
+async fn sync_custom(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
+ let endpoint = source.config["endpoint"]
+ .as_str()
+ .filter(|s| !s.trim().is_empty())
+ .ok_or_else(|| anyhow::anyhow!("custom source is missing config.endpoint"))?;
+ let mut url =
+ reqwest::Url::parse(endpoint).map_err(|e| anyhow::anyhow!("Invalid endpoint URL: {e}"))?;
+ if let Some(t) = source.last_sync_at {
+ url.query_pairs_mut().append_pair("since", &t.to_rfc3339());
+ }
+
+ // loopback 端点不走系统代理:代理对回环地址只会 502,本机服务必须直连
+ let loopback = url
+ .host_str()
+ .map(|h| {
+ h.eq_ignore_ascii_case("localhost") || h == "127.0.0.1" || h == "::1" || h == "[::1]"
+ })
+ .unwrap_or(false);
+ let mut builder = reqwest::Client::builder().timeout(std::time::Duration::from_secs(30));
+ if loopback {
+ builder = builder.no_proxy();
+ }
+ let http = builder.build()?;
+ let mut req = http.get(url);
+ if let Some(auth) = source.config["auth_header"]
+ .as_str()
+ .filter(|s| !s.trim().is_empty())
+ {
+ req = req.header(reqwest::header::AUTHORIZATION, auth.trim());
+ }
+ let resp = req.send().await?;
+ if !resp.status().is_success() {
+ anyhow::bail!("HTTP {} from endpoint", resp.status());
+ }
+ let body: serde_json::Value = resp.json().await?;
+ let items = body["items"]
+ .as_array()
+ .ok_or_else(|| anyhow::anyhow!("Response is missing the items[] array"))?;
+
+ let mut stats = SyncStats::default();
+ let mut seen_keys: Vec<String> = Vec::new();
+ for item in items.iter().take(MAX_NEW_PER_SYNC) {
+ let Some(id) = item["id"].as_str().map(str::trim).filter(|s| !s.is_empty()) else {
+ tracing::warn!(source_id = %source.id, "custom item 缺少 id,跳过");
+ continue;
+ };
+ let Some(content) = item["content"].as_str().filter(|s| !s.trim().is_empty()) else {
+ tracing::warn!(source_id = %source.id, %id, "custom item 缺少 content,跳过");
+ continue;
+ };
+ let title = item["title"]
+ .as_str()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .unwrap_or(id);
+ let mime = item["mime"].as_str().unwrap_or("text/markdown");
+ let doc_time = item["doc_time"]
+ .as_str()
+ .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
+ .map(|t| t.with_timezone(&Utc));
+ let filename = ensure_extension(title, mime);
+ let key = format!("custom:{id}");
+ let action = ingest_item(
+ state,
+ source.kb_id,
+ source.id,
+ &key,
+ &filename,
+ mime,
+ content.as_bytes(),
+ doc_time,
+ )
+ .await?;
+ stats.absorb(action);
+ seen_keys.push(key);
+ }
+ // 增量响应(?since=)里缺席≠删除,不做全集对账;但:
+ // 1) 再次出现的条目摘掉 missing 标记(失而复得)
+ // 2) 显式墓碑 deleted[] 才标"不在来源中"——删不删文档由用户在 UI 决定
+ if !seen_keys.is_empty() {
+ utopia_store::documents::clear_missing_keys(&state.pool, source.id, &seen_keys)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+ }
+ let tombstones: Vec<String> = body["deleted"]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str())
+ .map(|id| format!("custom:{}", id.trim()))
+ .collect()
+ })
+ .unwrap_or_default();
+ if !tombstones.is_empty() {
+ let n = utopia_store::documents::mark_missing_keys(&state.pool, source.id, &tombstones)
+ .await
+ .map_err(|e| anyhow::anyhow!(e))?;
+ tracing::info!(source_id = %source.id, count = n, "custom 墓碑:标记不在来源中");
+ }
+ Ok(stats)
+}
+
+/// 标题无扩展名时按 mime 补一个,接入解析矩阵的分派。
+fn ensure_extension(title: &str, mime: &str) -> String {
+ let has_ext = title
+ .rsplit('.')
+ .next()
+ .map(|e| e.len() <= 5 && e.len() >= 2 && !e.contains(' '))
+ .unwrap_or(false)
+ && title.contains('.');
+ if has_ext {
+ return title.to_string();
+ }
+ let ext = if mime.contains("html") {
+ "html"
+ } else if mime.contains("plain") {
+ "txt"
+ } else {
+ "md"
+ };
+ format!("{title}.{ext}")
+}
diff --git a/crates/utopia-server/src/llm_util.rs b/crates/utopia-server/src/llm_util.rs
new file mode 100644
index 00000000..257253aa
--- /dev/null
+++ b/crates/utopia-server/src/llm_util.rs
@@ -0,0 +1,26 @@
+//! 从工作区设置构造 LLM 客户端。
+
+use utopia_core::models::LlmSettings;
+use utopia_llm::LlmClient;
+
+pub fn chat_client(s: &LlmSettings) -> Option<LlmClient> {
+ if !s.chat_ready() {
+ return None;
+ }
+ Some(LlmClient::new(
+ s.chat_base_url.as_deref()?,
+ s.chat_api_key.as_deref(),
+ s.chat_model.as_deref()?,
+ ))
+}
+
+pub fn embed_client(s: &LlmSettings) -> Option<LlmClient> {
+ if !s.embed_ready() {
+ return None;
+ }
+ Some(LlmClient::new(
+ s.embed_base_url.as_deref()?,
+ s.embed_api_key.as_deref(),
+ s.embed_model.as_deref()?,
+ ))
+}
diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs
new file mode 100644
index 00000000..3d111eb6
--- /dev/null
+++ b/crates/utopia-server/src/main.rs
@@ -0,0 +1,174 @@
+mod adjudication;
+mod api;
+mod auth;
+mod blob;
+mod docs_corpus;
+mod error;
+mod extraction;
+mod ingest_sources;
+mod llm_util;
+mod mappings;
+mod pipeline;
+mod query_engine;
+mod retrieval;
+mod state;
+
+use state::AppState;
+use std::sync::Arc;
+use tracing_subscriber::EnvFilter;
+use utopia_core::config::AppConfig;
+use utopia_search::SearchIndex;
+use uuid::Uuid;
+
+fn payload_document_id(payload: &serde_json::Value) -> anyhow::Result<Uuid> {
+ payload
+ .get("document_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 document_id"))
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ dotenvy::dotenv().ok();
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,utopia=debug".into()),
+ )
+ .init();
+
+ let cfg = AppConfig::load()?;
+ let pool = utopia_store::db::connect(&cfg.database_url).await?;
+ utopia_store::db::migrate(&pool).await?;
+ tracing::info!("数据库迁移完成");
+
+ let index_dir = std::path::Path::new(&cfg.data_dir).join("index");
+ let search = Arc::new(SearchIndex::open(&index_dir)?);
+ tracing::info!("全文索引就绪: {}", index_dir.display());
+
+ let state = AppState::new(pool.clone(), &cfg, search);
+
+ // worker 并发数:系统设置持久化,启动时装载;运行中经同一 AtomicUsize 热调
+ let n = utopia_store::access::worker_concurrency(&pool)
+ .await
+ .unwrap_or(4);
+ state.worker_concurrency.store(
+ n.clamp(1, 32) as usize,
+ std::sync::atomic::Ordering::Relaxed,
+ );
+
+ // 任务分发:新任务类型在这里注册
+ let worker_state = state.clone();
+ tokio::spawn(utopia_store::jobs::run_worker(
+ pool,
+ state.worker_concurrency.clone(),
+ move |job| {
+ let st = worker_state.clone();
+ async move {
+ match job.kind.as_str() {
+ "noop" => {
+ tracing::info!(job_id = job.id, "noop 任务执行成功");
+ Ok(())
+ }
+ "process_document" => {
+ let id = payload_document_id(&job.payload)?;
+ pipeline::process_document(&st, id).await
+ }
+ "memory_ingest" => {
+ let id = payload_document_id(&job.payload)?;
+ pipeline::memory_ingest(&st, id).await
+ }
+ "explore_mappings" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ mappings::explore_mappings(&st, kb_id).await
+ }
+ "extract_document" => {
+ let id = payload_document_id(&job.payload)?;
+ extraction::extract_document(&st, id).await
+ }
+ "adjudicate_entities" => {
+ let kb_id: Uuid = job
+ .payload
+ .get("kb_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?;
+ adjudication::adjudicate_entities(&st, kb_id).await
+ }
+ "sync_source" => {
+ let source_id: Uuid = job
+ .payload
+ .get("source_id")
+ .and_then(|v| v.as_str())
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| anyhow::anyhow!("payload 缺少 source_id"))?;
+ ingest_sources::sync_source(&st, source_id).await
+ }
+ other => anyhow::bail!("未知任务类型: {other}"),
+ }
+ }
+ },
+ ));
+
+ // 定时摄入调度器:每分钟扫一次到期来源,入队同步任务
+ let sched_state = state.clone();
+ tokio::spawn(async move {
+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(60));
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ tick.tick().await;
+ match utopia_store::sources::due_sources(&sched_state.pool).await {
+ Ok(due) => {
+ for s in due {
+ match utopia_store::sources::mark_queued(&sched_state.pool, s.id).await {
+ Ok(true) => {
+ if let Err(e) = utopia_store::jobs::enqueue(
+ &sched_state.pool,
+ "sync_source",
+ serde_json::json!({ "source_id": s.id }),
+ )
+ .await
+ {
+ tracing::warn!(source_id = %s.id, error = %e, "同步任务入队失败");
+ }
+ }
+ Ok(false) => {}
+ Err(e) => tracing::warn!(source_id = %s.id, error = %e, "标记入队失败"),
+ }
+ }
+ }
+ Err(e) => tracing::warn!(error = %e, "扫描到期来源失败"),
+ }
+ }
+ });
+
+ let app = api::router(state, &cfg);
+ let listener = tokio::net::TcpListener::bind(&cfg.bind_addr).await?;
+ tracing::info!("Utopia 服务启动于 http://{}", cfg.bind_addr);
+
+ // 浏览器可能把 localhost 解析为 ::1(IPv6)——配置为 IPv4 地址时补一个同端口的
+ // IPv6 回环监听,避免「找不到 localhost」。绑定失败(端口被占/无 IPv6)仅告警。
+ if let Ok(addr) = cfg.bind_addr.parse::<std::net::SocketAddrV4>() {
+ let v6_addr = format!("[::1]:{}", addr.port());
+ match tokio::net::TcpListener::bind(&v6_addr).await {
+ Ok(v6_listener) => {
+ tracing::info!("同时监听 http://{v6_addr}");
+ let app_v6 = app.clone();
+ tokio::spawn(async move {
+ if let Err(e) = axum::serve(v6_listener, app_v6).await {
+ tracing::warn!(error = %e, "IPv6 监听退出");
+ }
+ });
+ }
+ Err(e) => tracing::warn!(error = %e, "IPv6 回环绑定失败(不影响 IPv4)"),
+ }
+ }
+
+ axum::serve(listener, app).await?;
+ Ok(())
+}
diff --git a/crates/utopia-server/src/mappings.rs b/crates/utopia-server/src/mappings.rs
new file mode 100644
index 00000000..4bb0184c
--- /dev/null
+++ b/crates/utopia-server/src/mappings.rs
@@ -0,0 +1,189 @@
+//! 问数语义映射的 Agentic 探索:读挂载源的 schema + KB 既有概念,让 LLM 提议
+//! "业务概念(Metric/Dimension 实体)→ 数据资产定义" 的映射。
+//!
+//! 提议以低置信(0.6)mapped_to 事实落库 → 自动流入 Review 的低置信区,
+//! Confirm/Reject 零新 UI;确认(置信提满)后的映射注入问数 prompt。
+//! agent 只提议,口径生效权在人——与消解"宁分勿合"同一哲学。
+
+use crate::llm_util;
+use crate::state::AppState;
+use uuid::Uuid;
+
+const PROPOSAL_CONFIDENCE: f32 = 0.6;
+const MAX_SCHEMA_CHARS: usize = 12_000;
+
+pub async fn explore_mappings(state: &AppState, kb_id: Uuid) -> anyhow::Result<()> {
+ let kb = utopia_store::kbs::get(&state.pool, kb_id).await?;
+ let settings = utopia_store::settings::get(&state.pool, kb.workspace_id)
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("Chat model not configured"))?;
+ let client = llm_util::chat_client(&settings)
+ .ok_or_else(|| anyhow::anyhow!("Chat model not configured"))?;
+
+ let sources = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
+ if sources.is_empty() {
+ anyhow::bail!("No data sources mounted");
+ }
+
+ // 各源 schema(引擎直读,保证新鲜;限量防 prompt 爆炸)
+ let mut schema_txt = String::new();
+ for ds in &sources {
+ let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds.id).await?;
+ let cols = crate::query_engine::engine_for(&engine, &conn)?
+ .fetch_schema()
+ .await?;
+ schema_txt.push_str(&format!("\n=== source: {} ===\n", ds.name));
+ let mut current = String::new();
+ for c in cols {
+ let key = format!("{}.{}", c.schema, c.table);
+ if key != current {
+ current = key.clone();
+ schema_txt.push_str(&format!("table {key}:\n"));
+ }
+ schema_txt.push_str(&format!(
+ " {} {}{}\n",
+ c.column,
+ c.data_type,
+ c.comment.map(|x| format!(" -- {x}")).unwrap_or_default()
+ ));
+ if schema_txt.len() > MAX_SCHEMA_CHARS {
+ schema_txt.push_str("(truncated)\n");
+ break;
+ }
+ }
+ }
+
+ // 既有概念(供归并复用,避免重复起名)
+ let existing: Vec<(String,)> = sqlx::query_as(
+ "SELECT e.canonical_name FROM entities e
+ JOIN entity_types t ON t.id = e.type_id
+ WHERE e.kb_id = $1 AND e.merged_into IS NULL AND t.key IN ('metric','dimension')
+ ORDER BY e.canonical_name LIMIT 100",
+ )
+ .bind(kb_id)
+ .fetch_all(&state.pool)
+ .await?;
+ let existing_names: Vec<String> = existing.into_iter().map(|(n,)| n).collect();
+
+ let prompt = format!(
+ "You are building the semantic layer of a BI system. Given database schemas, propose \
+ business concepts a user would ask about, each mapped to a concrete definition.\n\
+ Existing concepts (reuse these names when the meaning matches): {}\n\
+ Schemas:\n{}\n\
+ Reply with ONLY a JSON array, each item:\n\
+ {{\"name\": \"business concept name\", \"kind\": \"metric\"|\"dimension\", \
+ \"source\": \"data source name\", \
+ \"definition\": {{\"table\": \"schema.table\", \"expr\": \"SQL expression\", \
+ \"sql\": \"full SELECT if joins are needed (optional)\", \"unit\": \"optional\"}}, \
+ \"summary\": \"one line: source + expression, shown to reviewers\", \
+ \"rationale\": \"why this mapping, citing column comments\"}}\n\
+ Metrics are aggregatable quantities (use sum/count/avg in expr); dimensions are \
+ group-by columns. Propose at most 12, only well-grounded ones.",
+ if existing_names.is_empty() {
+ "(none)".into()
+ } else {
+ existing_names.join(", ")
+ },
+ schema_txt
+ );
+
+ let reply = client
+ .chat(&[utopia_llm::ChatMessage {
+ role: "user".into(),
+ content: prompt,
+ }])
+ .await?;
+ let json_str = reply
+ .trim()
+ .trim_start_matches("```json")
+ .trim_start_matches("```")
+ .trim_end_matches("```")
+ .trim();
+ let proposals: Vec<serde_json::Value> = serde_json::from_str(json_str)
+ .map_err(|e| anyhow::anyhow!("Mapping proposal parse error: {e}"))?;
+
+ let source_names: Vec<&str> = sources.iter().map(|d| d.name.as_str()).collect();
+ let mut accepted = 0usize;
+ for p in proposals.iter().take(12) {
+ let name = p["name"].as_str().map(str::trim).unwrap_or("");
+ let kind = p["kind"].as_str().unwrap_or("");
+ let source = p["source"].as_str().map(str::trim).unwrap_or("");
+ if name.is_empty()
+ || !matches!(kind, "metric" | "dimension")
+ || !source_names.iter().any(|s| s.eq_ignore_ascii_case(source))
+ {
+ continue;
+ }
+ let type_id: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM entity_types WHERE kb_id = $1 AND key = $2")
+ .bind(kb_id)
+ .bind(kind)
+ .fetch_optional(&state.pool)
+ .await?;
+ let Some((type_id,)) = type_id else { continue };
+
+ // 概念实体:走消解(同名归并;无向量上下文按 v1 兼容归并)
+ let resolved =
+ utopia_store::resolution::resolve_mention(&state.pool, kb_id, type_id, name, None)
+ .await?;
+
+ // 定义带 source + summary(Review 与 prompt 展示都靠 summary)
+ let mut definition = p["definition"].clone();
+ if !definition.is_object() {
+ continue;
+ }
+ definition["source"] = serde_json::json!(source);
+ if let Some(s) = p["summary"].as_str() {
+ definition["summary"] = serde_json::json!(s);
+ }
+
+ let mapped_to: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = 'mapped_to'")
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await?;
+ let Some((mapped_to,)) = mapped_to else {
+ continue;
+ };
+
+ let (fact_id, created) = utopia_store::graph::insert_value_fact(
+ &state.pool,
+ kb_id,
+ resolved.entity_id,
+ mapped_to,
+ &definition,
+ None,
+ None,
+ "day",
+ PROPOSAL_CONFIDENCE,
+ )
+ .await?;
+ if created {
+ accepted += 1;
+ // 证据挂 schema 文档的首个 live chunk(rationale 作 quote)
+ if let Some((chunk_id,)) = sqlx::query_as::<_, (Uuid,)>(
+ "SELECT c.id FROM chunks c JOIN documents d ON d.id = c.document_id
+ WHERE d.kb_id = $1 AND d.external_key LIKE 'datasource:%:schema'
+ AND c.superseded_at IS NULL
+ ORDER BY c.seq LIMIT 1",
+ )
+ .bind(kb_id)
+ .fetch_optional(&state.pool)
+ .await?
+ {
+ let rationale = p["rationale"].as_str().unwrap_or("");
+ utopia_store::graph::add_evidence(
+ &state.pool,
+ fact_id,
+ chunk_id,
+ (!rationale.is_empty()).then_some(rationale),
+ )
+ .await?;
+ }
+ }
+ }
+
+ tracing::info!(%kb_id, proposals = accepted, "映射探索完成,提议已入审核队列");
+ state.emit_review(kb_id);
+ Ok(())
+}
diff --git a/crates/utopia-server/src/pipeline.rs b/crates/utopia-server/src/pipeline.rs
new file mode 100644
index 00000000..9aaae29f
--- /dev/null
+++ b/crates/utopia-server/src/pipeline.rs
@@ -0,0 +1,133 @@
+//! 摄入管道:parse → chunk → 全文索引 → embedding(可选)→ ready。
+//! 每步幂等:重跑会先清掉旧分块与旧索引条目。
+
+use crate::llm_util;
+use crate::state::AppState;
+use uuid::Uuid;
+
+const EMBED_BATCH: usize = 16;
+
+pub async fn process_document(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
+ match run(state, document_id).await {
+ Ok(()) => Ok(()),
+ Err(e) => {
+ let _ =
+ utopia_store::documents::set_failed(&state.pool, document_id, &e.to_string()).await;
+ if let Ok(doc) = utopia_store::documents::get(&state.pool, document_id).await {
+ state.emit_document(doc.kb_id, document_id);
+ }
+ Err(e)
+ }
+ }
+}
+
+async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
+ let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+
+ // 1. 解析(CPU 密集,放 blocking 线程)
+ utopia_store::documents::set_status(&state.pool, document_id, "parsing").await?;
+ state.emit_document(doc.kb_id, document_id);
+ let bytes = state.blob.get(&doc.sha256).await?;
+ let filename = doc.filename.clone();
+ let parsed =
+ tokio::task::spawn_blocking(move || utopia_ingest::parse(&filename, &bytes)).await??;
+ let text_len = parsed.text.chars().count() as i32;
+
+ // 2. 分块 + 入库
+ let pieces = utopia_ingest::chunk_text(&parsed.text);
+ let chunk_pairs =
+ utopia_store::documents::replace_chunks(&state.pool, doc.kb_id, document_id, &pieces)
+ .await?;
+ let chunk_count = chunk_pairs.len() as i32;
+
+ // 3. 全文索引(Tantivy)
+ utopia_store::documents::set_status(&state.pool, document_id, "indexing").await?;
+ state.emit_document(doc.kb_id, document_id);
+ let search = state.search.clone();
+ let kb = doc.kb_id.to_string();
+ let did = document_id.to_string();
+ tokio::task::spawn_blocking(move || search.reindex_document(&kb, &did, &chunk_pairs)).await??;
+
+ // 4. embedding(工作区配置了 embedding 模型才做;没配也算 ready,先享受 BM25 搜索)
+ let kb_row = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
+ let settings = utopia_store::settings::get(&state.pool, kb_row.workspace_id).await?;
+ if let Some(client) = settings.as_ref().and_then(llm_util::embed_client) {
+ utopia_store::documents::set_status(&state.pool, document_id, "embedding").await?;
+ state.emit_document(doc.kb_id, document_id);
+ let pending =
+ utopia_store::documents::chunks_pending_embedding(&state.pool, document_id).await?;
+ for batch in pending.chunks(EMBED_BATCH) {
+ let texts: Vec<String> = batch.iter().map(|(_, t)| t.clone()).collect();
+ let embeddings = client.embed(&texts).await?;
+ if embeddings.len() != batch.len() {
+ anyhow::bail!("Embedding 返回数量不匹配");
+ }
+ let items: Vec<(Uuid, Vec<f32>)> =
+ batch.iter().map(|(id, _)| *id).zip(embeddings).collect();
+ utopia_store::documents::set_embeddings(&state.pool, &items).await?;
+ }
+ }
+
+ utopia_store::documents::set_ready(&state.pool, document_id, text_len, chunk_count).await?;
+
+ // 两段式:索引就绪后,若配置了对话模型则排队图谱抽取(不阻塞可搜可问)
+ if settings.as_ref().is_some_and(|s| s.chat_ready()) {
+ utopia_store::documents::set_graph_status(&state.pool, document_id, "queued").await?;
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "extract_document",
+ serde_json::json!({ "document_id": document_id }),
+ )
+ .await?;
+ }
+ state.emit_document(doc.kb_id, document_id);
+
+ tracing::info!(%document_id, chunks = chunk_count, "文档处理完成");
+ Ok(())
+}
+
+/// 记忆摄入(episodes 快速路径的后半程):新 episode chunk 补 embedding、
+/// 重建全文索引、触发增量抽取(extracted_at 为空的新 chunk 才会被抽)。
+/// 免解析免分块——episode 落库时已是 chunk。
+pub async fn memory_ingest(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
+ let doc = utopia_store::documents::get(&state.pool, document_id).await?;
+ let kb_row = utopia_store::kbs::get(&state.pool, doc.kb_id).await?;
+ let settings = utopia_store::settings::get(&state.pool, kb_row.workspace_id).await?;
+
+ if let Some(client) = settings.as_ref().and_then(llm_util::embed_client) {
+ let pending =
+ utopia_store::documents::chunks_pending_embedding(&state.pool, document_id).await?;
+ for batch in pending.chunks(EMBED_BATCH) {
+ let texts: Vec<String> = batch.iter().map(|(_, t)| t.clone()).collect();
+ let embeddings = client.embed(&texts).await?;
+ if embeddings.len() != batch.len() {
+ anyhow::bail!("Embedding 返回数量不匹配");
+ }
+ let items: Vec<(Uuid, Vec<f32>)> =
+ batch.iter().map(|(id, _)| *id).zip(embeddings).collect();
+ utopia_store::documents::set_embeddings(&state.pool, &items).await?;
+ }
+ }
+
+ let chunks = utopia_store::documents::chunks_full(&state.pool, document_id).await?;
+ let pairs: Vec<(String, String)> = chunks
+ .iter()
+ .map(|c| (c.id.to_string(), c.text.clone()))
+ .collect();
+ let search = state.search.clone();
+ let kb = doc.kb_id.to_string();
+ let did = document_id.to_string();
+ tokio::task::spawn_blocking(move || search.reindex_document(&kb, &did, &pairs)).await??;
+
+ if settings.as_ref().is_some_and(|s| s.chat_ready()) {
+ utopia_store::documents::set_graph_status(&state.pool, document_id, "queued").await?;
+ utopia_store::jobs::enqueue(
+ &state.pool,
+ "extract_document",
+ serde_json::json!({ "document_id": document_id }),
+ )
+ .await?;
+ }
+ state.emit_document(doc.kb_id, document_id);
+ Ok(())
+}
diff --git a/crates/utopia-server/src/query_engine.rs b/crates/utopia-server/src/query_engine.rs
new file mode 100644
index 00000000..01a015bc
--- /dev/null
+++ b/crates/utopia-server/src/query_engine.rs
@@ -0,0 +1,205 @@
+//! 问数查询引擎:trait 接缝(BlobStore 同手法)+ 引擎无关的安全闸。
+//!
+//! 引擎按协议族扩,不按产品名扩:postgres(本文件)→ mysql 线协议族(白捡
+//! TiDB/OceanBase/Doris/StarRocks)→ HTTP 族(ClickHouse、Trino——后者一个顶起
+//! Iceberg/Delta/Hive 整个湖仓生态)。挂载模型与注册表引擎无关,加引擎零迁移。
+//!
+//! 安全闸(纵深防御,不信任模型):
+//! 1. sqlparser 解析:仅放行单条 SELECT/WITH(含 CTE),拒绝 DML/DDL/多语句/SELECT INTO
+//! 2. 强制外包一层 LIMIT(cap+1 探测截断)
+//! 3. 会话级只读 + 语句超时(引擎各自的机制,parser 万一漏网也写不进去)
+//! 4. 结果统一为 JSON Lines(各引擎都有原生 JSON 行输出,也是模型最好消化的格式)
+
+use sqlparser::ast::Statement;
+use sqlparser::dialect::PostgreSqlDialect;
+use sqlparser::parser::Parser;
+use sqlx::postgres::PgPoolOptions;
+use sqlx::Row;
+use std::time::Duration;
+
+/// 行数上限(外包 LIMIT cap+1,第 201 行只用来判断截断)。
+pub const ROW_CAP: usize = 200;
+const STATEMENT_TIMEOUT_SECS: u32 = 10;
+
+pub struct QueryResult {
+ /// 每行一个 JSON 对象文本(键序 = 查询列序)
+ pub rows: Vec<String>,
+ pub truncated: bool,
+}
+
+#[derive(Debug)]
+pub struct SchemaColumn {
+ pub schema: String,
+ pub table: String,
+ pub column: String,
+ pub data_type: String,
+ pub comment: Option<String>,
+}
+
+#[async_trait::async_trait]
+pub trait QueryEngine: Send + Sync {
+ async fn test(&self) -> anyhow::Result<()>;
+ async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>>;
+ /// 执行已过闸的 SELECT。实现自身仍需强制只读会话与超时(纵深防御)。
+ async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult>;
+}
+
+/// 引擎工厂。conn 凭据只在服务端流转。
+pub fn engine_for(engine: &str, conn: &str) -> anyhow::Result<Box<dyn QueryEngine>> {
+ match engine {
+ "postgres" => Ok(Box::new(PostgresEngine {
+ conn: conn.to_string(),
+ })),
+ other => anyhow::bail!("Unsupported engine: {other}"),
+ }
+}
+
+/// 安全闸第 1 层:解析并校验,返回规整后的语句文本。
+pub fn guard_sql(sql: &str) -> anyhow::Result<String> {
+ let cleaned = sql.trim().trim_end_matches(';').trim();
+ if cleaned.is_empty() {
+ anyhow::bail!("Empty SQL");
+ }
+ let statements = Parser::parse_sql(&PostgreSqlDialect {}, cleaned)
+ .map_err(|e| anyhow::anyhow!("SQL parse error: {e}"))?;
+ if statements.len() != 1 {
+ anyhow::bail!("Exactly one statement is allowed");
+ }
+ match &statements[0] {
+ Statement::Query(_) => Ok(cleaned.to_string()),
+ other => anyhow::bail!(
+ "Read-only: only SELECT/WITH queries are allowed (got {})",
+ statement_kind(other)
+ ),
+ }
+}
+
+fn statement_kind(s: &Statement) -> &'static str {
+ match s {
+ Statement::Insert { .. } => "INSERT",
+ Statement::Update { .. } => "UPDATE",
+ Statement::Delete { .. } => "DELETE",
+ Statement::Drop { .. } => "DROP",
+ Statement::CreateTable { .. } | Statement::CreateView { .. } => "CREATE",
+ Statement::AlterTable { .. } => "ALTER",
+ Statement::Truncate { .. } => "TRUNCATE",
+ Statement::Copy { .. } => "COPY",
+ _ => "a non-SELECT statement",
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Postgres 族(顺带覆盖 Greenplum/Timescale 等 PG 兼容系)
+// ---------------------------------------------------------------------------
+
+pub struct PostgresEngine {
+ conn: String,
+}
+
+impl PostgresEngine {
+ async fn pool(&self) -> anyhow::Result<sqlx::PgPool> {
+ Ok(PgPoolOptions::new()
+ .max_connections(1)
+ .acquire_timeout(Duration::from_secs(5))
+ .connect(&self.conn)
+ .await?)
+ }
+}
+
+#[async_trait::async_trait]
+impl QueryEngine for PostgresEngine {
+ async fn test(&self) -> anyhow::Result<()> {
+ let pool = self.pool().await?;
+ sqlx::query("SELECT 1").execute(&pool).await?;
+ pool.close().await;
+ Ok(())
+ }
+
+ async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>> {
+ let pool = self.pool().await?;
+ let rows: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
+ "SELECT c.table_schema, c.table_name, c.column_name,
+ c.data_type, pgd.description
+ FROM information_schema.columns c
+ LEFT JOIN pg_catalog.pg_statio_all_tables st
+ ON st.schemaname = c.table_schema AND st.relname = c.table_name
+ LEFT JOIN pg_catalog.pg_description pgd
+ ON pgd.objoid = st.relid AND pgd.objsubid = c.ordinal_position
+ WHERE c.table_schema NOT IN ('pg_catalog', 'information_schema')
+ ORDER BY c.table_schema, c.table_name, c.ordinal_position",
+ )
+ .fetch_all(&pool)
+ .await?;
+ pool.close().await;
+ Ok(rows
+ .into_iter()
+ .map(|(schema, table, column, data_type, comment)| SchemaColumn {
+ schema,
+ table,
+ column,
+ data_type,
+ comment,
+ })
+ .collect())
+ }
+
+ async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult> {
+ let pool = self.pool().await?;
+ // 纵深防御第 3 层:会话级只读 + 超时(parser 漏网也写不进去、跑不死库)
+ sqlx::query("SET default_transaction_read_only = on")
+ .execute(&pool)
+ .await?;
+ sqlx::query(&format!(
+ "SET statement_timeout = '{STATEMENT_TIMEOUT_SECS}s'"
+ ))
+ .execute(&pool)
+ .await?;
+ // 第 2 层:外包 LIMIT;row_to_json 让 PG 全权处理类型→JSON(文本键序保留列序)
+ let wrapped = format!(
+ "SELECT row_to_json(_q)::text AS _j FROM ( {sql} ) AS _q LIMIT {}",
+ ROW_CAP + 1
+ );
+ let fetched = sqlx::query(&wrapped).fetch_all(&pool).await?;
+ pool.close().await;
+
+ let truncated = fetched.len() > ROW_CAP;
+ let rows = fetched
+ .into_iter()
+ .take(ROW_CAP)
+ .map(|r| r.try_get::<String, _>("_j").unwrap_or_else(|_| "{}".into()))
+ .collect();
+ Ok(QueryResult { rows, truncated })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::guard_sql;
+
+ #[test]
+ fn allows_select_and_cte() {
+ assert!(guard_sql("SELECT region, sum(amount) FROM orders GROUP BY 1").is_ok());
+ assert!(guard_sql("WITH t AS (SELECT 1 AS x) SELECT * FROM t;").is_ok());
+ }
+
+ #[test]
+ fn rejects_writes_and_ddl() {
+ for bad in [
+ "UPDATE orders SET amount = 0",
+ "DELETE FROM orders",
+ "INSERT INTO orders (region) VALUES ('east')",
+ "DROP TABLE orders",
+ "TRUNCATE orders",
+ "CREATE TABLE t (id int)",
+ "ALTER TABLE orders ADD COLUMN x int",
+ ] {
+ assert!(guard_sql(bad).is_err(), "should reject: {bad}");
+ }
+ }
+
+ #[test]
+ fn rejects_multi_statement() {
+ assert!(guard_sql("SELECT 1; DROP TABLE orders").is_err());
+ assert!(guard_sql("").is_err());
+ }
+}
diff --git a/crates/utopia-server/src/retrieval.rs b/crates/utopia-server/src/retrieval.rs
new file mode 100644
index 00000000..16c757ba
--- /dev/null
+++ b/crates/utopia-server/src/retrieval.rs
@@ -0,0 +1,50 @@
+//! 混合检索:BM25(Tantivy)+ 向量(pgvector)→ RRF 融合。
+//! embedding 未配置或请求失败时静默降级为纯 BM25。
+
+use crate::llm_util;
+use crate::state::AppState;
+use utopia_core::models::ChunkView;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+const RECALL_PER_CHANNEL: usize = 24;
+
+pub async fn hybrid(
+ state: &AppState,
+ kb_id: Uuid,
+ workspace_id: Uuid,
+ query: &str,
+ top_k: usize,
+) -> AppResult<Vec<ChunkView>> {
+ let mut lists: Vec<Vec<String>> = Vec::new();
+
+ // BM25
+ let bm25 = state
+ .search
+ .search(&kb_id.to_string(), query, RECALL_PER_CHANNEL)
+ .map_err(utopia_core::AppError::Other)?;
+ lists.push(bm25.into_iter().map(|h| h.chunk_id).collect());
+
+ // 向量(可选通道)
+ let settings = utopia_store::settings::get(&state.pool, workspace_id).await?;
+ if let Some(client) = settings.as_ref().and_then(llm_util::embed_client) {
+ match client.embed(&[query.to_string()]).await {
+ Ok(mut embeddings) if !embeddings.is_empty() => {
+ let ids = utopia_store::documents::vector_search(
+ &state.pool,
+ kb_id,
+ &embeddings.remove(0),
+ RECALL_PER_CHANNEL as i64,
+ )
+ .await?;
+ lists.push(ids.into_iter().map(|id| id.to_string()).collect());
+ }
+ Ok(_) => {}
+ Err(e) => tracing::warn!(error = %e, "查询 embedding 失败,降级为纯 BM25"),
+ }
+ }
+
+ let fused = utopia_search::rrf_fuse(&lists, top_k);
+ let ids: Vec<Uuid> = fused.iter().filter_map(|s| s.parse().ok()).collect();
+ utopia_store::documents::chunks_by_ids(&state.pool, kb_id, &ids).await
+}
diff --git a/crates/utopia-server/src/state.rs b/crates/utopia-server/src/state.rs
new file mode 100644
index 00000000..dd2bcf38
--- /dev/null
+++ b/crates/utopia-server/src/state.rs
@@ -0,0 +1,74 @@
+use sqlx::PgPool;
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::sync::broadcast;
+use utopia_core::config::AppConfig;
+use utopia_search::SearchIndex;
+use uuid::Uuid;
+
+/// 服务内事件(SSE 推送给前端做局部刷新)。
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct AppEvent {
+ pub kb_id: Uuid,
+ /// document = 文档摄入/抽取状态变化;review = 审核队列变化
+ pub kind: &'static str,
+ pub document_id: Option<Uuid>,
+}
+
+#[derive(Clone)]
+pub struct AppState {
+ pub pool: PgPool,
+ pub jwt_secret: String,
+ pub search: Arc<SearchIndex>,
+ /// Charter(内置文档)内存索引:chat 的 search_docs 工具用
+ pub docs: Arc<utopia_search::DocsIndex>,
+ /// 原始文件字节的存取接缝(内容寻址,key = sha256);当前实现为本地磁盘
+ pub blob: Arc<dyn crate::blob::BlobStore>,
+ pub open_registration: bool,
+ /// worker 并发数:调度循环每轮热读——系统设置改动即时生效
+ pub worker_concurrency: Arc<std::sync::atomic::AtomicUsize>,
+ pub events: broadcast::Sender<AppEvent>,
+}
+
+impl AppState {
+ pub fn new(pool: PgPool, cfg: &AppConfig, search: Arc<SearchIndex>) -> Self {
+ let (events, _) = broadcast::channel(256);
+ let data_dir = PathBuf::from(&cfg.data_dir);
+ let blob = Arc::new(crate::blob::LocalBlobStore::new(data_dir.join("files")));
+ Self {
+ pool,
+ jwt_secret: cfg.jwt_secret.clone(),
+ search,
+ docs: Arc::new(crate::docs_corpus::build_index()),
+ blob,
+ open_registration: cfg.open_registration,
+ worker_concurrency: Arc::new(std::sync::atomic::AtomicUsize::new(4)),
+ events,
+ }
+ }
+
+ /// 无订阅者时 send 返回 Err——正常情况,静默忽略。
+ pub fn emit_document(&self, kb_id: Uuid, document_id: Uuid) {
+ let _ = self.events.send(AppEvent {
+ kb_id,
+ kind: "document",
+ document_id: Some(document_id),
+ });
+ }
+
+ pub fn emit_review(&self, kb_id: Uuid) {
+ let _ = self.events.send(AppEvent {
+ kb_id,
+ kind: "review",
+ document_id: None,
+ });
+ }
+
+ pub fn emit_source(&self, kb_id: Uuid) {
+ let _ = self.events.send(AppEvent {
+ kb_id,
+ kind: "source",
+ document_id: None,
+ });
+ }
+}
diff --git a/crates/utopia-store/Cargo.toml b/crates/utopia-store/Cargo.toml
new file mode 100644
index 00000000..ad670f89
--- /dev/null
+++ b/crates/utopia-store/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "utopia-store"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[dependencies]
+utopia-core.workspace = true
+utopia-ingest.workspace = true
+pgvector.workspace = true
+cron.workspace = true
+sqlx.workspace = true
+tokio.workspace = true
+serde_json.workspace = true
+uuid.workspace = true
+chrono.workspace = true
+anyhow.workspace = true
+tracing.workspace = true
+url = "2.5.8"
diff --git a/crates/utopia-store/src/access.rs b/crates/utopia-store/src/access.rs
new file mode 100644
index 00000000..716c5c54
--- /dev/null
+++ b/crates/utopia-store/src/access.rs
@@ -0,0 +1,174 @@
+//! KB 级访问判定 —— 全部 KB 作用域路由的唯一鉴权入口。
+//! 判定链:系统管理员 → 全通;kb_members 矩阵有记录 → 按矩阵角色;
+//! open 库 → 按部署角色(隐形 workspace 的 membership);
+//! restricted 库无记录 → NotFound(不泄露库的存在)。
+
+use sqlx::PgPool;
+use utopia_core::models::{KbMemberView, KnowledgeBase, MyKbInfo, Role, User};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// 用户在某 KB 的有效角色(None = 不可见)。
+pub async fn kb_role(pool: &PgPool, user: &User, kb: &KnowledgeBase) -> AppResult<Option<Role>> {
+ if user.is_admin {
+ return Ok(Some(Role::Owner));
+ }
+ let matrix: Option<(String,)> =
+ sqlx::query_as("SELECT role FROM kb_members WHERE kb_id = $1 AND user_id = $2")
+ .bind(kb.id)
+ .bind(user.id)
+ .fetch_optional(pool)
+ .await?;
+ if let Some((r,)) = matrix {
+ return Ok(Role::parse(&r));
+ }
+ if kb.visibility == "open" {
+ // open 库 = 部署内人人可读;写权限一律来自本库矩阵
+ //(系统管理员在链首已 Owner;部署角色不再向库内映射写权)
+ let ws: Option<(String,)> =
+ sqlx::query_as("SELECT role FROM memberships WHERE workspace_id = $1 AND user_id = $2")
+ .bind(kb.workspace_id)
+ .bind(user.id)
+ .fetch_optional(pool)
+ .await?;
+ return Ok(ws.map(|_| Role::Viewer));
+ }
+ Ok(None)
+}
+
+/// 要求对 KB 至少具备 `min` 角色,返回 KB。
+pub async fn require_kb(
+ pool: &PgPool,
+ user: &User,
+ kb_id: Uuid,
+ min: Role,
+) -> AppResult<KnowledgeBase> {
+ let kb = crate::kbs::get(pool, kb_id).await?;
+ match kb_role(pool, user, &kb).await? {
+ Some(r) if r >= min => Ok(kb),
+ Some(_) => Err(AppError::Forbidden),
+ None => Err(AppError::NotFound),
+ }
+}
+
+// ---------------------------------------------------------------------------
+// KB 成员矩阵
+// ---------------------------------------------------------------------------
+
+pub async fn kb_members(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<KbMemberView>> {
+ let rows: Vec<KbMemberView> = sqlx::query_as(
+ "SELECT m.user_id, u.email, u.display_name, m.role
+ FROM kb_members m JOIN users u ON u.id = m.user_id
+ WHERE m.kb_id = $1 ORDER BY u.display_name",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn set_kb_member(
+ pool: &PgPool,
+ kb_id: Uuid,
+ user_id: Uuid,
+ role: &str,
+ added_by: Option<Uuid>,
+) -> AppResult<()> {
+ if !matches!(role, "viewer" | "editor" | "admin") {
+ return Err(AppError::Validation(
+ "role must be viewer, editor or admin".into(),
+ ));
+ }
+ // 改角色不改写最初邀请人(加入信息记录的是"谁引进来的")
+ sqlx::query(
+ "INSERT INTO kb_members (kb_id, user_id, role, added_by) VALUES ($1, $2, $3, $4)
+ ON CONFLICT (kb_id, user_id)
+ DO UPDATE SET role = $3, added_by = COALESCE(kb_members.added_by, $4)",
+ )
+ .bind(kb_id)
+ .bind(user_id)
+ .bind(role)
+ .bind(added_by)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 我在各可见库的成员信息 + 概览统计(账户层 Knowledge bases 页)。
+pub async fn my_kb_infos(
+ pool: &PgPool,
+ kb_ids: &[Uuid],
+ user_id: Uuid,
+) -> AppResult<Vec<MyKbInfo>> {
+ let rows: Vec<MyKbInfo> = sqlx::query_as(
+ "SELECT k.id AS kb_id,
+ m.role AS member_role,
+ m.created_at AS joined_at,
+ inviter.display_name AS added_by_name,
+ (SELECT count(*) FROM documents d WHERE d.kb_id = k.id) AS doc_count,
+ (SELECT count(*) FROM kb_members mm WHERE mm.kb_id = k.id) AS member_count
+ FROM knowledge_bases k
+ LEFT JOIN kb_members m ON m.kb_id = k.id AND m.user_id = $2
+ LEFT JOIN users inviter ON inviter.id = m.added_by
+ WHERE k.id = ANY($1)",
+ )
+ .bind(kb_ids)
+ .bind(user_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn remove_kb_member(pool: &PgPool, kb_id: Uuid, user_id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM kb_members WHERE kb_id = $1 AND user_id = $2")
+ .bind(kb_id)
+ .bind(user_id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// 部署配置
+// ---------------------------------------------------------------------------
+
+pub async fn open_registration(pool: &PgPool) -> AppResult<bool> {
+ let row: Option<(bool,)> =
+ sqlx::query_as("SELECT open_registration FROM deployment_settings LIMIT 1")
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(v,)| v).unwrap_or(true))
+}
+
+pub async fn set_open_registration(pool: &PgPool, value: bool) -> AppResult<()> {
+ sqlx::query("UPDATE deployment_settings SET open_registration = $1")
+ .bind(value)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 任务 worker 并发数(系统设置可改,改动即时生效——见 jobs::run_worker)。
+pub async fn worker_concurrency(pool: &PgPool) -> AppResult<i32> {
+ let row: Option<(i32,)> =
+ sqlx::query_as("SELECT worker_concurrency FROM deployment_settings LIMIT 1")
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(v,)| v).unwrap_or(4))
+}
+
+pub async fn set_worker_concurrency(pool: &PgPool, value: i32) -> AppResult<()> {
+ if !(1..=32).contains(&value) {
+ return Err(AppError::Validation(
+ "worker_concurrency must be between 1 and 32".into(),
+ ));
+ }
+ sqlx::query("UPDATE deployment_settings SET worker_concurrency = $1")
+ .bind(value)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
diff --git a/crates/utopia-store/src/accounts.rs b/crates/utopia-store/src/accounts.rs
new file mode 100644
index 00000000..a7c107e3
--- /dev/null
+++ b/crates/utopia-store/src/accounts.rs
@@ -0,0 +1,197 @@
+use sqlx::PgPool;
+use utopia_core::models::{Role, User, Workspace};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// 注册(单租户模型):
+/// - 部署内还没有组织 → 首个用户:创建组织 + 默认工作区,成为 owner + 系统管理员;
+/// - 已有组织 → 加入该组织,并以 viewer 进入默认(最早的)工作区;
+/// `open_registration = false` 时拒绝(仅引导首用户例外)。
+pub async fn register(
+ pool: &PgPool,
+ email: &str,
+ password_hash: &str,
+ display_name: &str,
+ org_name: Option<&str>,
+ open_registration: bool,
+) -> AppResult<(User, Workspace)> {
+ let mut tx = pool.begin().await?;
+
+ let existing_org: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM organizations ORDER BY created_at LIMIT 1")
+ .fetch_optional(&mut *tx)
+ .await?;
+
+ let result = match existing_org {
+ None => {
+ // 首个用户:引导整个部署
+ let org_id = Uuid::now_v7();
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, $2)")
+ .bind(org_id)
+ .bind(org_name.unwrap_or("Default Organization"))
+ .execute(&mut *tx)
+ .await?;
+
+ let user =
+ insert_user(&mut tx, org_id, email, password_hash, display_name, true).await?;
+
+ let workspace: Workspace = sqlx::query_as(
+ "INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3) RETURNING *",
+ )
+ .bind(Uuid::now_v7())
+ .bind(org_id)
+ .bind("Default Workspace")
+ .fetch_one(&mut *tx)
+ .await?;
+
+ insert_membership(&mut tx, user.id, workspace.id, Role::Owner).await?;
+ (user, workspace)
+ }
+ Some((org_id,)) => {
+ if !open_registration {
+ return Err(AppError::Validation(
+ "Registration is closed for this deployment. Contact your administrator."
+ .into(),
+ ));
+ }
+ let user =
+ insert_user(&mut tx, org_id, email, password_hash, display_name, false).await?;
+
+ // 加入默认(最早的)工作区;异常情况下组织没有工作区则补建一个
+ let default_ws: Option<Workspace> = sqlx::query_as(
+ "SELECT * FROM workspaces WHERE org_id = $1 ORDER BY created_at LIMIT 1",
+ )
+ .bind(org_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+
+ match default_ws {
+ Some(ws) => {
+ insert_membership(&mut tx, user.id, ws.id, Role::Viewer).await?;
+ (user, ws)
+ }
+ None => {
+ let ws: Workspace = sqlx::query_as(
+ "INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3) RETURNING *",
+ )
+ .bind(Uuid::now_v7())
+ .bind(org_id)
+ .bind("Default Workspace")
+ .fetch_one(&mut *tx)
+ .await?;
+ insert_membership(&mut tx, user.id, ws.id, Role::Owner).await?;
+ (user, ws)
+ }
+ }
+ }
+ };
+
+ tx.commit().await?;
+ Ok(result)
+}
+
+async fn insert_user(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ org_id: Uuid,
+ email: &str,
+ password_hash: &str,
+ display_name: &str,
+ is_admin: bool,
+) -> AppResult<User> {
+ sqlx::query_as(
+ "INSERT INTO users (id, org_id, email, password_hash, display_name, is_admin)
+ VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
+ )
+ .bind(Uuid::now_v7())
+ .bind(org_id)
+ .bind(email)
+ .bind(password_hash)
+ .bind(display_name)
+ .bind(is_admin)
+ .fetch_one(&mut **tx)
+ .await
+ .map_err(|e| match &e {
+ sqlx::Error::Database(db) if db.is_unique_violation() => {
+ AppError::Conflict("This email is already registered".into())
+ }
+ _ => AppError::Db(e),
+ })
+}
+
+async fn insert_membership(
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ user_id: Uuid,
+ workspace_id: Uuid,
+ role: Role,
+) -> AppResult<()> {
+ sqlx::query("INSERT INTO memberships (user_id, workspace_id, role) VALUES ($1, $2, $3)")
+ .bind(user_id)
+ .bind(workspace_id)
+ .bind(role.as_str())
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
+
+/// 管理员代开账号:加入既有组织 + 默认工作区,部署角色由管理员指定。
+pub async fn admin_create_user(
+ pool: &PgPool,
+ email: &str,
+ password_hash: &str,
+ display_name: &str,
+ role: Role,
+) -> AppResult<User> {
+ let mut tx = pool.begin().await?;
+ let (org_id,): (Uuid,) =
+ sqlx::query_as("SELECT id FROM organizations ORDER BY created_at LIMIT 1")
+ .fetch_optional(&mut *tx)
+ .await?
+ .ok_or_else(|| AppError::Validation("Deployment not bootstrapped yet".into()))?;
+ let user = insert_user(&mut tx, org_id, email, password_hash, display_name, false).await?;
+ let ws: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM workspaces WHERE org_id = $1 ORDER BY created_at LIMIT 1")
+ .bind(org_id)
+ .fetch_optional(&mut *tx)
+ .await?;
+ if let Some((ws_id,)) = ws {
+ insert_membership(&mut tx, user.id, ws_id, role).await?;
+ }
+ tx.commit().await?;
+ Ok(user)
+}
+
+pub async fn find_user_by_email(pool: &PgPool, email: &str) -> AppResult<Option<User>> {
+ let user = sqlx::query_as("SELECT * FROM users WHERE email = $1")
+ .bind(email)
+ .fetch_optional(pool)
+ .await?;
+ Ok(user)
+}
+
+pub async fn find_user_by_id(pool: &PgPool, id: Uuid) -> AppResult<Option<User>> {
+ let user = sqlx::query_as("SELECT * FROM users WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(user)
+}
+
+/// 改显示名(个人资料页)。
+pub async fn update_display_name(pool: &PgPool, id: Uuid, display_name: &str) -> AppResult<User> {
+ sqlx::query_as("UPDATE users SET display_name = $2 WHERE id = $1 RETURNING *")
+ .bind(id)
+ .bind(display_name)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+/// 改密码(server 层已验旧密并完成哈希)。
+pub async fn update_password(pool: &PgPool, id: Uuid, password_hash: &str) -> AppResult<()> {
+ sqlx::query("UPDATE users SET password_hash = $2 WHERE id = $1")
+ .bind(id)
+ .bind(password_hash)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
diff --git a/crates/utopia-store/src/audit.rs b/crates/utopia-store/src/audit.rs
new file mode 100644
index 00000000..ef209e73
--- /dev/null
+++ b/crates/utopia-store/src/audit.rs
@@ -0,0 +1,96 @@
+//! 审计日志:谁在何时对什么做了什么。纯审计——只记录与展示,不承载回滚等衍生功能。
+//! 记录失败绝不影响业务操作(调用方一律 `let _ =`)。
+
+use sqlx::PgPool;
+use utopia_core::models::AuditEventView;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+pub async fn record(
+ pool: &PgPool,
+ kb_id: Option<Uuid>,
+ actor_id: Uuid,
+ action: &str,
+ target_kind: &str,
+ target_id: Option<Uuid>,
+ detail: serde_json::Value,
+) -> AppResult<()> {
+ record_opt(
+ pool,
+ kb_id,
+ Some(actor_id),
+ action,
+ target_kind,
+ target_id,
+ detail,
+ )
+ .await
+}
+
+/// 无人类操作者的系统事件(如 AI 裁决自动合并)走这里:actor 为 NULL。
+pub async fn record_opt(
+ pool: &PgPool,
+ kb_id: Option<Uuid>,
+ actor_id: Option<Uuid>,
+ action: &str,
+ target_kind: &str,
+ target_id: Option<Uuid>,
+ detail: serde_json::Value,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO audit_events (id, kb_id, actor_id, action, target_kind, target_id, detail)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(actor_id)
+ .bind(action)
+ .bind(target_kind)
+ .bind(target_id)
+ .bind(detail)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 审核决策台账:只取 review 域的动作(review./fact./conflict./merge.),服务端分页。
+pub async fn review_history(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<(Vec<AuditEventView>, i64)> {
+ const COND: &str = "e.kb_id = $1 AND (e.action LIKE 'review.%' OR e.action LIKE 'fact.%'
+ OR e.action LIKE 'conflict.%' OR e.action LIKE 'merge.%')";
+ let rows: Vec<AuditEventView> = sqlx::query_as(&format!(
+ "SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
+ u.display_name AS actor_name, e.created_at
+ FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
+ WHERE {COND} ORDER BY e.created_at DESC LIMIT $2 OFFSET $3"
+ ))
+ .bind(kb_id)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?;
+ let (total,): (i64,) =
+ sqlx::query_as(&format!("SELECT count(*) FROM audit_events e WHERE {COND}"))
+ .bind(kb_id)
+ .fetch_one(pool)
+ .await?;
+ Ok((rows, total))
+}
+
+pub async fn list_for_kb(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<AuditEventView>> {
+ let rows: Vec<AuditEventView> = sqlx::query_as(
+ "SELECT e.id, e.action, e.target_kind, e.target_id, e.detail,
+ u.display_name AS actor_name, e.created_at
+ FROM audit_events e LEFT JOIN users u ON u.id = e.actor_id
+ WHERE e.kb_id = $1 ORDER BY e.created_at DESC LIMIT $2",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
diff --git a/crates/utopia-store/src/conversations.rs b/crates/utopia-store/src/conversations.rs
new file mode 100644
index 00000000..31dfd933
--- /dev/null
+++ b/crates/utopia-store/src/conversations.rs
@@ -0,0 +1,134 @@
+//! Chat 会话持久化:对话/消息仓储。轨迹(steps)与引用(sources)随
+//! assistant 消息落库,历史回放与实时流共用同一数据形状。
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use utopia_core::models::{ConversationMessage, ConversationView};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+pub async fn create(pool: &PgPool, kb_id: Uuid, user_id: Uuid, title: &str) -> AppResult<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query("INSERT INTO conversations (id, kb_id, user_id, title) VALUES ($1, $2, $3, $4)")
+ .bind(id)
+ .bind(kb_id)
+ .bind(user_id)
+ .bind(title.chars().take(80).collect::<String>())
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 本人在本 KB 的会话列表(新→旧)。
+pub async fn list(pool: &PgPool, kb_id: Uuid, user_id: Uuid) -> AppResult<Vec<ConversationView>> {
+ let rows: Vec<ConversationView> = sqlx::query_as(
+ "SELECT id, title, created_at, updated_at,
+ (SELECT count(*) FROM conversation_messages m
+ WHERE m.conversation_id = c.id) AS message_count
+ FROM conversations c
+ WHERE kb_id = $1 AND user_id = $2
+ ORDER BY updated_at DESC
+ LIMIT 100",
+ )
+ .bind(kb_id)
+ .bind(user_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 归属校验:会话必须属于本 KB 本人。
+pub async fn require_owned(
+ pool: &PgPool,
+ kb_id: Uuid,
+ user_id: Uuid,
+ conversation_id: Uuid,
+) -> AppResult<()> {
+ let found: Option<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM conversations WHERE id = $1 AND kb_id = $2 AND user_id = $3",
+ )
+ .bind(conversation_id)
+ .bind(kb_id)
+ .bind(user_id)
+ .fetch_optional(pool)
+ .await?;
+ found.map(|_| ()).ok_or(AppError::NotFound)
+}
+
+pub async fn messages(pool: &PgPool, conversation_id: Uuid) -> AppResult<Vec<ConversationMessage>> {
+ let rows: Vec<ConversationMessage> = sqlx::query_as(
+ "SELECT id, role, content, steps, sources, created_at
+ FROM conversation_messages WHERE conversation_id = $1 ORDER BY created_at",
+ )
+ .bind(conversation_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 服务端拼上下文用:最近 n 条的 (role, content),按时间正序。
+pub async fn recent_context(
+ pool: &PgPool,
+ conversation_id: Uuid,
+ n: i64,
+) -> AppResult<Vec<(String, String)>> {
+ let mut rows: Vec<(String, String, DateTime<Utc>)> = sqlx::query_as(
+ "SELECT role, content, created_at FROM conversation_messages
+ WHERE conversation_id = $1 ORDER BY created_at DESC LIMIT $2",
+ )
+ .bind(conversation_id)
+ .bind(n)
+ .fetch_all(pool)
+ .await?;
+ rows.reverse();
+ Ok(rows.into_iter().map(|(r, c, _)| (r, c)).collect())
+}
+
+pub async fn append_message(
+ pool: &PgPool,
+ conversation_id: Uuid,
+ role: &str,
+ content: &str,
+ steps: &serde_json::Value,
+ sources: &serde_json::Value,
+) -> AppResult<Uuid> {
+ let id = Uuid::now_v7();
+ let mut tx = pool.begin().await?;
+ sqlx::query(
+ "INSERT INTO conversation_messages (id, conversation_id, role, content, steps, sources)
+ VALUES ($1, $2, $3, $4, $5, $6)",
+ )
+ .bind(id)
+ .bind(conversation_id)
+ .bind(role)
+ .bind(content)
+ .bind(steps)
+ .bind(sources)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE conversations SET updated_at = now() WHERE id = $1")
+ .bind(conversation_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(id)
+}
+
+pub async fn delete(
+ pool: &PgPool,
+ kb_id: Uuid,
+ user_id: Uuid,
+ conversation_id: Uuid,
+) -> AppResult<()> {
+ let res =
+ sqlx::query("DELETE FROM conversations WHERE id = $1 AND kb_id = $2 AND user_id = $3")
+ .bind(conversation_id)
+ .bind(kb_id)
+ .bind(user_id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/datasources.rs b/crates/utopia-store/src/datasources.rs
new file mode 100644
index 00000000..533fd538
--- /dev/null
+++ b/crates/utopia-store/src/datasources.rs
@@ -0,0 +1,185 @@
+//! 问数数据源:系统层注册(凭据集中、跨 KB 复用)+ 知识库层挂载(权限跟 KB 走)。
+//! 查询执行时的安全闸(只读会话、SQL 解析白名单、LIMIT/超时)在 server 侧。
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use utopia_core::models::DataSourceView;
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// data_sources 的行投影,list 与 mounted 共用。
+type DataSourceRow = (
+ Uuid,
+ String,
+ String,
+ String,
+ DateTime<Utc>,
+ Option<DateTime<Utc>>,
+ Option<bool>,
+);
+
+/// 连接串 → 无凭据摘要(host:port/db)。解析失败给占位符,绝不回显原串。
+pub fn conn_summary(conn: &str) -> String {
+ url::Url::parse(conn)
+ .ok()
+ .map(|u| {
+ format!(
+ "{}:{}{}",
+ u.host_str().unwrap_or("?"),
+ u.port()
+ .map(|p| p.to_string())
+ .unwrap_or_else(|| "5432".into()),
+ u.path()
+ )
+ })
+ .unwrap_or_else(|| "(unparsed)".into())
+}
+
+pub async fn list(pool: &PgPool) -> AppResult<Vec<DataSourceView>> {
+ let rows: Vec<DataSourceRow> = sqlx::query_as(
+ "SELECT id, name, engine, conn_string, created_at, last_test_at, last_test_ok
+ FROM data_sources ORDER BY name",
+ )
+ .fetch_all(pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .map(
+ |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView {
+ id,
+ name,
+ engine,
+ summary: conn_summary(&conn),
+ created_at,
+ last_test_at,
+ last_test_ok,
+ },
+ )
+ .collect())
+}
+
+pub async fn create(
+ pool: &PgPool,
+ name: &str,
+ engine: &str,
+ conn_string: &str,
+ created_by: Uuid,
+) -> AppResult<Uuid> {
+ if name.trim().is_empty() {
+ return Err(AppError::Validation("Data source name is required".into()));
+ }
+ if engine != "postgres" {
+ return Err(AppError::Validation(
+ "Only the postgres engine is supported for now".into(),
+ ));
+ }
+ if !conn_string.starts_with("postgres://") && !conn_string.starts_with("postgresql://") {
+ return Err(AppError::Validation(
+ "Connection string must start with postgres://".into(),
+ ));
+ }
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO data_sources (id, name, engine, conn_string, created_by)
+ VALUES ($1, $2, $3, $4, $5)",
+ )
+ .bind(id)
+ .bind(name.trim())
+ .bind(engine)
+ .bind(conn_string.trim())
+ .bind(created_by)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM data_sources WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 连接串只在服务端内部流转(测试连接/查询执行)。
+pub async fn conn_string(pool: &PgPool, id: Uuid) -> AppResult<String> {
+ let row: Option<(String,)> =
+ sqlx::query_as("SELECT conn_string FROM data_sources WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?;
+ row.map(|(c,)| c).ok_or(AppError::NotFound)
+}
+
+pub async fn record_test(pool: &PgPool, id: Uuid, ok: bool) -> AppResult<()> {
+ sqlx::query("UPDATE data_sources SET last_test_at = now(), last_test_ok = $2 WHERE id = $1")
+ .bind(id)
+ .bind(ok)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// KB 挂载
+// ---------------------------------------------------------------------------
+
+pub async fn mount(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO kb_data_sources (kb_id, data_source_id) VALUES ($1, $2)
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(kb_id)
+ .bind(data_source_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn unmount(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<()> {
+ sqlx::query("DELETE FROM kb_data_sources WHERE kb_id = $1 AND data_source_id = $2")
+ .bind(kb_id)
+ .bind(data_source_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn mounted(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<DataSourceView>> {
+ let rows: Vec<DataSourceRow> = sqlx::query_as(
+ "SELECT d.id, d.name, d.engine, d.conn_string, d.created_at,
+ d.last_test_at, d.last_test_ok
+ FROM kb_data_sources m JOIN data_sources d ON d.id = m.data_source_id
+ WHERE m.kb_id = $1 ORDER BY d.name",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .map(
+ |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView {
+ id,
+ name,
+ engine,
+ summary: conn_summary(&conn),
+ created_at,
+ last_test_at,
+ last_test_ok,
+ },
+ )
+ .collect())
+}
+
+/// (engine, conn_string):查询执行/测试/拉 schema 用(凭据不出服务端)。
+pub async fn engine_and_conn(pool: &PgPool, id: Uuid) -> AppResult<(String, String)> {
+ let row: Option<(String, String)> =
+ sqlx::query_as("SELECT engine, conn_string FROM data_sources WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?;
+ row.ok_or(AppError::NotFound)
+}
diff --git a/crates/utopia-store/src/db.rs b/crates/utopia-store/src/db.rs
new file mode 100644
index 00000000..f849a891
--- /dev/null
+++ b/crates/utopia-store/src/db.rs
@@ -0,0 +1,15 @@
+use sqlx::postgres::PgPoolOptions;
+use sqlx::PgPool;
+
+pub async fn connect(database_url: &str) -> anyhow::Result<PgPool> {
+ let pool = PgPoolOptions::new()
+ .max_connections(10)
+ .connect(database_url)
+ .await?;
+ Ok(pool)
+}
+
+pub async fn migrate(pool: &PgPool) -> anyhow::Result<()> {
+ sqlx::migrate!("../../migrations").run(pool).await?;
+ Ok(())
+}
diff --git a/crates/utopia-store/src/documents.rs b/crates/utopia-store/src/documents.rs
new file mode 100644
index 00000000..0b9ba8aa
--- /dev/null
+++ b/crates/utopia-store/src/documents.rs
@@ -0,0 +1,523 @@
+use pgvector::Vector;
+use sqlx::PgPool;
+use utopia_core::models::{ChunkView, Document};
+use utopia_core::{AppError, AppResult};
+use utopia_ingest::ChunkPiece;
+use uuid::Uuid;
+
+#[allow(clippy::too_many_arguments)]
+pub async fn create(
+ pool: &PgPool,
+ kb_id: Uuid,
+ filename: &str,
+ mime: &str,
+ size_bytes: i64,
+ sha256: &str,
+ source_id: Option<Uuid>,
+ doc_time: Option<chrono::DateTime<chrono::Utc>>,
+ external_key: Option<&str>,
+) -> AppResult<Document> {
+ sqlx::query_as(
+ "INSERT INTO documents (id, kb_id, filename, mime, size_bytes, sha256, source_id,
+ doc_time, doc_time_source, external_key)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, COALESCE($8, now()), $9, $10) RETURNING *",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(filename)
+ .bind(mime)
+ .bind(size_bytes)
+ .bind(sha256)
+ .bind(source_id)
+ .bind(doc_time)
+ .bind(if doc_time.is_some() {
+ "source"
+ } else {
+ "upload_time"
+ })
+ .bind(external_key)
+ .fetch_one(pool)
+ .await
+ .map_err(|e| match &e {
+ sqlx::Error::Database(db) if db.is_unique_violation() => AppError::Conflict(format!(
+ "File already exists (identical content): {filename}"
+ )),
+ _ => AppError::Db(e),
+ })
+}
+
+pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Document>> {
+ let rows = sqlx::query_as("SELECT * FROM documents WHERE kb_id = $1 ORDER BY created_at DESC")
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Document> {
+ sqlx::query_as("SELECT * FROM documents WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+/// 按来源内逻辑身份查文档(同步三路判定用)。
+pub async fn find_by_external_key(
+ pool: &PgPool,
+ source_id: Uuid,
+ external_key: &str,
+) -> AppResult<Option<Document>> {
+ Ok(
+ sqlx::query_as("SELECT * FROM documents WHERE source_id = $1 AND external_key = $2")
+ .bind(source_id)
+ .bind(external_key)
+ .fetch_optional(pool)
+ .await?,
+ )
+}
+
+/// 按来源 + 内容哈希查文档(改名/移动识别用)。
+pub async fn find_by_source_sha(
+ pool: &PgPool,
+ source_id: Uuid,
+ sha256: &str,
+) -> AppResult<Option<Document>> {
+ Ok(
+ sqlx::query_as("SELECT * FROM documents WHERE source_id = $1 AND sha256 = $2 LIMIT 1")
+ .bind(source_id)
+ .bind(sha256)
+ .fetch_optional(pool)
+ .await?,
+ )
+}
+
+/// 迁移前的历史文档(无 external_key)按文件名认领——0008 之前建的行的一次性兜底。
+pub async fn find_legacy_by_filename(
+ pool: &PgPool,
+ source_id: Uuid,
+ filename: &str,
+) -> AppResult<Option<Document>> {
+ Ok(sqlx::query_as(
+ "SELECT * FROM documents
+ WHERE source_id = $1 AND external_key IS NULL AND filename = $2 LIMIT 1",
+ )
+ .bind(source_id)
+ .bind(filename)
+ .fetch_optional(pool)
+ .await?)
+}
+
+/// 给历史文档补上逻辑身份。
+pub async fn adopt_external_key(pool: &PgPool, id: Uuid, external_key: &str) -> AppResult<()> {
+ sqlx::query("UPDATE documents SET external_key = $2, updated_at = now() WHERE id = $1")
+ .bind(id)
+ .bind(external_key)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 变更:原地替换文档内容(新 sha),状态回 pending 待重跑管道。
+#[allow(clippy::too_many_arguments)]
+pub async fn replace_content(
+ pool: &PgPool,
+ id: Uuid,
+ filename: &str,
+ mime: &str,
+ size_bytes: i64,
+ sha256: &str,
+ doc_time: Option<chrono::DateTime<chrono::Utc>>,
+) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE documents SET filename = $2, mime = $3, size_bytes = $4, sha256 = $5,
+ doc_time = COALESCE($6, doc_time),
+ status = 'pending', graph_status = 'none', error = NULL,
+ missing_since = NULL, updated_at = now()
+ WHERE id = $1",
+ )
+ .bind(id)
+ .bind(filename)
+ .bind(mime)
+ .bind(size_bytes)
+ .bind(sha256)
+ .bind(doc_time)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 移动/改名:同内容换了路径,只更新身份,不重跑管道。
+pub async fn update_location(
+ pool: &PgPool,
+ id: Uuid,
+ filename: &str,
+ external_key: &str,
+) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE documents SET filename = $2, external_key = $3, missing_since = NULL,
+ updated_at = now() WHERE id = $1",
+ )
+ .bind(id)
+ .bind(filename)
+ .bind(external_key)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 记录一个内容版本(版本号自增)。
+pub async fn record_version(
+ pool: &PgPool,
+ document_id: Uuid,
+ sha256: &str,
+ size_bytes: i64,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO document_versions (id, document_id, version, sha256, size_bytes)
+ VALUES ($1, $2,
+ (SELECT coalesce(max(version), 0) + 1 FROM document_versions WHERE document_id = $2),
+ $3, $4)",
+ )
+ .bind(Uuid::now_v7())
+ .bind(document_id)
+ .bind(sha256)
+ .bind(size_bytes)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 全集对账(仅适用于能看到来源完整现状的类型,如 url 的配置列表):
+/// 本轮见到的 key 清除 missing 标记,没见到的打上标记。
+/// rss(滑动窗口)与 custom 的增量响应(?since=)不可用此函数——缺席≠删除。
+pub async fn reconcile_missing(
+ pool: &PgPool,
+ source_id: Uuid,
+ seen_keys: &[String],
+) -> AppResult<()> {
+ clear_missing_keys(pool, source_id, seen_keys).await?;
+ sqlx::query(
+ "UPDATE documents SET missing_since = now(), updated_at = now()
+ WHERE source_id = $1 AND missing_since IS NULL
+ AND external_key IS NOT NULL AND NOT (external_key = ANY($2))",
+ )
+ .bind(source_id)
+ .bind(seen_keys)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 本轮出现的条目清除 missing 标记(条目失而复得)。
+pub async fn clear_missing_keys(pool: &PgPool, source_id: Uuid, keys: &[String]) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE documents SET missing_since = NULL, updated_at = now()
+ WHERE source_id = $1 AND missing_since IS NOT NULL AND external_key = ANY($2)",
+ )
+ .bind(source_id)
+ .bind(keys)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 显式墓碑(custom 响应的 deleted[]):来源声明删除才打标,绝不因缺席推断。
+pub async fn mark_missing_keys(pool: &PgPool, source_id: Uuid, keys: &[String]) -> AppResult<u64> {
+ let res = sqlx::query(
+ "UPDATE documents SET missing_since = now(), updated_at = now()
+ WHERE source_id = $1 AND missing_since IS NULL AND external_key = ANY($2)",
+ )
+ .bind(source_id)
+ .bind(keys)
+ .execute(pool)
+ .await?;
+ Ok(res.rows_affected())
+}
+
+/// 该来源下所有已标记 missing 的文档 id(批量清理用)。
+pub async fn list_missing(pool: &PgPool, source_id: Uuid) -> AppResult<Vec<Uuid>> {
+ let rows: Vec<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM documents WHERE source_id = $1 AND missing_since IS NOT NULL",
+ )
+ .bind(source_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|(id,)| id).collect())
+}
+
+pub async fn set_status(pool: &PgPool, id: Uuid, status: &str) -> AppResult<()> {
+ sqlx::query("UPDATE documents SET status = $2, error = NULL, updated_at = now() WHERE id = $1")
+ .bind(id)
+ .bind(status)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn set_failed(pool: &PgPool, id: Uuid, error: &str) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE documents SET status = 'failed', error = $2, updated_at = now() WHERE id = $1",
+ )
+ .bind(id)
+ .bind(error)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn set_ready(pool: &PgPool, id: Uuid, text_len: i32, chunk_count: i32) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE documents SET status = 'ready', error = NULL, text_len = $2, chunk_count = $3,
+ updated_at = now() WHERE id = $1",
+ )
+ .bind(id)
+ .bind(text_len)
+ .bind(chunk_count)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM documents WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 重建文档分块(事务内,幂等)。返回 (chunk_id, text) 供全文索引。
+///
+/// 认领式增量:新块先按文本内容在现行块里找同款——找到即"认领"(原行只更新
+/// 序号/偏移/版本,身份延续:embedding、extracted_at、证据链接全部原地保鲜,
+/// 未变段落不重抽也不会被误标"证据过期");没同款的才新建。落选的旧块软删除
+/// (superseded_at 打标)而非物理删除——fact_evidence 引用不断链、旧版可回放,
+/// embedding 清空(旧版不参与检索,向量是存储大头不留)。
+pub async fn replace_chunks(
+ pool: &PgPool,
+ kb_id: Uuid,
+ document_id: Uuid,
+ pieces: &[ChunkPiece],
+) -> AppResult<Vec<(String, String)>> {
+ let mut tx = pool.begin().await?;
+ let (version,): (i32,) = sqlx::query_as(
+ "SELECT COALESCE(MAX(version), 1) FROM document_versions WHERE document_id = $1",
+ )
+ .bind(document_id)
+ .fetch_one(&mut *tx)
+ .await?;
+
+ // 认领池:现行块按文本分组(同文重复块按多重集配对,各认领各的)
+ let old: Vec<(Uuid, String)> = sqlx::query_as(
+ "SELECT id, text FROM chunks WHERE document_id = $1 AND superseded_at IS NULL",
+ )
+ .bind(document_id)
+ .fetch_all(&mut *tx)
+ .await?;
+ let mut claim_pool: std::collections::HashMap<String, Vec<Uuid>> =
+ std::collections::HashMap::new();
+ for (id, text) in old {
+ claim_pool.entry(text).or_default().push(id);
+ }
+
+ // 第一阶段:认领(原行更新)与待插清单——新块必须等软删跑完再插,
+ // 否则"落选"判定会把本轮刚插入的新块一并软删
+ let mut adopted: Vec<Uuid> = Vec::new();
+ let mut to_insert: Vec<(Uuid, &ChunkPiece)> = Vec::new();
+ let mut out = Vec::with_capacity(pieces.len());
+ for piece in pieces {
+ let claimed = claim_pool.get_mut(&piece.text).and_then(|ids| ids.pop());
+ if let Some(id) = claimed {
+ sqlx::query(
+ "UPDATE chunks SET seq = $2, char_start = $3, char_end = $4, doc_version = $5
+ WHERE id = $1",
+ )
+ .bind(id)
+ .bind(piece.seq)
+ .bind(piece.char_start)
+ .bind(piece.char_end)
+ .bind(version)
+ .execute(&mut *tx)
+ .await?;
+ adopted.push(id);
+ out.push((id.to_string(), piece.text.clone()));
+ } else {
+ let id = Uuid::now_v7();
+ to_insert.push((id, piece));
+ out.push((id.to_string(), piece.text.clone()));
+ }
+ }
+
+ // 第二阶段:落选旧块(新版里没有同款文本)→ 软删
+ sqlx::query(
+ "UPDATE chunks SET superseded_at = now(), embedding = NULL
+ WHERE document_id = $1 AND superseded_at IS NULL AND NOT (id = ANY($2))",
+ )
+ .bind(document_id)
+ .bind(&adopted)
+ .execute(&mut *tx)
+ .await?;
+
+ // 第三阶段:插入新块
+ for (id, piece) in to_insert {
+ sqlx::query(
+ "INSERT INTO chunks
+ (id, kb_id, document_id, seq, text, char_start, char_end, doc_version)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(document_id)
+ .bind(piece.seq)
+ .bind(&piece.text)
+ .bind(piece.char_start)
+ .bind(piece.char_end)
+ .bind(version)
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ Ok(out)
+}
+
+/// 抽取完成一个分块即打标(认领的块携带标记跳过重抽;也让中断的抽取可续跑)。
+pub async fn mark_chunk_extracted(pool: &PgPool, chunk_id: Uuid) -> AppResult<()> {
+ sqlx::query("UPDATE chunks SET extracted_at = now() WHERE id = $1")
+ .bind(chunk_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 清除文档现行分块的抽取标记(手动 Extract = 强制全量重抽)。
+pub async fn clear_extraction_marks(pool: &PgPool, document_id: Uuid) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE chunks SET extracted_at = NULL
+ WHERE document_id = $1 AND superseded_at IS NULL",
+ )
+ .bind(document_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 文档查看器:全部分块(按顺序)。
+pub async fn chunks_full(
+ pool: &PgPool,
+ document_id: Uuid,
+) -> AppResult<Vec<utopia_core::models::ChunkFull>> {
+ let rows = sqlx::query_as(
+ "SELECT id, seq, text FROM chunks
+ WHERE document_id = $1 AND superseded_at IS NULL ORDER BY seq",
+ )
+ .bind(document_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 抽取用分块:文本 + 摄入阶段已算好的 embedding(消解 v2 复用,零额外 embed 调用)。
+#[derive(Debug, sqlx::FromRow)]
+pub struct ChunkForExtract {
+ pub id: Uuid,
+ pub seq: i32,
+ pub text: String,
+ pub embedding: Option<Vector>,
+}
+
+pub async fn chunks_for_extraction(
+ pool: &PgPool,
+ document_id: Uuid,
+) -> AppResult<Vec<ChunkForExtract>> {
+ // 只取未抽取的分块:认领的未变段落携带 extracted_at 跳过(增量抽取 + 断点续抽)
+ let rows = sqlx::query_as(
+ "SELECT id, seq, text, embedding FROM chunks
+ WHERE document_id = $1 AND superseded_at IS NULL AND extracted_at IS NULL
+ ORDER BY seq",
+ )
+ .bind(document_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn set_graph_status(pool: &PgPool, id: Uuid, status: &str) -> AppResult<()> {
+ sqlx::query("UPDATE documents SET graph_status = $2, updated_at = now() WHERE id = $1")
+ .bind(id)
+ .bind(status)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 该文档尚未 embedding 的分块(id + 文本)。
+pub async fn chunks_pending_embedding(
+ pool: &PgPool,
+ document_id: Uuid,
+) -> AppResult<Vec<(Uuid, String)>> {
+ let rows: Vec<(Uuid, String)> = sqlx::query_as(
+ "SELECT id, text FROM chunks
+ WHERE document_id = $1 AND embedding IS NULL AND superseded_at IS NULL ORDER BY seq",
+ )
+ .bind(document_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn set_embeddings(pool: &PgPool, items: &[(Uuid, Vec<f32>)]) -> AppResult<()> {
+ let mut tx = pool.begin().await?;
+ for (id, emb) in items {
+ sqlx::query("UPDATE chunks SET embedding = $2 WHERE id = $1")
+ .bind(id)
+ .bind(Vector::from(emb.clone()))
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ Ok(())
+}
+
+/// 向量近邻检索(余弦距离,顺扫;P1 规模足够)。
+pub async fn vector_search(
+ pool: &PgPool,
+ kb_id: Uuid,
+ embedding: &[f32],
+ limit: i64,
+) -> AppResult<Vec<Uuid>> {
+ let query_vec = Vector::from(embedding.to_vec());
+ let rows: Vec<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM chunks
+ WHERE kb_id = $1 AND embedding IS NOT NULL AND superseded_at IS NULL
+ AND vector_dims(embedding) = vector_dims($2)
+ ORDER BY embedding <=> $2
+ LIMIT $3",
+ )
+ .bind(kb_id)
+ .bind(&query_vec)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows.into_iter().map(|(id,)| id).collect())
+}
+
+/// 按 id 集合取分块(带文档名),保持传入顺序。
+pub async fn chunks_by_ids(pool: &PgPool, kb_id: Uuid, ids: &[Uuid]) -> AppResult<Vec<ChunkView>> {
+ let rows: Vec<ChunkView> = sqlx::query_as(
+ "SELECT c.id, c.document_id, c.seq, c.text, d.filename
+ FROM chunks c JOIN documents d ON d.id = c.document_id
+ WHERE c.kb_id = $1 AND c.id = ANY($2)",
+ )
+ .bind(kb_id)
+ .bind(ids)
+ .fetch_all(pool)
+ .await?;
+ // 恢复 RRF 排名顺序
+ let mut by_id: std::collections::HashMap<Uuid, ChunkView> =
+ rows.into_iter().map(|c| (c.id, c)).collect();
+ Ok(ids.iter().filter_map(|id| by_id.remove(id)).collect())
+}
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
new file mode 100644
index 00000000..b35e948c
--- /dev/null
+++ b/crates/utopia-store/src/graph.rs
@@ -0,0 +1,655 @@
+//! 图谱仓储:本体、实体消解(P2 第一刀:同 KB 同类型同名合一)、事实账本、图查询。
+
+use sqlx::PgPool;
+use std::collections::HashSet;
+use utopia_core::models::{
+ ChunkFactView, EntityFact, EntityType, EvidenceView, FactReviewItem, GraphEdge, GraphNode,
+ RelationType,
+};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// 同断言已有事实的行投影:(id, valid_from, valid_to)。
+type FactSpanRow = (
+ Uuid,
+ Option<chrono::DateTime<chrono::Utc>>,
+ Option<chrono::DateTime<chrono::Utc>>,
+);
+
+/// 内置本体模板:(key, label, color, shape)
+// 低饱和粉彩色系(深色画布上柔和发光,不刺眼);组织/产品用方形区分"机构/制品"
+const DEFAULT_ENTITY_TYPES: &[(&str, &str, &str, &str)] = &[
+ ("person", "Person", "#7fd0ff", "circle"),
+ ("organization", "Organization", "#4cc38a", "square"),
+ ("project", "Project", "#f2b66d", "circle"),
+ // 问数语义层:可问的量与可切的维度(BI 语义层标准抽象),映射经 mapped_to 指向数据资产
+ ("metric", "Metric", "#ffd580", "square"),
+ ("dimension", "Dimension", "#9adcc6", "square"),
+ ("product", "Product", "#c4a5ff", "square"),
+ ("event", "Event", "#ff9daf", "circle"),
+ ("concept", "Concept", "#8ea5bd", "circle"),
+ ("location", "Location", "#5fd4d0", "circle"),
+];
+
+/// (key, label, temporal, functional, inverse_functional)
+/// functional = 同一时刻一个主语至多一个宾语(张三同时只 reports_to 一人);
+/// inverse_functional = 同一时刻一个宾语至多一个主语(一个项目同时只有一个 leads 它的人)。
+/// 两者都是时态冲突检测(自动闭合 valid_to)的触发依据。
+const DEFAULT_RELATION_TYPES: &[(&str, &str, &str, bool, bool)] = &[
+ ("works_at", "works at", "state", false, false),
+ ("leads", "leads", "state", false, true),
+ ("reports_to", "reports to", "state", true, false),
+ ("part_of", "part of", "state", true, false),
+ ("participates_in", "participates in", "state", false, false),
+ ("located_in", "located in", "state", false, false),
+ ("produces", "produces", "state", false, false),
+ ("alias_of", "alias of", "eternal", false, false),
+ ("related_to", "related to", "state", false, false),
+ // 问数语义层:概念 → 数据资产定义(object_value 宾语:{source, table?, expr?, sql?,
+ // derived?, unit?, summary})。多源=多条并存;同源口径演变由确认流程显式闭合,
+ // 不靠引擎盲判(唯一性粒度是 (概念,源),在 object_value 内部,引擎不感知)
+ ("mapped_to", "mapped to", "state", false, false),
+];
+
+pub async fn ensure_default_ontology(pool: &PgPool, kb_id: Uuid) -> AppResult<()> {
+ for (key, label, color, shape) in DEFAULT_ENTITY_TYPES {
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label, color, shape, builtin)
+ VALUES ($1, $2, $3, $4, $5, $6, TRUE) ON CONFLICT (kb_id, key) DO NOTHING",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(key)
+ .bind(label)
+ .bind(color)
+ .bind(shape)
+ .execute(pool)
+ .await?;
+ }
+ for (key, label, temporal, functional, inverse_functional) in DEFAULT_RELATION_TYPES {
+ sqlx::query(
+ "INSERT INTO relation_types
+ (id, kb_id, key, label, temporal, functional, inverse_functional, builtin)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, TRUE) ON CONFLICT (kb_id, key) DO NOTHING",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(key)
+ .bind(label)
+ .bind(temporal)
+ .bind(functional)
+ .bind(inverse_functional)
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
+
+pub async fn entity_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityType>> {
+ Ok(
+ sqlx::query_as("SELECT * FROM entity_types WHERE kb_id = $1 ORDER BY created_at")
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?,
+ )
+}
+
+pub async fn relation_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationType>> {
+ Ok(
+ sqlx::query_as("SELECT * FROM relation_types WHERE kb_id = $1 ORDER BY created_at")
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?,
+ )
+}
+
+/// 写入事实。返回 (事实 id, 是否新建)。
+///
+/// 同断言(同主谓宾)的多次观察不各立门户:
+/// - 同 valid_from 的 live 行已存在 → 复用(证据累积到同一条)
+/// - 新观察**没带时间**、同断言已有开放行 → 弱化陈述并入已有行("隶属星云科技"
+/// 并进"2021-02 起隶属星云科技",不再产生一条无时间的重复)
+/// - 新观察**带了时间**、同断言已有的是无时无终的裸行 → 时间精化:新行落库后
+/// 把裸行作废并以 supersedes 链上(作废+改写,认知史完整),证据随行复制
+/// - 双方都带时间但不同 → 保守并存(可能真是两段区间,如离职又回归)
+///
+/// 事实的宾语:实体(关系)或字面值(属性/问数映射)。同一套折并与时间精化逻辑。
+#[derive(Debug, Clone, Copy)]
+pub enum FactObject<'a> {
+ Entity(Uuid),
+ Value(&'a serde_json::Value),
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn insert_fact(
+ pool: &PgPool,
+ kb_id: Uuid,
+ subject_id: Uuid,
+ predicate_id: Uuid,
+ object_id: Uuid,
+ valid_from: Option<chrono::DateTime<chrono::Utc>>,
+ valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ valid_precision: &str,
+ confidence: f32,
+) -> AppResult<(Uuid, bool)> {
+ insert_fact_inner(
+ pool,
+ kb_id,
+ subject_id,
+ predicate_id,
+ FactObject::Entity(object_id),
+ valid_from,
+ valid_to,
+ valid_precision,
+ confidence,
+ )
+ .await
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn insert_fact_inner(
+ pool: &PgPool,
+ kb_id: Uuid,
+ subject_id: Uuid,
+ predicate_id: Uuid,
+ object: FactObject<'_>,
+ valid_from: Option<chrono::DateTime<chrono::Utc>>,
+ valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ valid_precision: &str,
+ confidence: f32,
+) -> AppResult<(Uuid, bool)> {
+ let same_sql = match object {
+ FactObject::Entity(_) => {
+ "SELECT id, valid_from, valid_to FROM facts
+ WHERE kb_id = $1 AND subject_id = $2 AND predicate_id = $3 AND object_id = $4
+ AND invalidated_at IS NULL"
+ }
+ FactObject::Value(_) => {
+ "SELECT id, valid_from, valid_to FROM facts
+ WHERE kb_id = $1 AND subject_id = $2 AND predicate_id = $3 AND object_value = $4
+ AND object_id IS NULL AND invalidated_at IS NULL"
+ }
+ };
+ let mut q = sqlx::query_as(same_sql)
+ .bind(kb_id)
+ .bind(subject_id)
+ .bind(predicate_id);
+ q = match object {
+ FactObject::Entity(id) => q.bind(id),
+ FactObject::Value(v) => q.bind(v),
+ };
+ let same: Vec<FactSpanRow> = q.fetch_all(pool).await?;
+ // 精确重复:同 valid_from → 复用
+ if let Some((existing, _, _)) = same.iter().find(|(_, vf, _)| *vf == valid_from) {
+ return Ok((*existing, false));
+ }
+ // 弱化陈述:新观察无时间,同断言已有开放行 → 并入(取起点最新的开放行)
+ if valid_from.is_none() && valid_to.is_none() {
+ if let Some((existing, _, _)) = same
+ .iter()
+ .filter(|(_, _, vt)| vt.is_none())
+ .max_by_key(|(_, vf, _)| *vf)
+ {
+ return Ok((*existing, false));
+ }
+ }
+ // 时间精化候选:已有无时无终的裸行,本次观察带了起点 → 落库后作废裸行并链上
+ let refine_target = if valid_from.is_some() {
+ same.iter()
+ .find(|(_, vf, vt)| vf.is_none() && vt.is_none())
+ .map(|(id, _, _)| *id)
+ } else {
+ None
+ };
+
+ let id = Uuid::now_v7();
+ let insert_sql = match object {
+ FactObject::Entity(_) => {
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id,
+ valid_from, valid_to, valid_precision, confidence)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)"
+ }
+ FactObject::Value(_) => {
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_value,
+ valid_from, valid_to, valid_precision, confidence)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)"
+ }
+ };
+ let mut ins = sqlx::query(insert_sql)
+ .bind(id)
+ .bind(kb_id)
+ .bind(subject_id)
+ .bind(predicate_id);
+ ins = match object {
+ FactObject::Entity(oid) => ins.bind(oid),
+ FactObject::Value(v) => ins.bind(v),
+ };
+ ins.bind(valid_from)
+ .bind(valid_to)
+ .bind(valid_precision)
+ .bind(confidence)
+ .execute(pool)
+ .await?;
+
+ // 时间精化:裸行(无时无终的同断言)被本次带时间的观察取代——作废+链上,证据随行
+ if let Some(old_id) = refine_target {
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(old_id)
+ .execute(pool)
+ .await?;
+ sqlx::query("UPDATE facts SET supersedes = $2 WHERE id = $1")
+ .bind(id)
+ .bind(old_id)
+ .execute(pool)
+ .await?;
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version)
+ SELECT $1, chunk_id, quote, document_id, doc_version
+ FROM fact_evidence WHERE fact_id = $2
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(id)
+ .bind(old_id)
+ .execute(pool)
+ .await?;
+ }
+ Ok((id, true))
+}
+
+/// 字面值宾语的事实(object_value 通道,问数映射首个消费者)。
+/// 去重:同 (S,P) 且 object_value 完全相等的 live 事实只存一条。
+#[allow(clippy::too_many_arguments)]
+pub async fn insert_value_fact(
+ pool: &PgPool,
+ kb_id: Uuid,
+ subject_id: Uuid,
+ predicate_id: Uuid,
+ object_value: &serde_json::Value,
+ valid_from: Option<chrono::DateTime<chrono::Utc>>,
+ valid_to: Option<chrono::DateTime<chrono::Utc>>,
+ valid_precision: &str,
+ confidence: f32,
+) -> AppResult<(Uuid, bool)> {
+ insert_fact_inner(
+ pool,
+ kb_id,
+ subject_id,
+ predicate_id,
+ FactObject::Value(object_value),
+ valid_from,
+ valid_to,
+ valid_precision,
+ confidence,
+ )
+ .await
+}
+
+/// 已确认(置信 ≥ threshold)的问数映射:概念名 + 定义。问数 prompt 注入用。
+pub async fn confirmed_mappings(
+ pool: &PgPool,
+ kb_id: Uuid,
+ threshold: f32,
+ limit: i64,
+) -> AppResult<Vec<(String, serde_json::Value)>> {
+ let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(
+ "SELECT s.canonical_name, f.object_value
+ FROM facts f
+ JOIN relation_types r ON r.id = f.predicate_id AND r.key = 'mapped_to'
+ JOIN entities s ON s.id = f.subject_id
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.valid_to IS NULL
+ AND f.object_value IS NOT NULL AND f.confidence >= $2
+ ORDER BY s.canonical_name
+ LIMIT $3",
+ )
+ .bind(kb_id)
+ .bind(threshold)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn add_evidence(
+ pool: &PgPool,
+ fact_id: Uuid,
+ chunk_id: Uuid,
+ quote: Option<&str>,
+) -> AppResult<()> {
+ // 证据落笔即记版本:出自哪份文档的第几版(S3 版本对账与"证据过期"判定的依据)
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version)
+ SELECT $1, $2, $3, c.document_id, c.doc_version FROM chunks c WHERE c.id = $2
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(fact_id)
+ .bind(chunk_id)
+ .bind(quote)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+const NODE_SQL: &str = "SELECT e.id, e.canonical_name AS name, t.key AS type_key,
+ t.label AS type_label, t.color, t.shape, e.disambiguator,
+ (SELECT count(*) FROM facts f
+ WHERE (f.subject_id = e.id OR f.object_id = e.id) AND f.invalidated_at IS NULL) AS degree
+ FROM entities e JOIN entity_types t ON t.id = e.type_id";
+
+/// 全图概览:按度数取 top N 实体及其间的边。
+/// `at`:服务端 as-of——只返回 T 时刻有效的边(起点不晚于 T 或未知,终点晚于 T 或开放)。
+/// 前端时间滑杆走本地过滤不传此参数;这是给 API/MCP 消费者的时间旅行入口。
+pub async fn overview(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+ at: Option<chrono::DateTime<chrono::Utc>>,
+) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>)> {
+ let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
+ "{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL ORDER BY degree DESC, e.created_at LIMIT $2"
+ ))
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+
+ let ids: Vec<Uuid> = nodes.iter().map(|n| n.id).collect();
+ let edges = edges_among(pool, kb_id, &ids, at).await?;
+ Ok((nodes, edges))
+}
+
+async fn edges_among(
+ pool: &PgPool,
+ kb_id: Uuid,
+ ids: &[Uuid],
+ at: Option<chrono::DateTime<chrono::Utc>>,
+) -> AppResult<Vec<GraphEdge>> {
+ if ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let edges: Vec<GraphEdge> = sqlx::query_as(
+ "SELECT f.id, f.subject_id AS source, f.object_id AS target, r.key AS predicate,
+ r.label, f.valid_from, f.valid_to, f.confidence
+ FROM facts f JOIN relation_types r ON r.id = f.predicate_id
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
+ AND f.subject_id = ANY($2) AND f.object_id = ANY($2)
+ AND ($3::timestamptz IS NULL
+ OR ((f.valid_from IS NULL OR f.valid_from <= $3)
+ AND (f.valid_to IS NULL OR f.valid_to > $3)))",
+ )
+ .bind(kb_id)
+ .bind(ids)
+ .bind(at)
+ .fetch_all(pool)
+ .await?;
+ Ok(edges)
+}
+
+/// 邻域扩展(BFS,最多 2 跳,节点数封顶)。
+pub async fn neighborhood(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+ hops: u8,
+ at: Option<chrono::DateTime<chrono::Utc>>,
+) -> AppResult<(Vec<GraphNode>, Vec<GraphEdge>)> {
+ const MAX_NODES: usize = 300;
+ let mut seen: HashSet<Uuid> = HashSet::from([entity_id]);
+ let mut frontier: Vec<Uuid> = vec![entity_id];
+
+ for _ in 0..hops.clamp(1, 2) {
+ if frontier.is_empty() || seen.len() >= MAX_NODES {
+ break;
+ }
+ let touching: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(
+ "SELECT subject_id, object_id FROM facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL AND object_id IS NOT NULL
+ AND (subject_id = ANY($2) OR object_id = ANY($2))",
+ )
+ .bind(kb_id)
+ .bind(&frontier)
+ .fetch_all(pool)
+ .await?;
+
+ let mut next = Vec::new();
+ for (s, o) in touching {
+ for id in [Some(s), o].into_iter().flatten() {
+ if seen.len() >= MAX_NODES {
+ break;
+ }
+ if seen.insert(id) {
+ next.push(id);
+ }
+ }
+ }
+ frontier = next;
+ }
+
+ let ids: Vec<Uuid> = seen.into_iter().collect();
+ let nodes: Vec<GraphNode> =
+ sqlx::query_as(&format!("{NODE_SQL} WHERE e.kb_id = $1 AND e.id = ANY($2)"))
+ .bind(kb_id)
+ .bind(&ids)
+ .fetch_all(pool)
+ .await?;
+ let edges = edges_among(pool, kb_id, &ids, at).await?;
+ Ok((nodes, edges))
+}
+
+pub async fn search_entities(
+ pool: &PgPool,
+ kb_id: Uuid,
+ q: &str,
+ limit: i64,
+) -> AppResult<Vec<GraphNode>> {
+ let pattern = format!("%{}%", q.trim());
+ let nodes: Vec<GraphNode> = sqlx::query_as(&format!(
+ "{NODE_SQL} WHERE e.kb_id = $1 AND e.merged_into IS NULL
+ AND e.canonical_name ILIKE $2 ORDER BY degree DESC LIMIT $3"
+ ))
+ .bind(kb_id)
+ .bind(pattern)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(nodes)
+}
+
+/// 实体详情:节点信息 + 事实时间线。
+pub async fn entity_detail(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+) -> AppResult<(GraphNode, Vec<EntityFact>)> {
+ let node: GraphNode = sqlx::query_as(&format!("{NODE_SQL} WHERE e.kb_id = $1 AND e.id = $2"))
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)?;
+
+ let facts: Vec<EntityFact> = sqlx::query_as(
+ "SELECT f.id,
+ CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,
+ r.key AS predicate_key, r.label AS predicate_label, r.temporal,
+ CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END AS other_id,
+ o.canonical_name AS other_name, f.object_value,
+ f.valid_from, f.valid_to, f.valid_precision, f.confidence,
+ (SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count,
+ (EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)
+ AND NOT EXISTS (SELECT 1 FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ WHERE fe.fact_id = f.id AND c.superseded_at IS NULL)
+ ) AS stale,
+ (f.supersedes IS NOT NULL) AS corrected,
+ (SELECT MAX(COALESCE(d.doc_time, d.created_at))
+ FROM fact_evidence fe JOIN documents d ON d.id = fe.document_id
+ WHERE fe.fact_id = f.id) AS last_evidence_time
+ FROM facts f
+ JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o
+ ON o.id = CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ AND (f.subject_id = $2 OR f.object_id = $2)
+ ORDER BY f.valid_from NULLS LAST, f.recorded_at",
+ )
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_all(pool)
+ .await?;
+
+ Ok((node, facts))
+}
+
+/// 低置信 live 事实(审核页)。
+pub async fn low_confidence_facts(
+ pool: &PgPool,
+ kb_id: Uuid,
+ below: f32,
+ limit: i64,
+) -> AppResult<Vec<FactReviewItem>> {
+ let rows: Vec<FactReviewItem> = sqlx::query_as(
+ "SELECT f.id, s.canonical_name AS subject_name, r.label AS predicate_label,
+ COALESCE(o.canonical_name, f.object_value->>'summary') AS object_name,
+ f.valid_from, f.valid_to, f.confidence,
+ (SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count,
+ (SELECT fe.quote FROM fact_evidence fe
+ WHERE fe.fact_id = f.id AND fe.quote IS NOT NULL LIMIT 1) AS quote
+ FROM facts f
+ JOIN entities s ON s.id = f.subject_id
+ JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.confidence < $2
+ ORDER BY f.confidence, f.recorded_at DESC
+ LIMIT $3",
+ )
+ .bind(kb_id)
+ .bind(below)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// "证据全部停留在旧版"的现行事实(S3 第三刀:文档新版没再确认的知识)。
+/// 判定纯派生自 chunk 存活性——认领机制保证未变段落的证据不被误伤;
+/// 绝不自动删除(没再提 ≠ 不成立),删除/闭合权在 Review 的人手里。
+pub async fn stale_facts(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<FactReviewItem>> {
+ let rows: Vec<FactReviewItem> = sqlx::query_as(
+ "SELECT f.id, s.canonical_name AS subject_name, r.label AS predicate_label,
+ COALESCE(o.canonical_name, f.object_value->>'summary') AS object_name,
+ f.valid_from, f.valid_to, f.confidence,
+ (SELECT count(*) FROM fact_evidence fe WHERE fe.fact_id = f.id) AS evidence_count,
+ (SELECT fe.quote FROM fact_evidence fe
+ WHERE fe.fact_id = f.id AND fe.quote IS NOT NULL LIMIT 1) AS quote
+ FROM facts f
+ JOIN entities s ON s.id = f.subject_id
+ JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ AND EXISTS (SELECT 1 FROM fact_evidence fe WHERE fe.fact_id = f.id)
+ AND NOT EXISTS (SELECT 1 FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ WHERE fe.fact_id = f.id AND c.superseded_at IS NULL)
+ ORDER BY f.recorded_at DESC
+ LIMIT $2",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 人工确认低置信事实:置信度提到 1.0。
+pub async fn confirm_fact(pool: &PgPool, kb_id: Uuid, fact_id: Uuid) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE facts SET confidence = 1.0 WHERE id = $1 AND kb_id = $2 AND invalidated_at IS NULL",
+ )
+ .bind(fact_id)
+ .bind(kb_id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ // 问数映射的口径唯一性:确认 (概念, 源) 的新定义 = 背书替换,同源旧映射作废。
+ // 认知轴修正(旧口径是"我们当时的理解",不是世界里结束的状态);
+ // 唯一性只活在这条确认流里,时态引擎保持领域无关。
+ sqlx::query(
+ "UPDATE facts f SET invalidated_at = now()
+ FROM facts nf
+ JOIN relation_types r ON r.id = nf.predicate_id
+ WHERE nf.id = $1 AND r.key = 'mapped_to'
+ AND f.kb_id = $2 AND f.id <> nf.id
+ AND f.subject_id = nf.subject_id AND f.predicate_id = nf.predicate_id
+ AND f.invalidated_at IS NULL
+ AND f.object_value->>'source' = nf.object_value->>'source'",
+ )
+ .bind(fact_id)
+ .bind(kb_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 人工否决事实:作废(账本 append-only,不 DELETE)。
+pub async fn reject_fact(pool: &PgPool, kb_id: Uuid, fact_id: Uuid) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE facts SET invalidated_at = now()
+ WHERE id = $1 AND kb_id = $2 AND invalidated_at IS NULL",
+ )
+ .bind(fact_id)
+ .bind(kb_id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 反向证据链:该文档每个分块抽出了哪些 live 事实(文档查看器右栏)。
+pub async fn document_extractions(
+ pool: &PgPool,
+ document_id: Uuid,
+) -> AppResult<Vec<ChunkFactView>> {
+ let rows: Vec<ChunkFactView> = sqlx::query_as(
+ "SELECT fe.chunk_id, f.id AS fact_id,
+ f.subject_id, s.canonical_name AS subject,
+ r.label AS predicate,
+ f.object_id, o.canonical_name AS object,
+ f.valid_from, f.valid_to, f.confidence
+ FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id AND c.document_id = $1
+ AND c.superseded_at IS NULL
+ JOIN facts f ON f.id = fe.fact_id AND f.invalidated_at IS NULL
+ JOIN entities s ON s.id = f.subject_id
+ JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o ON o.id = f.object_id
+ ORDER BY c.seq, f.recorded_at",
+ )
+ .bind(document_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 证据回放路径:不过滤 superseded——它的职责就是能看旧版。
+/// stale = 证据版本落后于文档当前版本(UI 标 "from v{n}")。
+pub async fn fact_evidence(pool: &PgPool, fact_id: Uuid) -> AppResult<Vec<EvidenceView>> {
+ let rows: Vec<EvidenceView> = sqlx::query_as(
+ "SELECT fe.quote, fe.chunk_id, c.document_id, d.filename, c.seq,
+ c.doc_version,
+ c.doc_version < COALESCE(
+ (SELECT MAX(version) FROM document_versions dv
+ WHERE dv.document_id = c.document_id), 1) AS stale
+ FROM fact_evidence fe
+ JOIN chunks c ON c.id = fe.chunk_id
+ JOIN documents d ON d.id = c.document_id
+ WHERE fe.fact_id = $1",
+ )
+ .bind(fact_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
diff --git a/crates/utopia-store/src/jobs.rs b/crates/utopia-store/src/jobs.rs
new file mode 100644
index 00000000..f59c568c
--- /dev/null
+++ b/crates/utopia-store/src/jobs.rs
@@ -0,0 +1,150 @@
+//! 任务队列:Postgres `FOR UPDATE SKIP LOCKED` 消费。
+//! worker 与 API 同进程(tokio task),失败按 30s * attempts² 退避重试。
+//! 并发消费:调度循环按"运行中 < 目标数"续派,任务在独立 task 执行;
+//! 目标数经 AtomicUsize 热读——系统设置里改并发即时生效,无需重启。
+
+use sqlx::PgPool;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+use utopia_core::AppResult;
+
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct Job {
+ pub id: i64,
+ pub kind: String,
+ pub payload: serde_json::Value,
+ pub attempts: i32,
+ pub max_attempts: i32,
+}
+
+pub async fn enqueue(pool: &PgPool, kind: &str, payload: serde_json::Value) -> AppResult<i64> {
+ let (id,): (i64,) =
+ sqlx::query_as("INSERT INTO jobs (kind, payload) VALUES ($1, $2) RETURNING id")
+ .bind(kind)
+ .bind(payload)
+ .fetch_one(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 认领一个到期任务;没有则返回 None。
+async fn claim_one(pool: &PgPool) -> AppResult<Option<Job>> {
+ let job = sqlx::query_as(
+ "UPDATE jobs SET status = 'running', locked_at = now(),
+ attempts = attempts + 1, updated_at = now()
+ WHERE id = (
+ SELECT id FROM jobs
+ WHERE status = 'queued' AND run_at <= now()
+ ORDER BY run_at
+ FOR UPDATE SKIP LOCKED
+ LIMIT 1
+ )
+ RETURNING id, kind, payload, attempts, max_attempts",
+ )
+ .fetch_optional(pool)
+ .await?;
+ Ok(job)
+}
+
+async fn mark_done(pool: &PgPool, id: i64) -> AppResult<()> {
+ sqlx::query("UPDATE jobs SET status = 'done', updated_at = now() WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+async fn mark_failed(pool: &PgPool, job: &Job, err: &str) -> AppResult<()> {
+ if job.attempts >= job.max_attempts {
+ sqlx::query(
+ "UPDATE jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE id = $1",
+ )
+ .bind(job.id)
+ .bind(err)
+ .execute(pool)
+ .await?;
+ } else {
+ let backoff_secs = 30i64 * i64::from(job.attempts) * i64::from(job.attempts);
+ sqlx::query(
+ "UPDATE jobs SET status = 'queued', last_error = $2,
+ run_at = now() + make_interval(secs => $3::float8),
+ updated_at = now()
+ WHERE id = $1",
+ )
+ .bind(job.id)
+ .bind(err)
+ .bind(backoff_secs as f64)
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
+
+/// worker 调度循环:运行中任务数低于目标并发就继续认领(有活立即续派),
+/// 空闲时 2s 轮询;每个任务在独立 tokio task 中执行,长抽取不再阻塞同步。
+/// `concurrency` 每轮热读——系统设置里改并发数即时生效。
+/// 任务分发逻辑由调用方以 handler 注入(store 不依赖上层 crate)。
+pub async fn run_worker<F, Fut>(pool: PgPool, concurrency: Arc<AtomicUsize>, handler: F)
+where
+ F: Fn(Job) -> Fut + Clone + Send + Sync + 'static,
+ Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
+{
+ let running = Arc::new(AtomicUsize::new(0));
+ // 孤儿回收:进程被杀时 running 任务无人收尸,文档会永远停在 extracting。
+ // 单进程部署下,启动时仍为 running 的必是孤儿——一律重排队(处理器均幂等)。
+ match sqlx::query(
+ "UPDATE jobs SET status = 'queued', locked_at = NULL, updated_at = now()
+ WHERE status = 'running'",
+ )
+ .execute(&pool)
+ .await
+ {
+ Ok(r) if r.rows_affected() > 0 => {
+ tracing::warn!(
+ count = r.rows_affected(),
+ "回收孤儿任务(上次进程退出时正在运行)"
+ );
+ }
+ Ok(_) => {}
+ Err(e) => tracing::error!(error = %e, "孤儿任务回收失败"),
+ }
+ tracing::info!(
+ concurrency = concurrency.load(Ordering::Relaxed),
+ "jobs worker 已启动"
+ );
+ loop {
+ let cap = concurrency.load(Ordering::Relaxed).max(1);
+ if running.load(Ordering::Relaxed) >= cap {
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ continue;
+ }
+ match claim_one(&pool).await {
+ Ok(Some(job)) => {
+ running.fetch_add(1, Ordering::Relaxed);
+ let pool = pool.clone();
+ let handler = handler.clone();
+ let running = running.clone();
+ tokio::spawn(async move {
+ let result = handler(job.clone()).await;
+ let outcome = match result {
+ Ok(()) => mark_done(&pool, job.id).await,
+ Err(e) => {
+ tracing::warn!(job_id = job.id, kind = %job.kind, error = %e, "任务执行失败");
+ mark_failed(&pool, &job, &e.to_string()).await
+ }
+ };
+ if let Err(e) = outcome {
+ tracing::error!(job_id = job.id, error = %e, "任务状态写回失败");
+ }
+ running.fetch_sub(1, Ordering::Relaxed);
+ });
+ }
+ Ok(None) => tokio::time::sleep(Duration::from_secs(2)).await,
+ Err(e) => {
+ tracing::error!(error = %e, "任务认领失败,5s 后重试");
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ }
+ }
+ }
+}
diff --git a/crates/utopia-store/src/kbs.rs b/crates/utopia-store/src/kbs.rs
new file mode 100644
index 00000000..156cf7d5
--- /dev/null
+++ b/crates/utopia-store/src/kbs.rs
@@ -0,0 +1,126 @@
+use sqlx::PgPool;
+use utopia_core::models::KnowledgeBase;
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+pub async fn list(pool: &PgPool, workspace_id: Uuid) -> AppResult<Vec<KnowledgeBase>> {
+ let rows =
+ sqlx::query_as("SELECT * FROM knowledge_bases WHERE workspace_id = $1 ORDER BY created_at")
+ .bind(workspace_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 用户可见的 KB:系统管理员全见;其余 = open 库 + 自己在矩阵里的 restricted 库。
+pub async fn list_visible(
+ pool: &PgPool,
+ workspace_id: Uuid,
+ user_id: Uuid,
+ is_admin: bool,
+) -> AppResult<Vec<KnowledgeBase>> {
+ let rows = sqlx::query_as(
+ "SELECT * FROM knowledge_bases k
+ WHERE k.workspace_id = $1
+ AND ($3
+ OR k.visibility = 'open'
+ OR EXISTS (SELECT 1 FROM kb_members m
+ WHERE m.kb_id = k.id AND m.user_id = $2))
+ ORDER BY k.created_at",
+ )
+ .bind(workspace_id)
+ .bind(user_id)
+ .bind(is_admin)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn create(
+ pool: &PgPool,
+ workspace_id: Uuid,
+ name: &str,
+ kind: &str,
+ description: Option<&str>,
+) -> AppResult<KnowledgeBase> {
+ // 部署的第一个库自动成为默认库:公共空间,永远 open、不可删(API 强制 + DB CHECK)
+ let kb = sqlx::query_as(
+ "INSERT INTO knowledge_bases (id, workspace_id, name, kind, description, is_default)
+ VALUES ($1, $2, $3, $4, $5,
+ NOT EXISTS (SELECT 1 FROM knowledge_bases WHERE workspace_id = $2))
+ RETURNING *",
+ )
+ .bind(Uuid::now_v7())
+ .bind(workspace_id)
+ .bind(name)
+ .bind(kind)
+ .bind(description)
+ .fetch_one(pool)
+ .await?;
+ Ok(kb)
+}
+
+pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<KnowledgeBase> {
+ sqlx::query_as("SELECT * FROM knowledge_bases WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+pub async fn update(
+ pool: &PgPool,
+ id: Uuid,
+ name: Option<&str>,
+ description: Option<&str>,
+ visibility: Option<&str>,
+) -> AppResult<KnowledgeBase> {
+ if let Some(v) = visibility {
+ if !matches!(v, "open" | "restricted") {
+ return Err(AppError::Validation(
+ "visibility must be open or restricted".into(),
+ ));
+ }
+ // 默认库永远 open:公共空间语义可依赖(改名/改描述不受限)
+ if v == "restricted" {
+ let current = get(pool, id).await?;
+ if current.is_default {
+ return Err(AppError::Validation(
+ "The default knowledge base stays open to everyone.".into(),
+ ));
+ }
+ }
+ }
+ sqlx::query_as(
+ "UPDATE knowledge_bases
+ SET name = COALESCE($2, name),
+ description = COALESCE($3, description),
+ visibility = COALESCE($4, visibility),
+ updated_at = now()
+ WHERE id = $1 RETURNING *",
+ )
+ .bind(id)
+ .bind(name)
+ .bind(description)
+ .bind(visibility)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ let current = get(pool, id).await?;
+ if current.is_default {
+ return Err(AppError::Validation(
+ "The default knowledge base cannot be deleted.".into(),
+ ));
+ }
+ let res = sqlx::query("DELETE FROM knowledge_bases WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/lib.rs b/crates/utopia-store/src/lib.rs
new file mode 100644
index 00000000..a30a2034
--- /dev/null
+++ b/crates/utopia-store/src/lib.rs
@@ -0,0 +1,21 @@
+//! utopia-store: sqlx 仓储、迁移、任务队列。
+//! 全部使用运行时查询(非编译期宏),构建无需数据库。
+
+pub mod access;
+pub mod accounts;
+pub mod audit;
+pub mod conversations;
+pub mod datasources;
+pub mod db;
+pub mod documents;
+pub mod graph;
+pub mod jobs;
+pub mod kbs;
+pub mod members;
+pub mod memory;
+pub mod ontology;
+pub mod resolution;
+pub mod settings;
+pub mod sources;
+pub mod temporal;
+pub mod workspaces;
diff --git a/crates/utopia-store/src/members.rs b/crates/utopia-store/src/members.rs
new file mode 100644
index 00000000..2a821c02
--- /dev/null
+++ b/crates/utopia-store/src/members.rs
@@ -0,0 +1,86 @@
+use sqlx::PgPool;
+use utopia_core::models::{MemberView, OrgUser, Role};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+pub async fn list(pool: &PgPool, workspace_id: Uuid) -> AppResult<Vec<MemberView>> {
+ let rows = sqlx::query_as(
+ "SELECT m.user_id, u.email, u.display_name, m.role, u.is_admin
+ FROM memberships m JOIN users u ON u.id = m.user_id
+ WHERE m.workspace_id = $1
+ ORDER BY m.created_at",
+ )
+ .bind(workspace_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 部署内全部用户(添加成员的选人器)。
+pub async fn org_users(pool: &PgPool, org_id: Uuid) -> AppResult<Vec<OrgUser>> {
+ let rows = sqlx::query_as(
+ "SELECT id, email, display_name, is_admin FROM users
+ WHERE org_id = $1 ORDER BY created_at",
+ )
+ .bind(org_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn owner_count(pool: &PgPool, workspace_id: Uuid) -> AppResult<i64> {
+ let (n,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM memberships WHERE workspace_id = $1 AND role = 'owner'",
+ )
+ .bind(workspace_id)
+ .fetch_one(pool)
+ .await?;
+ Ok(n)
+}
+
+pub async fn current_role(
+ pool: &PgPool,
+ workspace_id: Uuid,
+ user_id: Uuid,
+) -> AppResult<Option<Role>> {
+ crate::workspaces::role_of(pool, user_id, workspace_id).await
+}
+
+/// 设置/添加成员角色(upsert)。防呆逻辑在 API 层。
+pub async fn set_role(
+ pool: &PgPool,
+ workspace_id: Uuid,
+ user_id: Uuid,
+ role: Role,
+) -> AppResult<()> {
+ // 目标用户必须存在于本组织
+ let exists: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM users WHERE id = $1")
+ .bind(user_id)
+ .fetch_optional(pool)
+ .await?;
+ if exists.is_none() {
+ return Err(AppError::NotFound);
+ }
+ sqlx::query(
+ "INSERT INTO memberships (user_id, workspace_id, role) VALUES ($1, $2, $3)
+ ON CONFLICT (user_id, workspace_id) DO UPDATE SET role = EXCLUDED.role",
+ )
+ .bind(user_id)
+ .bind(workspace_id)
+ .bind(role.as_str())
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn remove(pool: &PgPool, workspace_id: Uuid, user_id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM memberships WHERE workspace_id = $1 AND user_id = $2")
+ .bind(workspace_id)
+ .bind(user_id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/memory.rs b/crates/utopia-store/src/memory.rs
new file mode 100644
index 00000000..4fa04ceb
--- /dev/null
+++ b/crates/utopia-store/src/memory.rs
@@ -0,0 +1,109 @@
+//! Agent/对话记忆:episodes 快速路径。
+//!
+//! 设计(零新轮子):记忆空间 = 知识库本身;每条 episode = 隐式 "Memory" 来源下
+//! "Memory log" 文档上追加的一个 chunk(文本内嵌事发时间戳行)。于是全链路复用:
+//! chunk 进全文/向量索引(记忆可检索)、fact_evidence 指 chunk(记忆事实可溯源到
+//! 原话)、extracted_at 增量抽取只处理新 episode、事实 valid_from 取事发时间、
+//! 与既有 functional 事实矛盾时时态引擎自动闭合——"上月喜欢 A 本月改 B"自然
+//! 变成两段区间。账本纪律:episodes 只追加,永不改写。
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+pub const MEMORY_SOURCE_KIND: &str = "memory";
+const MEMORY_DOC_KEY: &str = "memory:log";
+
+/// 每 KB 的隐式 Memory 来源(不可删;Library 里可见——记忆透明是特性)。
+pub async fn get_or_create_memory_source(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {
+ if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
+ "SELECT id FROM sources WHERE kb_id = $1 AND kind = $2 LIMIT 1",
+ )
+ .bind(kb_id)
+ .bind(MEMORY_SOURCE_KIND)
+ .fetch_optional(pool)
+ .await?
+ {
+ return Ok(id);
+ }
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO sources (id, kb_id, kind, name, config) VALUES ($1, $2, $3, 'Memory', '{}')",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(MEMORY_SOURCE_KIND)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// Memory log 文档(每 KB 一份)。绕开 documents::create 的同内容去重——
+/// 它不是内容寻址的文件,sha256 填哨兵值。
+pub async fn get_or_create_memory_doc(pool: &PgPool, kb_id: Uuid) -> AppResult<Uuid> {
+ if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
+ "SELECT id FROM documents WHERE kb_id = $1 AND external_key = $2 LIMIT 1",
+ )
+ .bind(kb_id)
+ .bind(MEMORY_DOC_KEY)
+ .fetch_optional(pool)
+ .await?
+ {
+ return Ok(id);
+ }
+ let source_id = get_or_create_memory_source(pool, kb_id).await?;
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO documents
+ (id, kb_id, source_id, filename, mime, size_bytes, sha256,
+ status, graph_status, external_key, doc_time_source)
+ VALUES ($1, $2, $3, 'memory-log.md', 'text/markdown', 0, 'memory:log',
+ 'ready', 'done', $4, 'none')",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(source_id)
+ .bind(MEMORY_DOC_KEY)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+/// 追加一条 episode:新 chunk(extracted_at 空 → 增量抽取会拾起;embedding 空 →
+/// memory_ingest 会补)。事发时间内嵌进文本首行,抽取模型据此定 valid_from。
+pub async fn append_episode(
+ pool: &PgPool,
+ kb_id: Uuid,
+ text: &str,
+ occurred_at: DateTime<Utc>,
+) -> AppResult<(Uuid, Uuid)> {
+ let doc_id = get_or_create_memory_doc(pool, kb_id).await?;
+ let stamped = format!("[{}] {}", occurred_at.format("%Y-%m-%d %H:%M"), text.trim());
+ let chunk_id = Uuid::now_v7();
+ let mut tx = pool.begin().await?;
+ sqlx::query(
+ "INSERT INTO chunks (id, kb_id, document_id, seq, text, char_start, char_end, doc_version)
+ VALUES ($1, $2, $3,
+ (SELECT COALESCE(MAX(seq), -1) + 1 FROM chunks
+ WHERE document_id = $3 AND superseded_at IS NULL),
+ $4, 0, $5, 1)",
+ )
+ .bind(chunk_id)
+ .bind(kb_id)
+ .bind(doc_id)
+ .bind(&stamped)
+ .bind(stamped.chars().count() as i32)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "UPDATE documents SET chunk_count = chunk_count + 1, size_bytes = size_bytes + $2,
+ updated_at = now() WHERE id = $1",
+ )
+ .bind(doc_id)
+ .bind(stamped.len() as i64)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok((doc_id, chunk_id))
+}
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
new file mode 100644
index 00000000..ff9e2be9
--- /dev/null
+++ b/crates/utopia-store/src/ontology.rs
@@ -0,0 +1,383 @@
+//! 本体编辑器仓储:类型/关系 CRUD(带使用量与删除保护)+ 未匹配统计。
+
+use sqlx::PgPool;
+use utopia_core::models::{EntityInstance, EntityTypeView, OntologyMiss, RelationTypeView};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+pub async fn entity_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityTypeView>> {
+ Ok(sqlx::query_as(
+ "SELECT t.id, t.key, t.label, t.color, t.shape, t.builtin, t.parent_id, t.description,
+ (SELECT count(*) FROM entities e
+ WHERE e.type_id = t.id AND e.merged_into IS NULL) AS usage
+ FROM entity_types t WHERE t.kb_id = $1 ORDER BY lower(t.label)",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+/// 某个类下的实体实例(按名称序,分页)。返回 (rows, total)。
+pub async fn entity_instances(
+ pool: &PgPool,
+ kb_id: Uuid,
+ type_id: Uuid,
+ limit: i64,
+ offset: i64,
+) -> AppResult<(Vec<EntityInstance>, i64)> {
+ let rows: Vec<EntityInstance> = sqlx::query_as(
+ "SELECT e.id, e.canonical_name AS name,
+ (SELECT count(*) FROM facts f
+ WHERE (f.subject_id = e.id OR f.object_id = e.id)
+ AND f.invalidated_at IS NULL) AS fact_count
+ FROM entities e
+ WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL
+ ORDER BY lower(e.canonical_name)
+ LIMIT $3 OFFSET $4",
+ )
+ .bind(kb_id)
+ .bind(type_id)
+ .bind(limit)
+ .bind(offset)
+ .fetch_all(pool)
+ .await?;
+ let (total,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM entities e
+ WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL",
+ )
+ .bind(kb_id)
+ .bind(type_id)
+ .fetch_one(pool)
+ .await?;
+ Ok((rows, total))
+}
+
+fn validate_shape(shape: &str) -> AppResult<()> {
+ if !matches!(shape, "circle" | "square") {
+ return Err(AppError::Validation(
+ "shape must be circle or square".into(),
+ ));
+ }
+ Ok(())
+}
+
+pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationTypeView>> {
+ Ok(sqlx::query_as(
+ "SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional, r.builtin, r.description,
+ r.kind, r.domain_type_id, r.datatype, r.unit,
+ (SELECT count(*) FROM facts f
+ WHERE f.predicate_id = r.id AND f.invalidated_at IS NULL) AS usage
+ FROM relation_types r WHERE r.kb_id = $1 ORDER BY lower(r.label)",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+fn validate_key(key: &str) -> AppResult<()> {
+ let ok = !key.is_empty()
+ && key.len() <= 40
+ && key
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
+ if !ok {
+ return Err(AppError::Validation(
+ "Key must be lowercase snake_case (a-z, 0-9, _), max 40 chars".into(),
+ ));
+ }
+ Ok(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn create_entity_type(
+ pool: &PgPool,
+ kb_id: Uuid,
+ key: &str,
+ label: &str,
+ color: &str,
+ shape: &str,
+ parent_id: Option<Uuid>,
+ description: &str,
+) -> AppResult<Uuid> {
+ validate_key(key)?;
+ validate_shape(shape)?;
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entity_types (id, kb_id, key, label, color, shape, parent_id, description)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(key)
+ .bind(label)
+ .bind(color)
+ .bind(shape)
+ .bind(parent_id)
+ .bind(description)
+ .execute(pool)
+ .await
+ .map_err(|e| match &e {
+ sqlx::Error::Database(db) if db.is_unique_violation() => {
+ AppError::Conflict(format!("Type key '{key}' already exists"))
+ }
+ _ => AppError::Db(e),
+ })?;
+ Ok(id)
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn update_entity_type(
+ pool: &PgPool,
+ kb_id: Uuid,
+ id: Uuid,
+ label: &str,
+ color: &str,
+ shape: &str,
+ parent_id: Option<Uuid>,
+ description: &str,
+) -> AppResult<()> {
+ if parent_id == Some(id) {
+ return Err(AppError::Validation(
+ "A class cannot be its own parent".into(),
+ ));
+ }
+ validate_shape(shape)?;
+ let res = sqlx::query(
+ "UPDATE entity_types SET label = $3, color = $4, shape = $5, parent_id = $6,
+ description = $7
+ WHERE id = $2 AND kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .bind(label)
+ .bind(color)
+ .bind(shape)
+ .bind(parent_id)
+ .bind(description)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
+ let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM entities WHERE type_id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?;
+ if usage > 0 {
+ return Err(AppError::Conflict(format!(
+ "Cannot delete: {usage} entities use this type"
+ )));
+ }
+ let res = sqlx::query("DELETE FROM entity_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
+ .bind(kb_id)
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::Conflict(
+ "Built-in types cannot be deleted".into(),
+ ));
+ }
+ Ok(())
+}
+
+/// 属性字段校验:attribute 必须有所属类和合法 datatype;relation 三者强制为空。
+fn validate_attribute_fields(
+ kind: &str,
+ domain_type_id: Option<Uuid>,
+ datatype: Option<&str>,
+) -> AppResult<()> {
+ match kind {
+ "relation" => Ok(()),
+ "attribute" => {
+ if domain_type_id.is_none() {
+ return Err(AppError::Validation(
+ "An attribute needs a class (domain)".into(),
+ ));
+ }
+ if !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
+ return Err(AppError::Validation(
+ "datatype must be text / number / date / bool".into(),
+ ));
+ }
+ Ok(())
+ }
+ _ => Err(AppError::Validation(
+ "kind must be relation / attribute".into(),
+ )),
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn create_relation_type(
+ pool: &PgPool,
+ kb_id: Uuid,
+ key: &str,
+ label: &str,
+ temporal: &str,
+ functional: bool,
+ inverse_functional: bool,
+ description: &str,
+ kind: &str,
+ domain_type_id: Option<Uuid>,
+ datatype: Option<&str>,
+ unit: Option<&str>,
+) -> AppResult<Uuid> {
+ validate_key(key)?;
+ if !matches!(temporal, "state" | "event" | "eternal") {
+ return Err(AppError::Validation(
+ "temporal must be state / event / eternal".into(),
+ ));
+ }
+ validate_attribute_fields(kind, domain_type_id, datatype)?;
+ let is_attr = kind == "attribute";
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO relation_types (id, kb_id, key, label, temporal, functional, inverse_functional, description,
+ kind, domain_type_id, datatype, unit)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(key)
+ .bind(label)
+ .bind(temporal)
+ .bind(functional)
+ .bind(inverse_functional)
+ .bind(description)
+ .bind(kind)
+ .bind(is_attr.then_some(domain_type_id).flatten())
+ .bind(is_attr.then_some(datatype).flatten())
+ .bind(is_attr.then_some(unit).flatten())
+ .execute(pool)
+ .await
+ .map_err(|e| match &e {
+ sqlx::Error::Database(db) if db.is_unique_violation() => {
+ AppError::Conflict(format!("Relation key '{key}' already exists"))
+ }
+ _ => AppError::Db(e),
+ })?;
+ Ok(id)
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn update_relation_type(
+ pool: &PgPool,
+ kb_id: Uuid,
+ id: Uuid,
+ label: &str,
+ temporal: &str,
+ functional: bool,
+ inverse_functional: bool,
+ description: &str,
+ datatype: Option<&str>,
+ unit: Option<&str>,
+) -> AppResult<()> {
+ if !matches!(temporal, "state" | "event" | "eternal") {
+ return Err(AppError::Validation(
+ "temporal must be state / event / eternal".into(),
+ ));
+ }
+ if datatype.is_some() && !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
+ return Err(AppError::Validation(
+ "datatype must be text / number / date / bool".into(),
+ ));
+ }
+ // kind 与 domain 不可变(改 kind 会让存量事实语义错乱;挪类=删了重建);
+ // datatype/unit 只对 attribute 行生效,datatype 缺省保持原值
+ let res = sqlx::query(
+ "UPDATE relation_types SET label = $3, temporal = $4, functional = $5, inverse_functional = $6, description = $7,
+ datatype = CASE WHEN kind = 'attribute' AND $8 IS NOT NULL THEN $8 ELSE datatype END,
+ unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END
+ WHERE id = $2 AND kb_id = $1",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .bind(label)
+ .bind(temporal)
+ .bind(functional)
+ .bind(inverse_functional)
+ .bind(description)
+ .bind(datatype)
+ .bind(unit)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+pub async fn delete_relation_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
+ let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM facts WHERE predicate_id = $1")
+ .bind(id)
+ .fetch_one(pool)
+ .await?;
+ if usage > 0 {
+ return Err(AppError::Conflict(format!(
+ "Cannot delete: {usage} facts use this relation"
+ )));
+ }
+ let res =
+ sqlx::query("DELETE FROM relation_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
+ .bind(kb_id)
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::Conflict(
+ "Built-in relations cannot be deleted".into(),
+ ));
+ }
+ Ok(())
+}
+
+/* ---- 未匹配统计 ---- */
+
+pub async fn record_miss(
+ pool: &PgPool,
+ kb_id: Uuid,
+ kind: &str,
+ key: &str,
+ example: Option<&str>,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO ontology_misses (kb_id, kind, key, example)
+ VALUES ($1, $2, left($3, 80), left($4, 200))
+ ON CONFLICT (kb_id, kind, key)
+ DO UPDATE SET count = ontology_misses.count + 1,
+ example = COALESCE(EXCLUDED.example, ontology_misses.example),
+ updated_at = now()",
+ )
+ .bind(kb_id)
+ .bind(kind)
+ .bind(key)
+ .bind(example)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn list_misses(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyMiss>> {
+ Ok(sqlx::query_as(
+ "SELECT kind, key, example, count FROM ontology_misses
+ WHERE kb_id = $1 ORDER BY count DESC, updated_at DESC LIMIT 50",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?)
+}
+
+pub async fn clear_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> AppResult<()> {
+ sqlx::query("DELETE FROM ontology_misses WHERE kb_id = $1 AND kind = $2 AND key = $3")
+ .bind(kb_id)
+ .bind(kind)
+ .bind(key)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
diff --git a/crates/utopia-store/src/resolution.rs b/crates/utopia-store/src/resolution.rs
new file mode 100644
index 00000000..9412e1a1
--- /dev/null
+++ b/crates/utopia-store/src/resolution.rs
@@ -0,0 +1,1353 @@
+//! 实体消解 v2:同名≠同人(设计见 DESIGN.md §4 实体消解 v2)。
+//!
+//! 漏斗:名字候选召回(免费,含泛用后缀词干互推)→ 画像向量相似度分层(毫秒,复用摄入阶段的 chunk embedding)
+//! → 灰区新建实体 + 疑似重复审核项(宁分勿合),LLM 攒批裁决在独立后台任务里跑,
+//! 人工终审兜底。LLM 永远不在抽取写入的关键路径上。
+//!
+//! 类型漂移:同名在同类型下无候选时再查其它类型(同一团队被抽成 organization/
+//! project/concept 是常态),按类型对的互斥强度分流——concept 兜底型当召回候选走
+//! 画像分层,易混具体类型照建实体但入队审核对,硬互斥(person vs organization)完全分开。
+
+use chrono::{DateTime, Utc};
+use pgvector::Vector;
+use sqlx::PgPool;
+use utopia_core::models::{MergeLogView, ReviewItem, ReviewSide};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// 上下文相似度阈值(bge-m3 类模型余弦相似度经验值,后续可调)。
+/// ≥ ATTACH 归并到既有实体;< NEW 判为不同实体;中间灰区宁分勿合 + 审核项。
+pub const SIM_ATTACH: f32 = 0.55;
+pub const SIM_NEW: f32 = 0.35;
+
+/// 名称规范化:全角 ASCII → 半角、全角空格 → 半角、空白折叠。
+/// 返回展示形态(保留大小写);匹配一律再套 SQL lower()。
+pub fn normalize_name(raw: &str) -> String {
+ let mapped: String = raw
+ .chars()
+ .map(|c| match c {
+ '\u{3000}' => ' ',
+ '\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c),
+ _ => c,
+ })
+ .collect();
+ mapped.split_whitespace().collect::<Vec<_>>().join(" ")
+}
+
+/// 泛用后缀词表:中文直接拼在词干后;英文按独立词算、首尾两种语序都认
+/// ("Phoenix Project" / "Project Phoenix")。只影响召回,判定仍走画像相似度。
+const GENERIC_SUFFIXES_CJK: &[&str] = &["项目", "公司", "集团", "部门", "团队"];
+const GENERIC_WORDS_EN: &[&str] = &["project", "corp", "inc", "team"];
+
+/// 词干:剥去一个泛用后缀后的 lower 形态。未命中、剥空、或词干本身就是
+/// 泛用词("项目团队")时返回 None。输入应已过 normalize_name。
+pub fn name_stem(name: &str) -> Option<String> {
+ let lower = name.to_lowercase();
+ let strip_punct = |w: &str| w.trim_end_matches(['.', ',']).to_string();
+ let generic = |s: &str| {
+ GENERIC_SUFFIXES_CJK.contains(&s) || GENERIC_WORDS_EN.contains(&strip_punct(s).as_str())
+ };
+ for suf in GENERIC_SUFFIXES_CJK {
+ if let Some(stem) = lower.strip_suffix(suf) {
+ let stem = stem.trim_end();
+ if !stem.is_empty() && !generic(stem) {
+ return Some(stem.to_string());
+ }
+ }
+ }
+ let words: Vec<&str> = lower.split(' ').collect();
+ if words.len() >= 2 {
+ if generic(words[words.len() - 1]) {
+ let stem = words[..words.len() - 1].join(" ");
+ if !generic(&stem) {
+ return Some(stem);
+ }
+ }
+ if generic(words[0]) {
+ let stem = words[1..].join(" ");
+ if !generic(&stem) {
+ return Some(stem);
+ }
+ }
+ }
+ None
+}
+
+/// mention 的召回键集合(全 lower):本名 + 词干 + 词干的泛用后缀增广。
+/// 增广覆盖反方向(库内是"星尘项目"、mention 只说"星尘");词干含 CJK 拼中文
+/// 尾缀,否则拼英文词(两种语序)。键数 ≤10,走 (kb,type,lower(name)) 索引多点查。
+pub fn recall_keys(name: &str) -> Vec<String> {
+ let lower = name.to_lowercase();
+ let base = name_stem(name).unwrap_or_else(|| lower.clone());
+ let mut keys = vec![lower];
+ fn add(keys: &mut Vec<String>, k: String) {
+ if !keys.contains(&k) {
+ keys.push(k);
+ }
+ }
+ add(&mut keys, base.clone());
+ if base.chars().any(|c| ('\u{4E00}'..='\u{9FFF}').contains(&c)) {
+ for suf in GENERIC_SUFFIXES_CJK {
+ add(&mut keys, format!("{base}{suf}"));
+ }
+ } else {
+ for w in GENERIC_WORDS_EN {
+ add(&mut keys, format!("{base} {w}"));
+ add(&mut keys, format!("{w} {base}"));
+ }
+ }
+ keys
+}
+
+// ---------------------------------------------------------------------------
+// 类型漂移:同名实体被抽成了不同类型("Orion platform team" ↔ organization/project/concept)
+// ---------------------------------------------------------------------------
+
+/// 抽取兜底类型:白名单外类型与漏报的主宾都降级到 concept(见 extraction),
+/// 因此 concept ↔ 具体类型 的同名大概率是同一实体的类型漂移,按召回候选参与画像分层。
+pub const FALLBACK_TYPE_KEY: &str = "concept";
+
+/// 易混具体类型:抽取常在这几类间摇摆(一个团队算组织还是项目?平台算项目还是产品?)。
+/// 同名跨这组类型 → 照建实体(宁分勿合),但入队审核对交 LLM/人工裁决。
+/// DESIGN.md §3.2 的 disjoint 公理目前只是设计面(0005 仅落了 subClassOf 数据面),
+/// 公理落库后这张表应改从本体读取。
+pub const CONFUSABLE_TYPE_KEYS: &[&str] = &["organization", "project", "product"];
+
+/// 单次消解最多入队的漂移审核对(防同名大组刷爆审核队列)。
+const MAX_DRIFT_REVIEWS: usize = 4;
+
+/// 跨类型同名的处置分类。
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum TypeDrift {
+ /// 一侧是兜底类型:当召回候选,走画像相似度分层(可 ATTACH)
+ Recall,
+ /// 两个易混具体类型:新建 + 审核对
+ Review,
+ /// 硬互斥(person vs organization 等,含未知自定义类型):完全分开
+ Disjoint,
+}
+
+fn classify_type_drift(a: &str, b: &str) -> TypeDrift {
+ if a == FALLBACK_TYPE_KEY || b == FALLBACK_TYPE_KEY {
+ return TypeDrift::Recall;
+ }
+ if CONFUSABLE_TYPE_KEYS.contains(&a) && CONFUSABLE_TYPE_KEYS.contains(&b) {
+ return TypeDrift::Review;
+ }
+ TypeDrift::Disjoint
+}
+
+fn cosine(a: &[f32], b: &[f32]) -> Option<f32> {
+ if a.len() != b.len() || a.is_empty() {
+ return None;
+ }
+ let (mut dot, mut na, mut nb) = (0f32, 0f32, 0f32);
+ for (x, y) in a.iter().zip(b) {
+ dot += x * y;
+ na += x * x;
+ nb += y * y;
+ }
+ if na == 0.0 || nb == 0.0 {
+ return None;
+ }
+ Some(dot / (na.sqrt() * nb.sqrt()))
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct Candidate {
+ id: Uuid,
+ profile_embedding: Option<Vector>,
+ profile_n: i32,
+ degree: i64,
+}
+
+/// 消解结果:mention 落到了哪个实体;附带需要入队的疑似重复审核对
+/// (同名灰区 / 类型漂移),由调用方写入审核队列并触发裁决任务。
+#[derive(Debug)]
+pub struct Resolution {
+ pub entity_id: Uuid,
+ pub created: bool,
+ pub reviews: Vec<ReviewRequest>,
+}
+
+/// 待入队的审核对:`Resolution::entity_id` vs `other_id`。
+#[derive(Debug)]
+pub struct ReviewRequest {
+ pub other_id: Uuid,
+ pub score: f32,
+ pub reason: String,
+}
+
+/// 单条 mention 消解。`context` 为 mention 所在分块的向量(无 embedding 模型时为 None,
+/// 退化为 v1 行为:同名归并到事实最多的候选)。
+pub async fn resolve_mention(
+ pool: &PgPool,
+ kb_id: Uuid,
+ type_id: Uuid,
+ raw_name: &str,
+ context: Option<&[f32]>,
+) -> AppResult<Resolution> {
+ let name = normalize_name(raw_name);
+ // 召回键 = 本名 + 泛用后缀词干及其增广("星尘"↔"星尘项目"互为候选)。
+ // 只扩召回,归并与否仍由下方画像相似度分层定夺。
+ let keys = recall_keys(&name);
+ let candidates: Vec<Candidate> = sqlx::query_as(
+ "SELECT e.id, e.profile_embedding, e.profile_n,
+ (SELECT count(*) FROM facts f
+ WHERE (f.subject_id = e.id OR f.object_id = e.id)
+ AND f.invalidated_at IS NULL) AS degree
+ FROM entities e
+ WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL
+ AND (lower(e.canonical_name) = ANY($3)
+ OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($3)))",
+ )
+ .bind(kb_id)
+ .bind(type_id)
+ .bind(&keys)
+ .fetch_all(pool)
+ .await?;
+
+ if candidates.is_empty() {
+ // 同类型无候选 ≠ 新名字:类型标签会漂(同一团队被抽成 organization/project/
+ // concept),先查其它类型下的同名实体,按类型对的互斥强度分流。
+ return resolve_type_drift(pool, kb_id, type_id, &name, &keys, context).await;
+ }
+
+ let Some(ctx) = context else {
+ // 无向量可比:v1 兼容 —— 归并到事实最多的同名候选
+ let best = candidates
+ .iter()
+ .max_by_key(|c| c.degree)
+ .expect("non-empty");
+ touch_entity(pool, best.id).await?;
+ return Ok(Resolution {
+ entity_id: best.id,
+ created: false,
+ reviews: Vec::new(),
+ });
+ };
+
+ // 有画像的候选算相似度;无画像(历史数据/无 embedding 期创建)单独归类
+ let mut best_scored: Option<(&Candidate, f32)> = None;
+ let mut unprofiled: Option<&Candidate> = None;
+ for c in &candidates {
+ match c
+ .profile_embedding
+ .as_ref()
+ .and_then(|p| cosine(p.as_slice(), ctx))
+ {
+ Some(sim) => {
+ if best_scored.map(|(_, s)| sim > s).unwrap_or(true) {
+ best_scored = Some((c, sim));
+ }
+ }
+ None => {
+ if unprofiled.map(|u| c.degree > u.degree).unwrap_or(true) {
+ unprofiled = Some(c);
+ }
+ }
+ }
+ }
+
+ if let Some((best, sim)) = best_scored {
+ if sim >= SIM_ATTACH {
+ update_profile(pool, best.id, best.profile_n, ctx).await?;
+ return Ok(Resolution {
+ entity_id: best.id,
+ created: false,
+ reviews: Vec::new(),
+ });
+ }
+ }
+ if let Some(c) = unprofiled {
+ // 无画像候选无从判别:v1 兼容归并,并用本次上下文初始化画像
+ update_profile(pool, c.id, c.profile_n, ctx).await?;
+ return Ok(Resolution {
+ entity_id: c.id,
+ created: false,
+ reviews: Vec::new(),
+ });
+ }
+
+ // 走到这里:所有候选都有画像且最高分 < ATTACH → 新建实体(同名不同人)
+ let id = create_entity(pool, kb_id, type_id, &name, context).await?;
+ refresh_disambiguators(pool, kb_id, &name).await?;
+ let reviews = best_scored
+ .filter(|(_, sim)| *sim >= SIM_NEW)
+ .map(|(c, sim)| {
+ vec![ReviewRequest {
+ other_id: c.id,
+ score: sim,
+ reason: format!("ambiguous name match (context similarity {sim:.2})"),
+ }]
+ })
+ .unwrap_or_default();
+ Ok(Resolution {
+ entity_id: id,
+ created: true,
+ reviews,
+ })
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct CrossCandidate {
+ id: Uuid,
+ canonical_name: String,
+ type_key: String,
+ profile_embedding: Option<Vector>,
+ profile_n: i32,
+}
+
+fn drift_reason(mention_key: &str, other_key: &str, sim: Option<f32>) -> String {
+ match sim {
+ Some(s) => format!("type drift: {mention_key} vs {other_key} (context similarity {s:.2})"),
+ None => {
+ format!("type drift: {mention_key} vs {other_key} (same name, no context to compare)")
+ }
+ }
+}
+
+fn confusable_reviews(
+ mention_key: &str,
+ cands: &[&CrossCandidate],
+ ctx: Option<&[f32]>,
+) -> Vec<ReviewRequest> {
+ cands
+ .iter()
+ .map(|c| {
+ let sim = ctx.and_then(|x| {
+ c.profile_embedding
+ .as_ref()
+ .and_then(|p| cosine(p.as_slice(), x))
+ });
+ ReviewRequest {
+ other_id: c.id,
+ score: sim.unwrap_or(0.0),
+ reason: drift_reason(mention_key, &c.type_key, sim),
+ }
+ })
+ .collect()
+}
+
+/// 同类型召回为空时的跨类型处置(类型漂移)。
+/// concept 兜底型候选跑既有画像分层:高相似直接 ATTACH(漂移的召回修复,concept
+/// 侧类型升格为具体类型),灰区/无从判别 → 宁分勿合新建 + 审核对;易混具体类型
+/// 一律新建 + 审核对(同名 + 类型摇摆本身就是信号,不设相似度门槛);硬互斥忽略。
+async fn resolve_type_drift(
+ pool: &PgPool,
+ kb_id: Uuid,
+ type_id: Uuid,
+ name: &str,
+ keys: &[String],
+ context: Option<&[f32]>,
+) -> AppResult<Resolution> {
+ let (mention_key,): (String,) = sqlx::query_as("SELECT key FROM entity_types WHERE id = $1")
+ .bind(type_id)
+ .fetch_one(pool)
+ .await?;
+ let cross: Vec<CrossCandidate> = sqlx::query_as(
+ "SELECT e.id, e.canonical_name, t.key AS type_key, e.profile_embedding, e.profile_n
+ FROM entities e JOIN entity_types t ON t.id = e.type_id
+ WHERE e.kb_id = $1 AND e.type_id <> $2 AND e.merged_into IS NULL
+ AND (lower(e.canonical_name) = ANY($3)
+ OR EXISTS (SELECT 1 FROM unnest(e.aliases) a WHERE lower(a) = ANY($3)))",
+ )
+ .bind(kb_id)
+ .bind(type_id)
+ .bind(keys)
+ .fetch_all(pool)
+ .await?;
+
+ let mut recall_cands: Vec<&CrossCandidate> = Vec::new();
+ let mut review_cands: Vec<&CrossCandidate> = Vec::new();
+ for c in &cross {
+ match classify_type_drift(&mention_key, &c.type_key) {
+ TypeDrift::Recall => recall_cands.push(c),
+ TypeDrift::Review => review_cands.push(c),
+ TypeDrift::Disjoint => {}
+ }
+ }
+
+ if let Some(ctx) = context {
+ let best = recall_cands
+ .iter()
+ .filter_map(|c| {
+ c.profile_embedding
+ .as_ref()
+ .and_then(|p| cosine(p.as_slice(), ctx))
+ .map(|sim| (*c, sim))
+ })
+ .max_by(|a, b| a.1.total_cmp(&b.1));
+ if let Some((best, sim)) = best {
+ if sim >= SIM_ATTACH {
+ update_profile(pool, best.id, best.profile_n, ctx).await?;
+ if best.type_key == FALLBACK_TYPE_KEY && mention_key != FALLBACK_TYPE_KEY {
+ // concept 只是"没认出来",具体类型是更强的判断 → 升格。
+ // 不是合并(没有第二个实体),不入 entity_merges;本体页可手工改回。
+ sqlx::query(
+ "UPDATE entities SET type_id = $2, updated_at = now() WHERE id = $1",
+ )
+ .bind(best.id)
+ .bind(type_id)
+ .execute(pool)
+ .await?;
+ // 类型标签兜底的消歧后缀可能已过时
+ refresh_disambiguators(pool, kb_id, &best.canonical_name).await?;
+ }
+ // mention 已定居到召回实体;同名易混类型实体的疑点仍在 → 照常入队
+ let mut reviews = confusable_reviews(&mention_key, &review_cands, Some(ctx));
+ reviews.truncate(MAX_DRIFT_REVIEWS);
+ return Ok(Resolution {
+ entity_id: best.id,
+ created: false,
+ reviews,
+ });
+ }
+ }
+ }
+
+ let id = create_entity(pool, kb_id, type_id, name, context).await?;
+ if !cross.is_empty() {
+ // 跨类型同名并存:消歧后缀按名字分组(不分类型),需要刷新
+ refresh_disambiguators(pool, kb_id, name).await?;
+ }
+ let mut reviews = confusable_reviews(&mention_key, &review_cands, context);
+ for c in &recall_cands {
+ let sim = context.and_then(|ctx| {
+ c.profile_embedding
+ .as_ref()
+ .and_then(|p| cosine(p.as_slice(), ctx))
+ });
+ match sim {
+ // 画像明确不像:完全分开,不打扰审核队列
+ Some(s) if s < SIM_NEW => {}
+ // 灰区或无从判别(无 embedding / 候选无画像):宁分勿合 + 审核对
+ _ => reviews.push(ReviewRequest {
+ other_id: c.id,
+ score: sim.unwrap_or(0.0),
+ reason: drift_reason(&mention_key, &c.type_key, sim),
+ }),
+ }
+ }
+ reviews.truncate(MAX_DRIFT_REVIEWS);
+ Ok(Resolution {
+ entity_id: id,
+ created: true,
+ reviews,
+ })
+}
+
+async fn create_entity(
+ pool: &PgPool,
+ kb_id: Uuid,
+ type_id: Uuid,
+ name: &str,
+ context: Option<&[f32]>,
+) -> AppResult<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entities (id, kb_id, type_id, canonical_name, profile_embedding, profile_n)
+ VALUES ($1, $2, $3, $4, $5, $6)",
+ )
+ .bind(id)
+ .bind(kb_id)
+ .bind(type_id)
+ .bind(name)
+ .bind(context.map(|c| Vector::from(c.to_vec())))
+ .bind(i32::from(context.is_some()))
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+async fn touch_entity(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ sqlx::query("UPDATE entities SET updated_at = now() WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 画像增量质心:profile ← (profile·n + ctx) / (n+1)。
+/// 维度不匹配(换过 embedding 模型)时用新向量重置画像。
+async fn update_profile(pool: &PgPool, id: Uuid, n: i32, ctx: &[f32]) -> AppResult<()> {
+ let existing: Option<(Option<Vector>,)> =
+ sqlx::query_as("SELECT profile_embedding FROM entities WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?;
+ let old = existing.and_then(|(v,)| v);
+ let (new_vec, new_n) = match old {
+ Some(p) if p.as_slice().len() == ctx.len() && n > 0 => {
+ let nf = n as f32;
+ let merged: Vec<f32> = p
+ .as_slice()
+ .iter()
+ .zip(ctx)
+ .map(|(a, b)| (a * nf + b) / (nf + 1.0))
+ .collect();
+ (merged, n + 1)
+ }
+ _ => (ctx.to_vec(), 1),
+ };
+ sqlx::query(
+ "UPDATE entities SET profile_embedding = $2, profile_n = $3, updated_at = now()
+ WHERE id = $1",
+ )
+ .bind(id)
+ .bind(Vector::from(new_vec))
+ .bind(new_n)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 同名组展示消歧:组内 ≥2 个存活实体时,各自取最强区分性事实
+/// (works_at/part_of/located_in/leads 的宾语名),否则退回类型标签;组内唯一则清空。
+pub async fn refresh_disambiguators(pool: &PgPool, kb_id: Uuid, name: &str) -> AppResult<()> {
+ let group: Vec<(Uuid,)> = sqlx::query_as(
+ "SELECT id FROM entities
+ WHERE kb_id = $1 AND merged_into IS NULL AND lower(canonical_name) = lower($2)",
+ )
+ .bind(kb_id)
+ .bind(name)
+ .fetch_all(pool)
+ .await?;
+
+ if group.len() < 2 {
+ for (id,) in &group {
+ sqlx::query("UPDATE entities SET disambiguator = NULL WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ }
+ return Ok(());
+ }
+
+ for (id,) in &group {
+ let label: Option<(String,)> = sqlx::query_as(
+ "SELECT o.canonical_name FROM facts f
+ JOIN relation_types r ON r.id = f.predicate_id
+ JOIN entities o ON o.id = f.object_id
+ WHERE f.kb_id = $1 AND f.subject_id = $2
+ AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
+ AND r.key IN ('works_at', 'part_of', 'located_in', 'leads')
+ ORDER BY (r.key = 'works_at') DESC, f.confidence DESC, f.recorded_at DESC
+ LIMIT 1",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .fetch_optional(pool)
+ .await?;
+ let disambiguator = match label {
+ Some((l,)) => l,
+ None => {
+ let (type_label,): (String,) = sqlx::query_as(
+ "SELECT t.label FROM entities e JOIN entity_types t ON t.id = e.type_id
+ WHERE e.id = $1",
+ )
+ .bind(id)
+ .fetch_one(pool)
+ .await?;
+ type_label
+ }
+ };
+ sqlx::query("UPDATE entities SET disambiguator = $2 WHERE id = $1")
+ .bind(id)
+ .bind(disambiguator)
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// 审核队列
+// ---------------------------------------------------------------------------
+
+/// 灰区疑似重复对入队(同一 pending 对幂等)。
+pub async fn create_review(
+ pool: &PgPool,
+ kb_id: Uuid,
+ left_id: Uuid,
+ right_id: Uuid,
+ score: f32,
+ reason: &str,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO resolution_reviews (id, kb_id, left_id, right_id, score, reason)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (kb_id, least(left_id, right_id), greatest(left_id, right_id))
+ WHERE status = 'pending'
+ DO NOTHING",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(left_id)
+ .bind(right_id)
+ .bind(score)
+ .bind(reason)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct ReviewRow {
+ id: Uuid,
+ left_id: Uuid,
+ right_id: Uuid,
+ score: f32,
+ reason: Option<String>,
+ stage: String,
+ created_at: DateTime<Utc>,
+}
+
+async fn review_side(pool: &PgPool, kb_id: Uuid, entity_id: Uuid) -> AppResult<ReviewSide> {
+ #[derive(sqlx::FromRow)]
+ struct SideRow {
+ id: Uuid,
+ name: String,
+ type_label: String,
+ color: String,
+ disambiguator: Option<String>,
+ degree: i64,
+ }
+ let row: SideRow = sqlx::query_as(
+ "SELECT e.id, e.canonical_name AS name, t.label AS type_label, t.color, e.disambiguator,
+ (SELECT count(*) FROM facts f
+ WHERE (f.subject_id = e.id OR f.object_id = e.id)
+ AND f.invalidated_at IS NULL) AS degree
+ FROM entities e JOIN entity_types t ON t.id = e.type_id
+ WHERE e.kb_id = $1 AND e.id = $2",
+ )
+ .bind(kb_id)
+ .bind(entity_id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)?;
+
+ Ok(ReviewSide {
+ id: row.id,
+ name: row.name,
+ type_label: row.type_label,
+ color: row.color,
+ disambiguator: row.disambiguator,
+ degree: row.degree,
+ top_facts: entity_fact_lines(pool, kb_id, entity_id, 4).await?,
+ })
+}
+
+/// 实体的事实摘要行:"works at → 星云科技 (2023-01 → now)",裁决 prompt 与审核 UI 共用。
+pub async fn entity_fact_lines(
+ pool: &PgPool,
+ kb_id: Uuid,
+ entity_id: Uuid,
+ limit: i64,
+) -> AppResult<Vec<String>> {
+ #[derive(sqlx::FromRow)]
+ struct Line {
+ direction: String,
+ predicate_label: String,
+ other_name: Option<String>,
+ valid_from: Option<DateTime<Utc>>,
+ valid_to: Option<DateTime<Utc>>,
+ }
+ let rows: Vec<Line> = sqlx::query_as(
+ "SELECT CASE WHEN f.subject_id = $2 THEN 'out' ELSE 'in' END AS direction,
+ r.label AS predicate_label, o.canonical_name AS other_name,
+ f.valid_from, f.valid_to
+ FROM facts f
+ JOIN relation_types r ON r.id = f.predicate_id
+ LEFT JOIN entities o
+ ON o.id = CASE WHEN f.subject_id = $2 THEN f.object_id ELSE f.subject_id END
+ WHERE f.kb_id = $1 AND f.invalidated_at IS NULL
+ AND (f.subject_id = $2 OR f.object_id = $2)
+ ORDER BY f.confidence DESC, f.recorded_at DESC
+ LIMIT $3",
+ )
+ .bind(kb_id)
+ .bind(entity_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|l| {
+ let other = l.other_name.unwrap_or_else(|| "?".into());
+ let core = if l.direction == "out" {
+ format!("{} → {}", l.predicate_label, other)
+ } else {
+ format!("{} ← {}", l.predicate_label, other)
+ };
+ match (l.valid_from, l.valid_to) {
+ (Some(f), Some(t)) => {
+ format!("{core} ({} → {})", f.format("%Y-%m"), t.format("%Y-%m"))
+ }
+ (Some(f), None) => format!("{core} ({} → now)", f.format("%Y-%m")),
+ _ => core,
+ }
+ })
+ .collect())
+}
+
+async fn assemble_reviews(
+ pool: &PgPool,
+ kb_id: Uuid,
+ rows: Vec<ReviewRow>,
+) -> AppResult<Vec<ReviewItem>> {
+ let mut items = Vec::with_capacity(rows.len());
+ for r in rows {
+ items.push(ReviewItem {
+ id: r.id,
+ score: r.score,
+ reason: r.reason,
+ stage: r.stage,
+ created_at: r.created_at,
+ left: review_side(pool, kb_id, r.left_id).await?,
+ right: review_side(pool, kb_id, r.right_id).await?,
+ });
+ }
+ Ok(items)
+}
+
+/// 全部待处理审核项(LLM 裁决中 + 等人工的都展示,人工可随时抢先定夺)。
+pub async fn list_reviews(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ReviewItem>> {
+ let rows: Vec<ReviewRow> = sqlx::query_as(
+ "SELECT id, left_id, right_id, score, reason, stage, created_at
+ FROM resolution_reviews
+ WHERE kb_id = $1 AND status = 'pending'
+ ORDER BY created_at DESC LIMIT 100",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ assemble_reviews(pool, kb_id, rows).await
+}
+
+/// 等待 LLM 裁决的审核项(后台裁决任务消费)。
+pub async fn pending_adjudications(
+ pool: &PgPool,
+ kb_id: Uuid,
+ limit: i64,
+) -> AppResult<Vec<ReviewItem>> {
+ let rows: Vec<ReviewRow> = sqlx::query_as(
+ "SELECT id, left_id, right_id, score, reason, stage, created_at
+ FROM resolution_reviews
+ WHERE kb_id = $1 AND status = 'pending' AND stage = 'adjudicating'
+ ORDER BY created_at LIMIT $2",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ assemble_reviews(pool, kb_id, rows).await
+}
+
+/// LLM 不确定 / 未配模型 → 转人工。
+pub async fn escalate_review(pool: &PgPool, review_id: Uuid, reason: &str) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE resolution_reviews SET stage = 'human', reason = $2
+ WHERE id = $1 AND status = 'pending'",
+ )
+ .bind(review_id)
+ .bind(reason)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 自动定夺(LLM 高置信):merged / kept。合并动作本身由调用方先执行。
+pub async fn close_review_auto(
+ pool: &PgPool,
+ review_id: Uuid,
+ status: &str,
+ reason: &str,
+) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE resolution_reviews SET status = $2, reason = $3, decided_at = now()
+ WHERE id = $1 AND status = 'pending'",
+ )
+ .bind(review_id)
+ .bind(status)
+ .bind(reason)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 人工定夺。merge 方向:度数高(事实多)的一方作为存活目标,平局取更早创建的。
+pub async fn decide_review(
+ pool: &PgPool,
+ kb_id: Uuid,
+ review_id: Uuid,
+ action: &str,
+ user_id: Uuid,
+) -> AppResult<()> {
+ let row: Option<ReviewRow> = sqlx::query_as(
+ "SELECT id, left_id, right_id, score, reason, stage, created_at
+ FROM resolution_reviews WHERE id = $1 AND kb_id = $2 AND status = 'pending'",
+ )
+ .bind(review_id)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?;
+ let row = row.ok_or(AppError::NotFound)?;
+
+ match action {
+ "merge" => {
+ let (target, source) = merge_direction(pool, row.left_id, row.right_id).await?;
+ merge_entities(
+ pool,
+ kb_id,
+ source,
+ target,
+ Some(user_id),
+ "review decision",
+ )
+ .await?;
+ sqlx::query(
+ "UPDATE resolution_reviews SET status = 'merged', decided_at = now(), decided_by = $2
+ WHERE id = $1",
+ )
+ .bind(review_id)
+ .bind(user_id)
+ .execute(pool)
+ .await?;
+ }
+ "keep" => {
+ sqlx::query(
+ "UPDATE resolution_reviews SET status = 'kept', decided_at = now(), decided_by = $2
+ WHERE id = $1",
+ )
+ .bind(review_id)
+ .bind(user_id)
+ .execute(pool)
+ .await?;
+ }
+ _ => return Err(AppError::Validation("action must be merge or keep".into())),
+ }
+ Ok(())
+}
+
+/// 合并方向:返回 (target 存活, source 被并)。
+pub async fn merge_direction(pool: &PgPool, a: Uuid, b: Uuid) -> AppResult<(Uuid, Uuid)> {
+ let (deg_a,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM facts WHERE (subject_id = $1 OR object_id = $1) AND invalidated_at IS NULL",
+ )
+ .bind(a)
+ .fetch_one(pool)
+ .await?;
+ let (deg_b,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM facts WHERE (subject_id = $1 OR object_id = $1) AND invalidated_at IS NULL",
+ )
+ .bind(b)
+ .fetch_one(pool)
+ .await?;
+ // uuidv7 时间有序:度数平局时更早创建的一方存活
+ Ok(if deg_a > deg_b || (deg_a == deg_b && a < b) {
+ (a, b)
+ } else {
+ (b, a)
+ })
+}
+
+// ---------------------------------------------------------------------------
+// 合并 / 回滚
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, sqlx::FromRow)]
+struct EntityFull {
+ type_id: Uuid,
+ canonical_name: String,
+ aliases: Vec<String>,
+ profile_embedding: Option<Vector>,
+ profile_n: i32,
+ merged_into: Option<Uuid>,
+}
+
+async fn entity_full(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<EntityFull> {
+ sqlx::query_as(
+ "SELECT type_id, canonical_name, aliases, profile_embedding, profile_n, merged_into
+ FROM entities WHERE kb_id = $1 AND id = $2",
+ )
+ .bind(kb_id)
+ .bind(id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+/// 合并 source → target:事实改挂 target、互指事实与合并后的重复事实作废、
+/// source 名并入 target 别名、画像加权合并、source 标记 merged_into。全程记日志可回滚。
+pub async fn merge_entities(
+ pool: &PgPool,
+ kb_id: Uuid,
+ source_id: Uuid,
+ target_id: Uuid,
+ merged_by: Option<Uuid>,
+ reason: &str,
+) -> AppResult<Uuid> {
+ if source_id == target_id {
+ return Err(AppError::Validation(
+ "Cannot merge an entity into itself".into(),
+ ));
+ }
+ let source = entity_full(pool, kb_id, source_id).await?;
+ let target = entity_full(pool, kb_id, target_id).await?;
+ if source.merged_into.is_some() || target.merged_into.is_some() {
+ return Err(AppError::Conflict("Entity already merged".into()));
+ }
+
+ let mut tx = pool.begin().await?;
+
+ // 互指事实(合并后变自环)→ 作废
+ let cross: Vec<(Uuid,)> = sqlx::query_as(
+ "UPDATE facts SET invalidated_at = now()
+ WHERE kb_id = $1 AND invalidated_at IS NULL
+ AND ((subject_id = $2 AND object_id = $3) OR (subject_id = $3 AND object_id = $2))
+ RETURNING id",
+ )
+ .bind(kb_id)
+ .bind(source_id)
+ .bind(target_id)
+ .fetch_all(&mut *tx)
+ .await?;
+ let mut invalidated: Vec<Uuid> = cross.into_iter().map(|(id,)| id).collect();
+
+ let moved_subject: Vec<Uuid> = sqlx::query_as::<_, (Uuid,)>(
+ "UPDATE facts SET subject_id = $2 WHERE kb_id = $3 AND subject_id = $1 RETURNING id",
+ )
+ .bind(source_id)
+ .bind(target_id)
+ .bind(kb_id)
+ .fetch_all(&mut *tx)
+ .await?
+ .into_iter()
+ .map(|(id,)| id)
+ .collect();
+ let moved_object: Vec<Uuid> = sqlx::query_as::<_, (Uuid,)>(
+ "UPDATE facts SET object_id = $2 WHERE kb_id = $3 AND object_id = $1 RETURNING id",
+ )
+ .bind(source_id)
+ .bind(target_id)
+ .bind(kb_id)
+ .fetch_all(&mut *tx)
+ .await?
+ .into_iter()
+ .map(|(id,)| id)
+ .collect();
+
+ // 合并后 SPO+valid_from 重复的 live 事实:留最早 recorded_at 的一条,其余作废
+ let dups: Vec<(Vec<Uuid>,)> = sqlx::query_as(
+ "SELECT (array_agg(id ORDER BY recorded_at))[2:] FROM facts
+ WHERE kb_id = $1 AND invalidated_at IS NULL
+ AND (subject_id = $2 OR object_id = $2)
+ GROUP BY subject_id, predicate_id, object_id, valid_from
+ HAVING count(*) > 1",
+ )
+ .bind(kb_id)
+ .bind(target_id)
+ .fetch_all(&mut *tx)
+ .await?;
+ let dup_ids: Vec<Uuid> = dups.into_iter().flat_map(|(ids,)| ids).collect();
+ if !dup_ids.is_empty() {
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = ANY($1)")
+ .bind(&dup_ids)
+ .execute(&mut *tx)
+ .await?;
+ invalidated.extend(dup_ids);
+ }
+
+ // source 名与别名并入 target 别名(去重、排除 target 本名)
+ let mut aliases = target.aliases.clone();
+ let taken: std::collections::HashSet<String> = std::iter::once(&target.canonical_name)
+ .chain(aliases.iter())
+ .map(|s| s.to_lowercase())
+ .collect();
+ for a in std::iter::once(&source.canonical_name).chain(source.aliases.iter()) {
+ if !taken.contains(&a.to_lowercase()) && !aliases.iter().any(|x| x.eq_ignore_ascii_case(a))
+ {
+ aliases.push(a.clone());
+ }
+ }
+
+ // 画像加权合并
+ let (profile, profile_n) = match (&target.profile_embedding, &source.profile_embedding) {
+ (Some(t), Some(s)) if t.as_slice().len() == s.as_slice().len() => {
+ let (nt, ns) = (
+ target.profile_n.max(1) as f32,
+ source.profile_n.max(1) as f32,
+ );
+ let merged: Vec<f32> = t
+ .as_slice()
+ .iter()
+ .zip(s.as_slice())
+ .map(|(a, b)| (a * nt + b * ns) / (nt + ns))
+ .collect();
+ (
+ Some(Vector::from(merged)),
+ target.profile_n + source.profile_n,
+ )
+ }
+ (Some(t), _) => (Some(t.clone()), target.profile_n),
+ (None, Some(s)) => (Some(s.clone()), source.profile_n),
+ (None, None) => (None, 0),
+ };
+
+ // 类型调和:concept 是抽取兜底而非类型判断,被并侧带具体类型时目标升格;
+ // 两个具体类型相并(易混对被裁"same")保留 target(存活方)的类型。
+ let concept_type: Option<Uuid> =
+ sqlx::query_as::<_, (Uuid,)>("SELECT id FROM entity_types WHERE kb_id = $1 AND key = $2")
+ .bind(kb_id)
+ .bind(FALLBACK_TYPE_KEY)
+ .fetch_optional(&mut *tx)
+ .await?
+ .map(|(id,)| id);
+ let new_type_id =
+ if concept_type == Some(target.type_id) && concept_type != Some(source.type_id) {
+ source.type_id
+ } else {
+ target.type_id
+ };
+
+ sqlx::query(
+ "UPDATE entities SET aliases = $2, profile_embedding = $3, profile_n = $4,
+ type_id = $5, updated_at = now() WHERE id = $1",
+ )
+ .bind(target_id)
+ .bind(&aliases)
+ .bind(&profile)
+ .bind(profile_n)
+ .bind(new_type_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE entities SET merged_into = $2, updated_at = now() WHERE id = $1")
+ .bind(source_id)
+ .bind(target_id)
+ .execute(&mut *tx)
+ .await?;
+
+ // 其余涉及 source 的 pending 审核项关闭(合并后过时;疑点若仍在会由后续 mention 重新提起)。
+ // (source, target) 这一对本身除外——它正是本次合并的裁决对象,由调用方标记 merged,
+ // 在这里扫掉会让它在历史里错误地显示为"保持分开"
+ sqlx::query(
+ "UPDATE resolution_reviews
+ SET status = 'kept', reason = 'superseded by merge', decided_at = now()
+ WHERE kb_id = $1 AND status = 'pending' AND (left_id = $2 OR right_id = $2)
+ AND NOT (least(left_id, right_id) = least($2, $3)
+ AND greatest(left_id, right_id) = greatest($2, $3))",
+ )
+ .bind(kb_id)
+ .bind(source_id)
+ .bind(target_id)
+ .execute(&mut *tx)
+ .await?;
+
+ let merge_id = Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO entity_merges (id, kb_id, source_id, target_id,
+ moved_subject_facts, moved_object_facts, invalidated_facts,
+ target_profile_before, target_profile_n_before, target_type_before,
+ merged_by, reason)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
+ )
+ .bind(merge_id)
+ .bind(kb_id)
+ .bind(source_id)
+ .bind(target_id)
+ .bind(&moved_subject)
+ .bind(&moved_object)
+ .bind(&invalidated)
+ .bind(&target.profile_embedding)
+ .bind(target.profile_n)
+ .bind(target.type_id)
+ .bind(merged_by)
+ .bind(reason)
+ .execute(&mut *tx)
+ .await?;
+
+ tx.commit().await?;
+
+ // 搬移后的时态对账:换了主/宾的事实等价于新观察落库——两个对象折成一个后,
+ // 唯一性不变量才第一次看得到旧开放区间与继任者相撞(如"星尘"并入"星尘项目",
+ // 旧负责人的 leads 应在新任起点闭合)。
+ // 修正行 id 记入合并账本:这些修正的唯一成因是本次合并,回滚时必须随之撤销。
+ // 注:本步在事务外,失败有自愈性——残留的旧开放行会在下一条相关新事实落库时
+ // 被常规插入对账撞到并闭合。
+ let moved_all: Vec<Uuid> = moved_subject
+ .iter()
+ .chain(moved_object.iter())
+ .copied()
+ .collect();
+ let report = crate::temporal::reconcile_moved_facts(pool, kb_id, &moved_all).await?;
+ if !report.corrected.is_empty() {
+ sqlx::query("UPDATE entity_merges SET temporal_corrections = $2 WHERE id = $1")
+ .bind(merge_id)
+ .bind(&report.corrected)
+ .execute(pool)
+ .await?;
+ }
+
+ refresh_disambiguators(pool, kb_id, &source.canonical_name).await?;
+ if !source
+ .canonical_name
+ .eq_ignore_ascii_case(&target.canonical_name)
+ {
+ refresh_disambiguators(pool, kb_id, &target.canonical_name).await?;
+ }
+ Ok(merge_id)
+}
+
+#[derive(Debug, sqlx::FromRow)]
+struct MergeRow {
+ source_id: Uuid,
+ target_id: Uuid,
+ moved_subject_facts: Vec<Uuid>,
+ moved_object_facts: Vec<Uuid>,
+ invalidated_facts: Vec<Uuid>,
+ temporal_corrections: Vec<Uuid>,
+ target_profile_before: Option<Vector>,
+ target_profile_n_before: i32,
+ target_type_before: Option<Uuid>,
+ reverted_at: Option<DateTime<Utc>>,
+}
+
+/// 精确回滚一次合并:事实原路搬回、作废撤销、target 画像与类型恢复快照、source 复活。
+pub async fn revert_merge(pool: &PgPool, kb_id: Uuid, merge_id: Uuid) -> AppResult<()> {
+ let m: MergeRow = sqlx::query_as(
+ "SELECT source_id, target_id, moved_subject_facts, moved_object_facts,
+ invalidated_facts, temporal_corrections, target_profile_before,
+ target_profile_n_before, target_type_before, reverted_at
+ FROM entity_merges WHERE id = $1 AND kb_id = $2",
+ )
+ .bind(merge_id)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)?;
+ if m.reverted_at.is_some() {
+ return Err(AppError::Conflict("Merge already reverted".into()));
+ }
+
+ let mut tx = pool.begin().await?;
+ sqlx::query("UPDATE facts SET subject_id = $1 WHERE id = ANY($2)")
+ .bind(m.source_id)
+ .bind(&m.moved_subject_facts)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE facts SET object_id = $1 WHERE id = ANY($2)")
+ .bind(m.source_id)
+ .bind(&m.moved_object_facts)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE facts SET invalidated_at = NULL WHERE id = ANY($1)")
+ .bind(&m.invalidated_facts)
+ .execute(&mut *tx)
+ .await?;
+
+ // 合并引发的时态修正随之撤销:这些修正的唯一成因是本次合并(两实体折一后
+ // 不变量才看到的相撞),成因既撤、修正随撤——先恢复被取代的原行,再作废修正行。
+ // 只撤仍存活的修正:之后被真实新观察再度改写过的链保持不动(那部分有独立依据)。
+ sqlx::query(
+ "UPDATE facts SET invalidated_at = NULL WHERE id IN (
+ SELECT supersedes FROM facts
+ WHERE id = ANY($1) AND invalidated_at IS NULL AND supersedes IS NOT NULL)",
+ )
+ .bind(&m.temporal_corrections)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "UPDATE facts SET invalidated_at = now()
+ WHERE id = ANY($1) AND invalidated_at IS NULL",
+ )
+ .bind(&m.temporal_corrections)
+ .execute(&mut *tx)
+ .await?;
+
+ let source = entity_full(pool, kb_id, m.source_id).await?;
+ // target 别名回退:剔除来自 source 的名字
+ sqlx::query(
+ "UPDATE entities SET
+ aliases = (SELECT coalesce(array_agg(a), '{}') FROM unnest(aliases) a
+ WHERE lower(a) <> ALL($2)),
+ profile_embedding = $3, profile_n = $4,
+ type_id = coalesce($5, type_id), updated_at = now()
+ WHERE id = $1",
+ )
+ .bind(m.target_id)
+ .bind(
+ std::iter::once(&source.canonical_name)
+ .chain(source.aliases.iter())
+ .map(|s| s.to_lowercase())
+ .collect::<Vec<_>>(),
+ )
+ .bind(&m.target_profile_before)
+ .bind(m.target_profile_n_before)
+ .bind(m.target_type_before)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE entities SET merged_into = NULL, updated_at = now() WHERE id = $1")
+ .bind(m.source_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("UPDATE entity_merges SET reverted_at = now() WHERE id = $1")
+ .bind(merge_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+
+ refresh_disambiguators(pool, kb_id, &source.canonical_name).await?;
+ Ok(())
+}
+
+/// 合并日志(审核页历史区)。
+pub async fn list_merges(pool: &PgPool, kb_id: Uuid, limit: i64) -> AppResult<Vec<MergeLogView>> {
+ let rows: Vec<MergeLogView> = sqlx::query_as(
+ "SELECT m.id, s.canonical_name AS source_name, t.canonical_name AS target_name,
+ u.display_name AS merged_by_name, m.reason, m.created_at, m.reverted_at
+ FROM entity_merges m
+ JOIN entities s ON s.id = m.source_id
+ JOIN entities t ON t.id = m.target_id
+ LEFT JOIN users u ON u.id = m.merged_by
+ WHERE m.kb_id = $1
+ ORDER BY m.created_at DESC LIMIT $2",
+ )
+ .bind(kb_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+// ---------------------------------------------------------------------------
+// LLM 裁决缓存
+// ---------------------------------------------------------------------------
+
+pub async fn get_verdict(
+ pool: &PgPool,
+ kb_id: Uuid,
+ pair_key: &str,
+) -> AppResult<Option<(Option<bool>, f32)>> {
+ let row: Option<(Option<bool>, f32)> = sqlx::query_as(
+ "SELECT same, confidence FROM resolution_verdicts WHERE kb_id = $1 AND pair_key = $2",
+ )
+ .bind(kb_id)
+ .bind(pair_key)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row)
+}
+
+pub async fn put_verdict(
+ pool: &PgPool,
+ kb_id: Uuid,
+ pair_key: &str,
+ same: Option<bool>,
+ confidence: f32,
+ model: &str,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO resolution_verdicts (kb_id, pair_key, same, confidence, model)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (kb_id, pair_key)
+ DO UPDATE SET same = $3, confidence = $4, model = $5, created_at = now()",
+ )
+ .bind(kb_id)
+ .bind(pair_key)
+ .bind(same)
+ .bind(confidence)
+ .bind(model)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_fullwidth_and_whitespace() {
+ assert_eq!(normalize_name(" ACME Corp "), "ACME Corp");
+ assert_eq!(normalize_name("张三"), "张三");
+ assert_eq!(normalize_name("张 三"), "张 三");
+ }
+
+ #[test]
+ fn stem_generic_suffixes() {
+ assert_eq!(name_stem("星尘项目").as_deref(), Some("星尘"));
+ assert_eq!(name_stem("星辰科技公司").as_deref(), Some("星辰科技"));
+ assert_eq!(name_stem("Phoenix Project").as_deref(), Some("phoenix"));
+ assert_eq!(name_stem("Project Phoenix").as_deref(), Some("phoenix"));
+ assert_eq!(name_stem("Acme Inc.").as_deref(), Some("acme"));
+ assert_eq!(name_stem("星尘"), None);
+ assert_eq!(name_stem("项目"), None); // 剥空不算词干
+ assert_eq!(name_stem("项目团队"), None); // 词干本身是泛用词
+ assert_eq!(name_stem("Team Project"), None);
+ }
+
+ #[test]
+ fn recall_keys_bidirectional() {
+ // 无后缀 mention 能召回带后缀实体(增广),反之靠词干
+ let k = recall_keys("星尘");
+ assert!(k.contains(&"星尘".to_string()));
+ assert!(k.contains(&"星尘项目".to_string()));
+ let k = recall_keys("星尘项目");
+ assert!(k.contains(&"星尘项目".to_string()));
+ assert!(k.contains(&"星尘".to_string()));
+ let k = recall_keys("Phoenix");
+ assert!(k.contains(&"phoenix project".to_string()));
+ assert!(k.contains(&"project phoenix".to_string()));
+ let k = recall_keys("Project Phoenix");
+ assert!(k.contains(&"phoenix".to_string()));
+ assert!(recall_keys("张三").len() <= 10);
+ }
+
+ #[test]
+ fn type_drift_classes() {
+ // 兜底型任意一侧 → 召回候选
+ assert_eq!(
+ classify_type_drift("concept", "organization"),
+ TypeDrift::Recall
+ );
+ assert_eq!(classify_type_drift("project", "concept"), TypeDrift::Recall);
+ assert_eq!(classify_type_drift("concept", "person"), TypeDrift::Recall);
+ // 易混具体类型两两 → 审核对
+ assert_eq!(
+ classify_type_drift("organization", "project"),
+ TypeDrift::Review
+ );
+ assert_eq!(classify_type_drift("project", "product"), TypeDrift::Review);
+ assert_eq!(
+ classify_type_drift("product", "organization"),
+ TypeDrift::Review
+ );
+ // 硬互斥与未知自定义类型 → 完全分开
+ assert_eq!(
+ classify_type_drift("person", "organization"),
+ TypeDrift::Disjoint
+ );
+ assert_eq!(
+ classify_type_drift("person", "project"),
+ TypeDrift::Disjoint
+ );
+ assert_eq!(
+ classify_type_drift("event", "location"),
+ TypeDrift::Disjoint
+ );
+ assert_eq!(
+ classify_type_drift("team", "organization"),
+ TypeDrift::Disjoint
+ );
+ }
+
+ #[test]
+ fn cosine_basics() {
+ assert!((cosine(&[1.0, 0.0], &[1.0, 0.0]).unwrap() - 1.0).abs() < 1e-6);
+ assert!(cosine(&[1.0, 0.0], &[0.0, 1.0]).unwrap().abs() < 1e-6);
+ assert!(cosine(&[1.0], &[1.0, 2.0]).is_none());
+ assert!(cosine(&[0.0, 0.0], &[1.0, 1.0]).is_none());
+ }
+}
diff --git a/crates/utopia-store/src/settings.rs b/crates/utopia-store/src/settings.rs
new file mode 100644
index 00000000..d7881c3a
--- /dev/null
+++ b/crates/utopia-store/src/settings.rs
@@ -0,0 +1,54 @@
+use sqlx::PgPool;
+use utopia_core::models::LlmSettings;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+pub async fn get(pool: &PgPool, workspace_id: Uuid) -> AppResult<Option<LlmSettings>> {
+ let row = sqlx::query_as("SELECT * FROM llm_settings WHERE workspace_id = $1")
+ .bind(workspace_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row)
+}
+
+/// upsert;api_key 传 None 表示保留旧值(前端不回传密钥)。
+#[allow(clippy::too_many_arguments)]
+pub async fn upsert(
+ pool: &PgPool,
+ workspace_id: Uuid,
+ chat_base_url: Option<&str>,
+ chat_api_key: Option<&str>,
+ chat_model: Option<&str>,
+ embed_base_url: Option<&str>,
+ embed_api_key: Option<&str>,
+ embed_model: Option<&str>,
+ embed_dim: Option<i32>,
+) -> AppResult<LlmSettings> {
+ let row = sqlx::query_as(
+ "INSERT INTO llm_settings
+ (workspace_id, chat_base_url, chat_api_key, chat_model,
+ embed_base_url, embed_api_key, embed_model, embed_dim, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, now())
+ ON CONFLICT (workspace_id) DO UPDATE SET
+ chat_base_url = EXCLUDED.chat_base_url,
+ chat_api_key = COALESCE(EXCLUDED.chat_api_key, llm_settings.chat_api_key),
+ chat_model = EXCLUDED.chat_model,
+ embed_base_url = EXCLUDED.embed_base_url,
+ embed_api_key = COALESCE(EXCLUDED.embed_api_key, llm_settings.embed_api_key),
+ embed_model = EXCLUDED.embed_model,
+ embed_dim = EXCLUDED.embed_dim,
+ updated_at = now()
+ RETURNING *",
+ )
+ .bind(workspace_id)
+ .bind(chat_base_url)
+ .bind(chat_api_key)
+ .bind(chat_model)
+ .bind(embed_base_url)
+ .bind(embed_api_key)
+ .bind(embed_model)
+ .bind(embed_dim)
+ .fetch_one(pool)
+ .await?;
+ Ok(row)
+}
diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs
new file mode 100644
index 00000000..8c88d4b2
--- /dev/null
+++ b/crates/utopia-store/src/sources.rs
@@ -0,0 +1,378 @@
+//! 摄入来源仓储:"来源即文件夹"——source 是容器,挂着它摄入的文档,可定时同步。
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use utopia_core::models::{Source, SourceView, SyncRun};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+/// folder = 纯容器(上传/拖拽入内,无同步语义);url/rss = 拉取型;api = 推送型。
+/// 本机目录监听(watch_folder)已否决——自部署用户看不到服务器磁盘;
+/// 未来的 watch 形态是对象存储/网盘(P5 连接器,与 BlobStore 接缝配套)。
+/// custom = 自定义拉取器:任何实现 Utopia ingest 接口的 URL(返回 items JSON)即可定时摄取。
+pub const KINDS: &[&str] = &["folder", "url", "rss", "api", "custom"];
+
+/// 校验并规范化标准 5 段 cron 表达式(内部用 cron crate 的 6 段:补秒位)。
+pub fn validate_cron(expr: &str) -> AppResult<String> {
+ let normalized = expr.split_whitespace().collect::<Vec<_>>().join(" ");
+ let fields = normalized.split(' ').count();
+ if fields != 5 {
+ return Err(AppError::Validation(format!(
+ "Cron expression must have 5 fields (minute hour day month weekday), got {fields}"
+ )));
+ }
+ use std::str::FromStr;
+ cron::Schedule::from_str(&format!("0 {normalized}"))
+ .map_err(|e| AppError::Validation(format!("Invalid cron expression: {e}")))?;
+ Ok(normalized)
+}
+
+/// cron 的下一次触发时刻(服务器本地时区)。
+fn cron_next_after(expr: &str, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
+ use std::str::FromStr;
+ let schedule = cron::Schedule::from_str(&format!("0 {expr}")).ok()?;
+ let local_after = after.with_timezone(&chrono::Local);
+ schedule
+ .after(&local_after)
+ .next()
+ .map(|t| t.with_timezone(&Utc))
+}
+
+pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<SourceView>> {
+ // config 剔除 auth_header:自定义拉取器的凭据不下发给任何客户端
+ let rows: Vec<SourceView> = sqlx::query_as(
+ "SELECT s.id, s.kind, s.name, s.config - 'auth_header' AS config, s.icon,
+ s.sync_interval_minutes, s.sync_cron,
+ s.last_sync_at, s.last_sync_status, s.last_sync_error, s.last_sync_added,
+ (SELECT count(*) FROM documents d WHERE d.source_id = s.id) AS doc_count,
+ (SELECT count(*) FROM documents d
+ WHERE d.source_id = s.id AND d.missing_since IS NOT NULL) AS missing_count
+ FROM sources s WHERE s.kb_id = $1 ORDER BY s.created_at",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Source> {
+ sqlx::query_as("SELECT * FROM sources WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn create(
+ pool: &PgPool,
+ kb_id: Uuid,
+ kind: &str,
+ name: &str,
+ config: &serde_json::Value,
+ icon: Option<&str>,
+ sync_interval_minutes: Option<i32>,
+ sync_cron: Option<&str>,
+) -> AppResult<Source> {
+ if !KINDS.contains(&kind) {
+ return Err(AppError::Validation(format!(
+ "kind must be one of: {}",
+ KINDS.join(", ")
+ )));
+ }
+ if name.trim().is_empty() {
+ return Err(AppError::Validation("Source name is required".into()));
+ }
+ // 互斥:cron 优先(UI 只会传其一)
+ let cron_norm = sync_cron.map(validate_cron).transpose()?;
+ let interval = if cron_norm.is_some() {
+ None
+ } else {
+ sync_interval_minutes
+ };
+ // serde 缺省的 Value::Null 会以 jsonb null 落库,前端读 config.x 直接炸——规范化为空对象
+ let config = if config.is_null() {
+ serde_json::json!({})
+ } else {
+ config.clone()
+ };
+ let source = sqlx::query_as(
+ "INSERT INTO sources (id, kb_id, kind, name, config, icon, sync_interval_minutes, sync_cron)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(kind)
+ .bind(name.trim())
+ .bind(config)
+ .bind(icon)
+ .bind(interval)
+ .bind(cron_norm)
+ .fetch_one(pool)
+ .await?;
+ Ok(source)
+}
+
+/// 设置 api 来源的推送密钥(创建 / 轮换时)。
+pub async fn set_ingest_token(pool: &PgPool, source_id: Uuid, token: &str) -> AppResult<()> {
+ let res = sqlx::query("UPDATE sources SET ingest_token = $2 WHERE id = $1")
+ .bind(source_id)
+ .bind(token)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 更新调度:interval 与 cron 互斥,任一被显式设置时都会覆盖两者。
+#[allow(clippy::too_many_arguments)]
+pub async fn update(
+ pool: &PgPool,
+ id: Uuid,
+ name: Option<&str>,
+ config: Option<&serde_json::Value>,
+ icon: Option<&str>,
+ schedule: Option<(Option<i32>, Option<String>)>,
+) -> AppResult<Source> {
+ let schedule = match schedule {
+ Some((interval, cron)) => {
+ let cron_norm = cron.as_deref().map(validate_cron).transpose()?;
+ let interval = if cron_norm.is_some() { None } else { interval };
+ Some((interval, cron_norm))
+ }
+ None => None,
+ };
+ let source = sqlx::query_as(
+ "UPDATE sources SET
+ name = COALESCE($2, name),
+ config = COALESCE($3, config),
+ icon = COALESCE($4, icon),
+ sync_interval_minutes = CASE WHEN $5 THEN $6 ELSE sync_interval_minutes END,
+ sync_cron = CASE WHEN $5 THEN $7 ELSE sync_cron END
+ WHERE id = $1 RETURNING *",
+ )
+ .bind(id)
+ .bind(name)
+ .bind(config)
+ .bind(icon)
+ .bind(schedule.is_some())
+ .bind(schedule.as_ref().and_then(|(i, _)| *i))
+ .bind(schedule.as_ref().and_then(|(_, c)| c.clone()))
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)?;
+ Ok(source)
+}
+
+/// 删除来源;其文档保留(source_id 置 NULL,落回 Uploads 组)。
+pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM sources WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 到期待同步的来源(调度器每分钟扫)。
+/// interval 型在 SQL 里判定;cron 型取回 Rust 侧求下一次触发时刻再过滤。
+pub async fn due_sources(pool: &PgPool) -> AppResult<Vec<Source>> {
+ let rows: Vec<Source> = sqlx::query_as(
+ "SELECT * FROM sources
+ WHERE last_sync_status NOT IN ('queued', 'running')
+ AND ((sync_interval_minutes IS NOT NULL
+ AND (last_sync_at IS NULL
+ OR last_sync_at + make_interval(mins => sync_interval_minutes) <= now()))
+ OR sync_cron IS NOT NULL)",
+ )
+ .fetch_all(pool)
+ .await?;
+
+ let now = chrono::Utc::now();
+ Ok(rows
+ .into_iter()
+ .filter(|s| match &s.sync_cron {
+ None => true, // interval 型已在 SQL 判定
+ Some(expr) => {
+ // 基准取上次同步时刻(没同步过取创建时刻):错过的触发点在下一轮扫描补上
+ let anchor = s.last_sync_at.unwrap_or(s.created_at);
+ cron_next_after(expr, anchor).is_some_and(|next| next <= now)
+ }
+ })
+ .collect())
+}
+
+/// 标记入队(幂等:已在队列/运行中则返回 false,避免重复入队)。
+pub async fn mark_queued(pool: &PgPool, id: Uuid) -> AppResult<bool> {
+ let res = sqlx::query(
+ "UPDATE sources SET last_sync_status = 'queued'
+ WHERE id = $1 AND last_sync_status NOT IN ('queued', 'running')",
+ )
+ .bind(id)
+ .execute(pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+}
+
+pub async fn mark_running(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ sqlx::query("UPDATE sources SET last_sync_status = 'running' WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn finish_sync(
+ pool: &PgPool,
+ id: Uuid,
+ error: Option<&str>,
+ added: i32,
+) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE sources SET last_sync_status = $2, last_sync_error = $3,
+ last_sync_added = $4, last_sync_at = now()
+ WHERE id = $1",
+ )
+ .bind(id)
+ .bind(if error.is_some() { "failed" } else { "ok" })
+ .bind(error)
+ .bind(added)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// 文档打标签(整组替换)。
+pub async fn set_document_tags(
+ pool: &PgPool,
+ kb_id: Uuid,
+ document_id: Uuid,
+ tags: &[String],
+) -> AppResult<()> {
+ let cleaned: Vec<String> = tags
+ .iter()
+ .map(|t| t.trim().to_string())
+ .filter(|t| !t.is_empty())
+ .collect();
+ let res = sqlx::query(
+ "UPDATE documents SET tags = $3, updated_at = now() WHERE id = $1 AND kb_id = $2",
+ )
+ .bind(document_id)
+ .bind(kb_id)
+ .bind(&cleaned)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
+
+/// 同步用去重:该 KB 是否已有同内容文档。
+pub async fn document_exists_by_sha(pool: &PgPool, kb_id: Uuid, sha256: &str) -> AppResult<bool> {
+ let row: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM documents WHERE kb_id = $1 AND sha256 = $2 LIMIT 1")
+ .bind(kb_id)
+ .bind(sha256)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.is_some())
+}
+
+/// 记录同步时刻(避免调度器在长同步过程中重复触发后又立刻到期)。
+pub async fn touch_sync_time(pool: &PgPool, id: Uuid, at: DateTime<Utc>) -> AppResult<()> {
+ sqlx::query("UPDATE sources SET last_sync_at = $2 WHERE id = $1")
+ .bind(id)
+ .bind(at)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// 同步运行记录(渠道审计历史)
+// ---------------------------------------------------------------------------
+
+pub async fn start_run(pool: &PgPool, source_id: Uuid) -> AppResult<Uuid> {
+ let id = Uuid::now_v7();
+ sqlx::query("INSERT INTO source_sync_runs (id, source_id) VALUES ($1, $2)")
+ .bind(id)
+ .bind(source_id)
+ .execute(pool)
+ .await?;
+ Ok(id)
+}
+
+pub async fn finish_run(
+ pool: &PgPool,
+ run_id: Uuid,
+ source_id: Uuid,
+ error: Option<&str>,
+ created_docs: i32,
+ updated_docs: i32,
+) -> AppResult<()> {
+ sqlx::query(
+ "UPDATE source_sync_runs SET finished_at = now(), status = $2, error = $3,
+ created_docs = $4, updated_docs = $5
+ WHERE id = $1",
+ )
+ .bind(run_id)
+ .bind(if error.is_some() { "failed" } else { "ok" })
+ .bind(error)
+ .bind(created_docs)
+ .bind(updated_docs)
+ .execute(pool)
+ .await?;
+ // 每来源只留最近 50 条
+ sqlx::query(
+ "DELETE FROM source_sync_runs WHERE source_id = $1 AND id NOT IN
+ (SELECT id FROM source_sync_runs WHERE source_id = $1
+ ORDER BY started_at DESC LIMIT 50)",
+ )
+ .bind(source_id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+pub async fn list_runs(pool: &PgPool, source_id: Uuid, limit: i64) -> AppResult<Vec<SyncRun>> {
+ let rows: Vec<SyncRun> = sqlx::query_as(
+ "SELECT id, started_at, finished_at, status, created_docs, updated_docs, error
+ FROM source_sync_runs WHERE source_id = $1
+ ORDER BY started_at DESC LIMIT $2",
+ )
+ .bind(source_id)
+ .bind(limit)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cron_validation() {
+ assert_eq!(validate_cron("30 9 * * *").unwrap(), "30 9 * * *");
+ assert_eq!(
+ validate_cron(" 0 9 * * Mon,Thu ").unwrap(),
+ "0 9 * * Mon,Thu"
+ );
+ assert!(validate_cron("9 * * *").is_err()); // 4 段
+ assert!(validate_cron("99 9 * * *").is_err()); // 分钟越界
+ assert!(validate_cron("0 0 0 0 0 0").is_err()); // 6 段
+ }
+
+ #[test]
+ fn cron_next_computes() {
+ let after = chrono::Utc::now();
+ let next = cron_next_after("*/5 * * * *", after).unwrap();
+ assert!(next > after);
+ assert!((next - after).num_minutes() <= 5);
+ }
+}
diff --git a/crates/utopia-store/src/temporal.rs b/crates/utopia-store/src/temporal.rs
new file mode 100644
index 00000000..17b37854
--- /dev/null
+++ b/crates/utopia-store/src/temporal.rs
@@ -0,0 +1,401 @@
+//! 时态引擎(S3):functional 状态关系的矛盾检测与自动闭合。
+//!
+//! 原则:
+//! - 纯规则判定,零 LLM——模糊性已在上游(消解归并实体、本体标 functional)消化
+//! - 闭合走"作废 + 改写"而非原地改:旧断言 invalidated_at 记下"何时被修正",
+//! 修正行闭合区间并以 supersedes 链回旧行——"以当时的认知回放当时"得以成立
+//! - 闭合点只用世界时间(新事实的 valid_from),绝不用摄取时刻顶替
+//! - 拿不准(缺时间/同时开始/低置信)绝不硬闭合,进 fact_conflicts 由人裁决
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use utopia_core::models::ConflictView;
+use utopia_core::AppResult;
+use uuid::Uuid;
+
+/// 低于此置信度的新事实不允许自动改写历史(进审)。
+const AUTO_CLOSE_MIN_CONFIDENCE: f32 = 0.75;
+
+/// 命中的开放期事实(不变量下至多一条,引擎上线前的历史脏数据可能多条)。
+#[derive(Debug, sqlx::FromRow)]
+struct OpenFact {
+ id: Uuid,
+ valid_from: Option<DateTime<Utc>>,
+}
+
+/// 唯一性方向:functional = 主语侧(张三同时只 reports_to 一人);
+/// inverse functional = 宾语侧(一个项目同时只有一个 leads 它的人)。
+#[derive(Debug, Clone, Copy)]
+pub enum Uniqueness {
+ SubjectSide,
+ ObjectSide,
+}
+
+/// 对账结果:自动闭合产生的修正行 id(调用方按需记账,如合并回滚要撤销它们)
+/// 与进入人审的冲突数。
+#[derive(Debug, Default)]
+pub struct ReconcileReport {
+ pub corrected: Vec<Uuid>,
+ pub conflicts: u32,
+}
+
+/// 一条新 state 事实落库后、沿指定唯一性方向的对账。调用方负责判断关系确实
+/// 带该方向的唯一性且 temporal = state(本体元数据在抽取任务里已加载)。
+///
+/// 宾语可以是实体(object_id)或字面值(object_value,属性事实)——
+/// "宾语不同"的判定是 (object_id, object_value) 组合比较:工资从 3 万变 3.5 万
+/// 与"从张三换成李四"走同一条闭合路径。
+#[allow(clippy::too_many_arguments)]
+pub async fn reconcile_new_fact(
+ pool: &PgPool,
+ kb_id: Uuid,
+ new_fact_id: Uuid,
+ subject_id: Uuid,
+ predicate_id: Uuid,
+ object_id: Option<Uuid>,
+ object_value: Option<&serde_json::Value>,
+ direction: Uniqueness,
+ new_valid_from: Option<DateTime<Utc>>,
+ new_valid_to: Option<DateTime<Utc>>,
+ new_confidence: f32,
+) -> AppResult<ReconcileReport> {
+ // 已闭区间的新事实是历史陈述,不威胁"开放期唯一"不变量——不触发任何改写
+ // (闭区间之间的重叠矛盾是更细的区间代数,暂不自动裁,留给 Review 的人眼)
+ if new_valid_to.is_some() {
+ return Ok(ReconcileReport::default());
+ }
+ // 宾语侧唯一性只对实体宾语有意义(字面值不"被占用")
+ if matches!(direction, Uniqueness::ObjectSide) && object_id.is_none() {
+ return Ok(ReconcileReport::default());
+ }
+ // 不变量点查:主语侧 = 同 (kb, S, P) 宾语不同;宾语侧 = 同 (kb, P, O) 主语不同
+ let sql = match direction {
+ Uniqueness::SubjectSide => {
+ "SELECT id, valid_from FROM facts
+ WHERE kb_id = $1 AND subject_id = $2 AND predicate_id = $3
+ AND valid_to IS NULL AND invalidated_at IS NULL
+ AND id <> $4
+ AND (object_id IS DISTINCT FROM $5 OR object_value IS DISTINCT FROM $6)"
+ }
+ Uniqueness::ObjectSide => {
+ "SELECT id, valid_from FROM facts
+ WHERE kb_id = $1 AND object_id = $5 AND predicate_id = $3
+ AND valid_to IS NULL AND invalidated_at IS NULL
+ AND id <> $4 AND subject_id IS DISTINCT FROM $2"
+ }
+ };
+ let q = sqlx::query_as(sql)
+ .bind(kb_id)
+ .bind(subject_id)
+ .bind(predicate_id)
+ .bind(new_fact_id)
+ .bind(object_id);
+ let open: Vec<OpenFact> = match direction {
+ Uniqueness::SubjectSide => q.bind(object_value).fetch_all(pool).await?,
+ Uniqueness::ObjectSide => q.fetch_all(pool).await?,
+ };
+ if open.is_empty() {
+ return Ok(ReconcileReport::default());
+ }
+
+ let mut report = ReconcileReport::default();
+ for old in open {
+ match (old.valid_from, new_valid_from) {
+ // 新事实没有世界时间:闭合点无从谈起 → 人裁
+ (_, None) => {
+ record_conflict(pool, kb_id, old.id, new_fact_id, "no_time").await?;
+ report.conflicts += 1;
+ }
+ // 同一时刻开始:谁接替谁说不清 → 人裁
+ (Some(of), Some(nf)) if of == nf => {
+ record_conflict(pool, kb_id, old.id, new_fact_id, "simultaneous").await?;
+ report.conflicts += 1;
+ }
+ // 新事实开始得更早:它是历史前任,闭合在旧事实的开始
+ (Some(of), Some(nf)) if nf < of => {
+ if new_confidence < AUTO_CLOSE_MIN_CONFIDENCE {
+ record_conflict(pool, kb_id, old.id, new_fact_id, "low_confidence").await?;
+ report.conflicts += 1;
+ } else {
+ report
+ .corrected
+ .push(close_superseded(pool, new_fact_id, of).await?);
+ }
+ }
+ // 常规接替:旧事实闭合在新事实的开始(旧事实无起点也适用——起点未知但已结束)
+ (_, Some(nf)) => {
+ if new_confidence < AUTO_CLOSE_MIN_CONFIDENCE {
+ record_conflict(pool, kb_id, old.id, new_fact_id, "low_confidence").await?;
+ report.conflicts += 1;
+ } else {
+ report
+ .corrected
+ .push(close_superseded(pool, old.id, nf).await?);
+ }
+ }
+ }
+ }
+ Ok(report)
+}
+
+/// 实体合并搬移事实后的对账:换了主/宾的事实等价于"新落库的观察"——
+/// 两个对象折成一个之后,唯一性不变量才第一次看得到它们相撞。
+/// 按 recorded_at 顺序逐条重跑插入时对账;非唯一性关系、已闭合区间、
+/// 已被前一条改写作废的事实自动跳过。
+/// 返回的修正行 id 由调用方记入合并账本——这些修正的唯一成因是合并本身,
+/// 回滚合并时必须随之撤销(修正行作废、被取代的原行恢复),否则修正行会
+/// 错挂在 target 上而其依据已随回滚离开。
+pub async fn reconcile_moved_facts(
+ pool: &PgPool,
+ kb_id: Uuid,
+ fact_ids: &[Uuid],
+) -> AppResult<ReconcileReport> {
+ if fact_ids.is_empty() {
+ return Ok(ReconcileReport::default());
+ }
+ #[derive(sqlx::FromRow)]
+ struct MovedFact {
+ id: Uuid,
+ subject_id: Uuid,
+ predicate_id: Uuid,
+ object_id: Option<Uuid>,
+ object_value: Option<serde_json::Value>,
+ valid_from: Option<DateTime<Utc>>,
+ confidence: f32,
+ functional: bool,
+ inverse_functional: bool,
+ }
+ let rows: Vec<MovedFact> = sqlx::query_as(
+ "SELECT f.id, f.subject_id, f.predicate_id, f.object_id, f.object_value, f.valid_from,
+ f.confidence, r.functional, r.inverse_functional
+ FROM facts f JOIN relation_types r ON r.id = f.predicate_id
+ WHERE f.kb_id = $1 AND f.id = ANY($2)
+ AND f.invalidated_at IS NULL AND f.valid_to IS NULL
+ AND r.temporal = 'state' AND (r.functional OR r.inverse_functional)
+ ORDER BY f.recorded_at",
+ )
+ .bind(kb_id)
+ .bind(fact_ids)
+ .fetch_all(pool)
+ .await?;
+
+ let mut report = ReconcileReport::default();
+ for f in rows {
+ // 字面值事实(属性)合并后同样对账:两个"张三"折成一个,工资撞车也要闭合
+ if f.object_id.is_none() && f.object_value.is_none() {
+ continue;
+ }
+ // 前面的闭合可能已把本条改写作废——逐条复核存活性再当"新事实"用
+ let (alive,): (bool,) = sqlx::query_as(
+ "SELECT EXISTS (SELECT 1 FROM facts
+ WHERE id = $1 AND invalidated_at IS NULL AND valid_to IS NULL)",
+ )
+ .bind(f.id)
+ .fetch_one(pool)
+ .await?;
+ if !alive {
+ continue;
+ }
+ let mut directions = Vec::new();
+ if f.functional {
+ directions.push(Uniqueness::SubjectSide);
+ }
+ if f.inverse_functional {
+ directions.push(Uniqueness::ObjectSide);
+ }
+ for dir in directions {
+ let r = reconcile_new_fact(
+ pool,
+ kb_id,
+ f.id,
+ f.subject_id,
+ f.predicate_id,
+ f.object_id,
+ f.object_value.as_ref(),
+ dir,
+ f.valid_from,
+ None,
+ f.confidence,
+ )
+ .await?;
+ report.corrected.extend(r.corrected);
+ report.conflicts += r.conflicts;
+ }
+ }
+ Ok(report)
+}
+
+/// 作废 + 改写:旧行记 invalidated_at(认知轴),插入闭合区间的修正行
+/// (世界轴),证据引用随行复制。返回修正行 id。
+pub async fn close_superseded(
+ pool: &PgPool,
+ fact_id: Uuid,
+ valid_to: DateTime<Utc>,
+) -> AppResult<Uuid> {
+ let mut tx = pool.begin().await?;
+ let corrected = Uuid::now_v7();
+ let inserted: Option<(Uuid,)> = sqlx::query_as(
+ "INSERT INTO facts (id, kb_id, subject_id, predicate_id, object_id, object_value,
+ valid_from, valid_to, valid_precision, confidence, supersedes)
+ SELECT $1, kb_id, subject_id, predicate_id, object_id, object_value,
+ valid_from, $3, valid_precision, confidence, id
+ FROM facts WHERE id = $2 AND invalidated_at IS NULL
+ RETURNING id",
+ )
+ .bind(corrected)
+ .bind(fact_id)
+ .bind(valid_to)
+ .fetch_optional(&mut *tx)
+ .await?;
+ // 已被并发修正过:不重复动手
+ if inserted.is_none() {
+ tx.rollback().await?;
+ return Ok(fact_id);
+ }
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(fact_id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query(
+ "INSERT INTO fact_evidence (fact_id, chunk_id, quote, document_id, doc_version)
+ SELECT $1, chunk_id, quote, document_id, doc_version
+ FROM fact_evidence WHERE fact_id = $2
+ ON CONFLICT DO NOTHING",
+ )
+ .bind(corrected)
+ .bind(fact_id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(corrected)
+}
+
+async fn record_conflict(
+ pool: &PgPool,
+ kb_id: Uuid,
+ old_fact_id: Uuid,
+ new_fact_id: Uuid,
+ reason: &str,
+) -> AppResult<()> {
+ sqlx::query(
+ "INSERT INTO fact_conflicts (id, kb_id, old_fact_id, new_fact_id, reason)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (old_fact_id, new_fact_id) DO NOTHING",
+ )
+ .bind(Uuid::now_v7())
+ .bind(kb_id)
+ .bind(old_fact_id)
+ .bind(new_fact_id)
+ .bind(reason)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// Review 页的冲突列表(双方事实带名字与区间)。
+/// 惰性清理:任一方已被作废(被驳回/被别的闭合改写)的冲突已无意义,
+/// 自动出队标 stale——防止在僵尸冲突上误裁(如把 Eve 闭合在已驳回的 Ivan 上)。
+pub async fn list_conflicts(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<ConflictView>> {
+ sqlx::query(
+ "UPDATE fact_conflicts c
+ SET status = 'resolved', resolution = 'stale', resolved_at = now()
+ WHERE c.kb_id = $1 AND c.status = 'open'
+ AND EXISTS (SELECT 1 FROM facts f
+ WHERE f.id IN (c.old_fact_id, c.new_fact_id)
+ AND f.invalidated_at IS NOT NULL)",
+ )
+ .bind(kb_id)
+ .execute(pool)
+ .await?;
+ let rows: Vec<ConflictView> = sqlx::query_as(
+ "SELECT c.id, c.reason, c.created_at, r.label AS predicate_label,
+ c.old_fact_id, os.canonical_name AS old_subject,
+ oo.canonical_name AS old_object, fo.valid_from AS old_valid_from,
+ c.new_fact_id, ns.canonical_name AS new_subject,
+ no_.canonical_name AS new_object, fn_.valid_from AS new_valid_from,
+ fn_.confidence AS new_confidence
+ FROM fact_conflicts c
+ JOIN facts fo ON fo.id = c.old_fact_id
+ JOIN facts fn_ ON fn_.id = c.new_fact_id
+ JOIN entities os ON os.id = fo.subject_id
+ JOIN entities ns ON ns.id = fn_.subject_id
+ JOIN relation_types r ON r.id = fo.predicate_id
+ LEFT JOIN entities oo ON oo.id = fo.object_id
+ LEFT JOIN entities no_ ON no_.id = fn_.object_id
+ WHERE c.kb_id = $1 AND c.status = 'open'
+ ORDER BY c.created_at DESC
+ LIMIT 200",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 人工裁决:close(旧事实闭合于 close_at 或新事实起点)/ keep(并存不矛盾)/
+/// reject_new(新事实是抽取错误,作废)。
+pub async fn resolve_conflict(
+ pool: &PgPool,
+ kb_id: Uuid,
+ conflict_id: Uuid,
+ resolution: &str,
+ close_at: Option<DateTime<Utc>>,
+) -> AppResult<()> {
+ let row: Option<(Uuid, Uuid, Option<DateTime<Utc>>)> = sqlx::query_as(
+ "SELECT c.old_fact_id, c.new_fact_id, fn_.valid_from
+ FROM fact_conflicts c JOIN facts fn_ ON fn_.id = c.new_fact_id
+ WHERE c.id = $1 AND c.kb_id = $2 AND c.status = 'open'",
+ )
+ .bind(conflict_id)
+ .bind(kb_id)
+ .fetch_optional(pool)
+ .await?;
+ let Some((old_fact_id, new_fact_id, new_from)) = row else {
+ return Err(utopia_core::AppError::NotFound);
+ };
+
+ let stored = match resolution {
+ "close" => {
+ let at = close_at.or(new_from).ok_or_else(|| {
+ utopia_core::AppError::Validation(
+ "close_at is required when the new fact has no start time".into(),
+ )
+ })?;
+ close_superseded(pool, old_fact_id, at).await?;
+ "closed"
+ }
+ "keep" => "kept_both",
+ "reject_new" => {
+ sqlx::query("UPDATE facts SET invalidated_at = now() WHERE id = $1")
+ .bind(new_fact_id)
+ .execute(pool)
+ .await?;
+ // 波及:同一新事实撞出的其他 open 冲突一并出队(新事实已死,无从裁起)
+ sqlx::query(
+ "UPDATE fact_conflicts
+ SET status = 'resolved', resolution = 'rejected_new', resolved_at = now()
+ WHERE new_fact_id = $1 AND status = 'open' AND id <> $2",
+ )
+ .bind(new_fact_id)
+ .bind(conflict_id)
+ .execute(pool)
+ .await?;
+ "rejected_new"
+ }
+ other => {
+ return Err(utopia_core::AppError::Validation(format!(
+ "Unknown resolution: {other}"
+ )))
+ }
+ };
+ sqlx::query(
+ "UPDATE fact_conflicts SET status = 'resolved', resolution = $3, resolved_at = now()
+ WHERE id = $1 AND kb_id = $2",
+ )
+ .bind(conflict_id)
+ .bind(kb_id)
+ .bind(stored)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
diff --git a/crates/utopia-store/src/workspaces.rs b/crates/utopia-store/src/workspaces.rs
new file mode 100644
index 00000000..fc1c763e
--- /dev/null
+++ b/crates/utopia-store/src/workspaces.rs
@@ -0,0 +1,95 @@
+use sqlx::PgPool;
+use utopia_core::models::{Role, Workspace};
+use utopia_core::{AppError, AppResult};
+use uuid::Uuid;
+
+pub async fn list_for_user(pool: &PgPool, user_id: Uuid) -> AppResult<Vec<Workspace>> {
+ let rows = sqlx::query_as(
+ "SELECT w.* FROM workspaces w
+ JOIN memberships m ON m.workspace_id = w.id
+ WHERE m.user_id = $1
+ ORDER BY w.created_at",
+ )
+ .bind(user_id)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// 在用户所属组织内新建工作区,创建者为 owner。
+pub async fn create(
+ pool: &PgPool,
+ org_id: Uuid,
+ user_id: Uuid,
+ name: &str,
+) -> AppResult<Workspace> {
+ let mut tx = pool.begin().await?;
+ let ws: Workspace =
+ sqlx::query_as("INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3) RETURNING *")
+ .bind(Uuid::now_v7())
+ .bind(org_id)
+ .bind(name)
+ .fetch_one(&mut *tx)
+ .await?;
+ sqlx::query("INSERT INTO memberships (user_id, workspace_id, role) VALUES ($1, $2, $3)")
+ .bind(user_id)
+ .bind(ws.id)
+ .bind(Role::Owner.as_str())
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(ws)
+}
+
+pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Workspace> {
+ sqlx::query_as("SELECT * FROM workspaces WHERE id = $1")
+ .bind(id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+/// 取用户在工作区中的角色;非成员返回 None。
+pub async fn role_of(pool: &PgPool, user_id: Uuid, workspace_id: Uuid) -> AppResult<Option<Role>> {
+ let role: Option<(String,)> =
+ sqlx::query_as("SELECT role FROM memberships WHERE user_id = $1 AND workspace_id = $2")
+ .bind(user_id)
+ .bind(workspace_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(role.and_then(|(r,)| Role::parse(&r)))
+}
+
+/// 权限检查:非成员 → NotFound(不泄露存在性);角色不足 → Forbidden。
+pub async fn require_role(
+ pool: &PgPool,
+ user_id: Uuid,
+ workspace_id: Uuid,
+ min: Role,
+) -> AppResult<Role> {
+ match role_of(pool, user_id, workspace_id).await? {
+ None => Err(AppError::NotFound),
+ Some(r) if r >= min => Ok(r),
+ Some(_) => Err(AppError::Forbidden),
+ }
+}
+
+pub async fn rename(pool: &PgPool, id: Uuid, name: &str) -> AppResult<Workspace> {
+ sqlx::query_as("UPDATE workspaces SET name = $2 WHERE id = $1 RETURNING *")
+ .bind(id)
+ .bind(name)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(AppError::NotFound)
+}
+
+pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
+ let res = sqlx::query("DELETE FROM workspaces WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 00000000..8b0d0b81
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,38 @@
+services:
+ db:
+ # 拉不动 Docker Hub 时可用 UTOPIA_DB_IMAGE 覆盖为任何带 pgvector 的 PG16+ 镜像
+ image: ${UTOPIA_DB_IMAGE:-pgvector/pgvector:pg16}
+ environment:
+ POSTGRES_USER: utopia
+ POSTGRES_PASSWORD: utopia
+ POSTGRES_DB: utopia
+ ports:
+ - "5432:5432"
+ volumes:
+ - dbdata:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U utopia -d utopia"]
+ interval: 5s
+ timeout: 3s
+ retries: 10
+
+ # 完整部署:docker compose --profile app up -d
+ # 本地开发只起 db,应用用 cargo run 跑
+ app:
+ build:
+ context: .
+ dockerfile: docker/Dockerfile
+ profiles: ["app"]
+ environment:
+ UTOPIA_DATABASE_URL: postgres://utopia:utopia@db:5432/utopia
+ UTOPIA_BIND_ADDR: 0.0.0.0:8080
+ UTOPIA_JWT_SECRET: ${UTOPIA_JWT_SECRET:-please-change-me-in-production}
+ UTOPIA_WEB_DIST: /app/web-dist
+ ports:
+ - "8080:8080"
+ depends_on:
+ db:
+ condition: service_healthy
+
+volumes:
+ dbdata:
diff --git a/docker/Dockerfile b/docker/Dockerfile
new file mode 100644
index 00000000..4fe1d741
--- /dev/null
+++ b/docker/Dockerfile
@@ -0,0 +1,27 @@
+# ---- 前端构建 ----
+FROM node:20-slim AS web
+WORKDIR /src
+RUN corepack enable
+COPY web/package.json web/pnpm-lock.yaml ./
+RUN pnpm install --frozen-lockfile
+COPY web/ ./
+RUN pnpm build
+
+# ---- 后端构建 ----
+FROM rust:1-slim AS build
+WORKDIR /src
+RUN apt-get update && apt-get install -y --no-install-recommends pkg-config && rm -rf /var/lib/apt/lists/*
+COPY Cargo.toml Cargo.lock ./
+COPY crates/ crates/
+COPY migrations/ migrations/
+RUN cargo build --release -p utopia-server
+
+# ---- 运行 ----
+FROM debian:bookworm-slim
+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
+WORKDIR /app
+COPY --from=build /src/target/release/utopia-server /usr/local/bin/utopia-server
+COPY --from=web /src/dist /app/web-dist
+ENV UTOPIA_WEB_DIST=/app/web-dist
+EXPOSE 8080
+CMD ["utopia-server"]
diff --git a/migrations/0001_core.sql b/migrations/0001_core.sql
new file mode 100644
index 00000000..e48fb07b
--- /dev/null
+++ b/migrations/0001_core.sql
@@ -0,0 +1,63 @@
+-- 0001: 核心多租户表 + 任务队列
+-- pgvector 扩展提前建好(P1 的 chunks.embedding 依赖),使用 pgvector/pgvector 镜像自带
+CREATE EXTENSION IF NOT EXISTS vector;
+
+CREATE TABLE organizations (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE users (
+ id UUID PRIMARY KEY,
+ org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
+ email TEXT NOT NULL UNIQUE,
+ password_hash TEXT NOT NULL,
+ display_name TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE workspaces (
+ id UUID PRIMARY KEY,
+ org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE memberships (
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ workspace_id UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'editor', 'viewer')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (user_id, workspace_id)
+);
+CREATE INDEX memberships_workspace_idx ON memberships (workspace_id);
+
+CREATE TABLE knowledge_bases (
+ id UUID PRIMARY KEY,
+ workspace_id UUID NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL DEFAULT 'knowledge' CHECK (kind IN ('knowledge', 'memory')),
+ description TEXT,
+ -- 部署的公共默认空间(workspace 里第一个建的库):永远 open、不可删(API 强制)
+ is_default BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX knowledge_bases_workspace_idx ON knowledge_bases (workspace_id);
+
+-- 任务队列:FOR UPDATE SKIP LOCKED 消费,见 docs/DESIGN.md 第 2 节
+CREATE TABLE jobs (
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ kind TEXT NOT NULL,
+ payload JSONB NOT NULL DEFAULT '{}',
+ status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'running', 'done', 'failed')),
+ attempts INT NOT NULL DEFAULT 0,
+ max_attempts INT NOT NULL DEFAULT 3,
+ run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ locked_at TIMESTAMPTZ,
+ last_error TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX jobs_claim_idx ON jobs (run_at) WHERE status = 'queued';
diff --git a/migrations/0002_ingest.sql b/migrations/0002_ingest.sql
new file mode 100644
index 00000000..972af16c
--- /dev/null
+++ b/migrations/0002_ingest.sql
@@ -0,0 +1,70 @@
+-- 0002: 摄入管道(来源/文档/分块)+ 工作区 LLM 设置
+
+CREATE TABLE sources (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL DEFAULT 'upload',
+ name TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX sources_kb_idx ON sources (kb_id);
+
+CREATE TABLE documents (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ source_id UUID REFERENCES sources(id) ON DELETE SET NULL,
+ filename TEXT NOT NULL,
+ mime TEXT NOT NULL DEFAULT 'application/octet-stream',
+ size_bytes BIGINT NOT NULL DEFAULT 0,
+ sha256 TEXT NOT NULL,
+ -- pending → parsing → indexing → embedding → ready | failed
+ status TEXT NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'parsing', 'indexing', 'embedding', 'ready', 'failed')),
+ error TEXT,
+ -- 文档时间:可信分级 + 可修改(见 DESIGN.md 4.2)
+ doc_time TIMESTAMPTZ,
+ doc_time_source TEXT NOT NULL DEFAULT 'file_mtime',
+ text_len INT NOT NULL DEFAULT 0,
+ chunk_count INT NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX documents_kb_idx ON documents (kb_id, created_at DESC);
+CREATE UNIQUE INDEX documents_kb_sha_idx ON documents (kb_id, sha256);
+
+CREATE TABLE chunks (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
+ seq INT NOT NULL,
+ text TEXT NOT NULL,
+ heading TEXT,
+ char_start INT NOT NULL DEFAULT 0,
+ char_end INT NOT NULL DEFAULT 0,
+ -- 维度不定(随所选 embedding 模型),P1 顺扫检索;量大后按已配维度建 HNSW 索引
+ embedding vector,
+ -- 版本软删除:文档更新时旧分块打标(superseded_at)而非物理删除——
+ -- fact_evidence 引用不断链、旧版原文可回放;打标时 embedding 清空(旧版不参与检索)
+ doc_version INT NOT NULL DEFAULT 1,
+ superseded_at TIMESTAMPTZ,
+ -- 图谱抽取完成标记:文档更新时被"认领"的未变分块携带它跳过重抽(增量抽取),
+ -- 也让中断的抽取可断点续跑
+ extracted_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX chunks_document_idx ON chunks (document_id, seq);
+CREATE INDEX chunks_kb_idx ON chunks (kb_id);
+CREATE INDEX chunks_live_idx ON chunks (document_id) WHERE superseded_at IS NULL;
+
+-- 工作区级 LLM 设置(对话与 embedding 分开配置,OpenAI 兼容协议)
+CREATE TABLE llm_settings (
+ workspace_id UUID PRIMARY KEY REFERENCES workspaces(id) ON DELETE CASCADE,
+ chat_base_url TEXT,
+ chat_api_key TEXT,
+ chat_model TEXT,
+ embed_base_url TEXT,
+ embed_api_key TEXT,
+ embed_model TEXT,
+ embed_dim INT,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/migrations/0003_single_tenant.sql b/migrations/0003_single_tenant.sql
new file mode 100644
index 00000000..94ee4973
--- /dev/null
+++ b/migrations/0003_single_tenant.sql
@@ -0,0 +1,9 @@
+-- 0003: 单租户部署模型
+-- 一次部署 = 一个组织;首个注册用户为系统管理员,后续用户加入同一组织。
+-- organizations 表与 org_id 列保留为内部管道(永远单行),为将来可能的托管版留门。
+
+ALTER TABLE users ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- 存量数据:最早注册的用户视为系统管理员
+UPDATE users SET is_admin = TRUE
+WHERE id = (SELECT id FROM users ORDER BY created_at LIMIT 1);
diff --git a/migrations/0004_graph.sql b/migrations/0004_graph.sql
new file mode 100644
index 00000000..5a9e2052
--- /dev/null
+++ b/migrations/0004_graph.sql
@@ -0,0 +1,115 @@
+-- 0004: 图谱层 —— 轻量本体 + 实体 + 双时态事实账本 + 证据链
+-- 设计见 docs/DESIGN.md §3:事实 append-only;抽取错误设 invalidated_at,事实变化闭合 valid_to。
+
+CREATE TABLE entity_types (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ key TEXT NOT NULL,
+ label TEXT NOT NULL,
+ color TEXT NOT NULL DEFAULT '#64748b',
+ builtin BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (kb_id, key)
+);
+
+CREATE TABLE relation_types (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ key TEXT NOT NULL,
+ label TEXT NOT NULL,
+ -- 时间语义:state 状态型(区间) / event 事件型(时点) / eternal 永恒型(无时间)
+ temporal TEXT NOT NULL DEFAULT 'state' CHECK (temporal IN ('state', 'event', 'eternal')),
+ -- 基数唯一(同一时刻单值),时态冲突检测(自动闭合 valid_to)的依据:
+ -- functional = 主语侧唯一;inverse_functional = 宾语侧唯一(一个项目一个 leader)
+ functional BOOLEAN NOT NULL DEFAULT FALSE,
+ inverse_functional BOOLEAN NOT NULL DEFAULT FALSE,
+ builtin BOOLEAN NOT NULL DEFAULT FALSE,
+ -- 属性系统:属性 = 值域为字面量的关系(RDF datatype property),一表两用。
+ -- 属性值走 facts.object_value 通道,时态/证据/Review 全套复用
+ kind TEXT NOT NULL DEFAULT 'relation' CHECK (kind IN ('relation', 'attribute')),
+ -- 属性挂在哪个类下(attribute 必填;类删则属性随删)
+ domain_type_id UUID REFERENCES entity_types(id) ON DELETE CASCADE,
+ datatype TEXT CHECK (datatype IN ('text', 'number', 'date', 'bool')),
+ unit TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (kb_id, key)
+);
+
+CREATE TABLE entities (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ type_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE RESTRICT,
+ canonical_name TEXT NOT NULL,
+ aliases TEXT[] NOT NULL DEFAULT '{}',
+ attrs JSONB NOT NULL DEFAULT '{}',
+ -- 被合并后指向存活实体(合并可回滚,P2 后续)
+ merged_into UUID REFERENCES entities(id),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE UNIQUE INDEX entities_kb_type_name_idx
+ ON entities (kb_id, type_id, lower(canonical_name)) WHERE merged_into IS NULL;
+CREATE INDEX entities_kb_idx ON entities (kb_id);
+-- 跨类型同名召回(类型漂移处理):上面的唯一索引带 type_id 前缀,跨类型查询用不上
+CREATE INDEX entities_kb_name_idx
+ ON entities (kb_id, lower(canonical_name)) WHERE merged_into IS NULL;
+
+-- 事实账本:SPO + 双时间轴(append-only,永不 DELETE)
+CREATE TABLE facts (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ subject_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ predicate_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,
+ object_id UUID REFERENCES entities(id) ON DELETE CASCADE,
+ object_value JSONB,
+ valid_from TIMESTAMPTZ,
+ valid_to TIMESTAMPTZ,
+ valid_precision TEXT NOT NULL DEFAULT 'day',
+ recorded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ invalidated_at TIMESTAMPTZ,
+ confidence REAL NOT NULL DEFAULT 1.0,
+ derived_by_rule UUID,
+ supersedes UUID REFERENCES facts(id),
+ CHECK (object_id IS NOT NULL OR object_value IS NOT NULL)
+);
+-- 热路径部分索引:作废行不进索引(账本边界与清理,DESIGN.md §3.1)
+CREATE INDEX facts_live_subject_idx ON facts (kb_id, subject_id) WHERE invalidated_at IS NULL;
+CREATE INDEX facts_live_object_idx ON facts (kb_id, object_id) WHERE invalidated_at IS NULL;
+CREATE INDEX facts_live_time_idx ON facts (kb_id, valid_from, valid_to) WHERE invalidated_at IS NULL;
+-- 时态冲突检测的不变量点查:主语侧与宾语侧各一(开放期 + 未作废)
+CREATE INDEX facts_open_pair_idx ON facts (kb_id, subject_id, predicate_id)
+ WHERE valid_to IS NULL AND invalidated_at IS NULL;
+CREATE INDEX facts_open_obj_pair_idx ON facts (kb_id, object_id, predicate_id)
+ WHERE valid_to IS NULL AND invalidated_at IS NULL;
+
+-- 证据链:事实 ↔ 原文分块(溯源一等公民)
+CREATE TABLE fact_evidence (
+ fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ chunk_id UUID NOT NULL REFERENCES chunks(id) ON DELETE CASCADE,
+ quote TEXT,
+ -- 证据出处版本:出自哪份文档的第几版(版本对账与"证据过期"展示的判定依据)
+ document_id UUID REFERENCES documents(id) ON DELETE CASCADE,
+ doc_version INT,
+ PRIMARY KEY (fact_id, chunk_id)
+);
+
+-- 文档的图谱抽取状态(与摄入管道状态分离:两段式可用)
+ALTER TABLE documents ADD COLUMN graph_status TEXT NOT NULL DEFAULT 'none'
+ CHECK (graph_status IN ('none', 'queued', 'extracting', 'done', 'failed'));
+
+-- 时态冲突(S3):自动闭合拿不准的进审,人裁 close / keep / reject_new
+CREATE TABLE fact_conflicts (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ old_fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ new_fact_id UUID NOT NULL REFERENCES facts(id) ON DELETE CASCADE,
+ -- no_time | simultaneous | low_confidence
+ reason TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'resolved')),
+ -- closed | kept_both | rejected_new
+ resolution TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ resolved_at TIMESTAMPTZ,
+ UNIQUE (old_fact_id, new_fact_id)
+);
+CREATE INDEX fact_conflicts_open_idx ON fact_conflicts (kb_id) WHERE status = 'open';
diff --git a/migrations/0005_ontology.sql b/migrations/0005_ontology.sql
new file mode 100644
index 00000000..c1907a04
--- /dev/null
+++ b/migrations/0005_ontology.sql
@@ -0,0 +1,15 @@
+-- 0005: 本体编辑器基础 —— 类型层级(subClassOf 数据面)+ 抽取未匹配统计(LLM 建议流的信号源)
+
+-- 实体类型层级:parent_id = subClassOf(公理推理 P4 点亮;编辑器先落数据)
+ALTER TABLE entity_types ADD COLUMN parent_id UUID REFERENCES entity_types(id) ON DELETE SET NULL;
+
+-- 抽取过程中命中白名单之外的类型/关系:不是垃圾,是本体扩展的信号
+CREATE TABLE ontology_misses (
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ kind TEXT NOT NULL CHECK (kind IN ('entity_type', 'relation_type')),
+ key TEXT NOT NULL,
+ example TEXT,
+ count INT NOT NULL DEFAULT 1,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kb_id, kind, key)
+);
diff --git a/migrations/0006_resolution.sql b/migrations/0006_resolution.sql
new file mode 100644
index 00000000..590d62a5
--- /dev/null
+++ b/migrations/0006_resolution.sql
@@ -0,0 +1,70 @@
+-- 0006: 实体消解 v2 —— 同名≠同人。
+-- 设计见 docs/DESIGN.md §4:名字只是候选召回线索,身份由上下文(画像向量 + 关系兼容性)决定;
+-- 宁分勿合,灰区先落审核队列,LLM 攒批裁决在后台跑,人工终审兜底。
+
+-- 名字不再是身份:拆掉同名唯一索引,同名实体允许并存;保留普通索引做候选召回
+DROP INDEX entities_kb_type_name_idx;
+CREATE INDEX entities_kb_type_name_idx
+ ON entities (kb_id, type_id, lower(canonical_name)) WHERE merged_into IS NULL;
+
+-- 实体画像:证据分块向量的增量质心(上下文相似度判定用;复用摄入阶段已算好的 chunk embedding)
+ALTER TABLE entities ADD COLUMN profile_embedding vector;
+ALTER TABLE entities ADD COLUMN profile_n INTEGER NOT NULL DEFAULT 0;
+-- 同名并存时的展示消歧后缀(如 张三 · Platform Engineering)
+ALTER TABLE entities ADD COLUMN disambiguator TEXT;
+
+-- 消解审核队列:疑似同一实体的灰区对。
+-- stage: adjudicating = 等 LLM 攒批裁决;human = LLM 不确定/未配模型,等人工终审。
+-- status: pending → merged / kept。
+CREATE TABLE resolution_reviews (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ left_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ right_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ score REAL NOT NULL DEFAULT 0,
+ reason TEXT,
+ stage TEXT NOT NULL DEFAULT 'adjudicating' CHECK (stage IN ('adjudicating', 'human')),
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'merged', 'kept')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ decided_at TIMESTAMPTZ,
+ decided_by UUID REFERENCES users(id)
+);
+CREATE UNIQUE INDEX resolution_reviews_pair_idx
+ ON resolution_reviews (kb_id, least(left_id, right_id), greatest(left_id, right_id))
+ WHERE status = 'pending';
+CREATE INDEX resolution_reviews_kb_pending_idx
+ ON resolution_reviews (kb_id, created_at) WHERE status = 'pending';
+
+-- LLM 裁决缓存:同一对(名字 + 上下文摘要哈希)不重复付费;same 为 NULL 表示模型也不确定
+CREATE TABLE resolution_verdicts (
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ pair_key TEXT NOT NULL,
+ same BOOLEAN,
+ confidence REAL NOT NULL DEFAULT 0,
+ model TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kb_id, pair_key)
+);
+
+-- 合并日志:记录被移动/作废的事实与目标实体画像快照,支持精确回滚
+CREATE TABLE entity_merges (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ source_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ target_id UUID NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ moved_subject_facts UUID[] NOT NULL DEFAULT '{}',
+ moved_object_facts UUID[] NOT NULL DEFAULT '{}',
+ invalidated_facts UUID[] NOT NULL DEFAULT '{}',
+ -- 合并后时态对账产生的修正行(成因是合并本身,回滚时随之撤销)
+ temporal_corrections UUID[] NOT NULL DEFAULT '{}',
+ target_profile_before vector,
+ target_profile_n_before INTEGER NOT NULL DEFAULT 0,
+ -- 类型调和(concept 目标被具体类型升格)的回滚快照
+ target_type_before UUID REFERENCES entity_types(id),
+ -- NULL = 自动合并(LLM 裁决高置信)
+ merged_by UUID REFERENCES users(id),
+ reason TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ reverted_at TIMESTAMPTZ
+);
+CREATE INDEX entity_merges_kb_idx ON entity_merges (kb_id, created_at DESC);
diff --git a/migrations/0007_sources.sql b/migrations/0007_sources.sql
new file mode 100644
index 00000000..3edd32f0
--- /dev/null
+++ b/migrations/0007_sources.sql
@@ -0,0 +1,16 @@
+-- 0007: 来源即文件夹 —— source 是 Library 中的容器,挂着它摄入的文档,可定时同步。
+-- kind: upload(手动上传的虚拟归属,通常 source_id 为 NULL)| watch_folder | url | rss | api
+-- 设计见 docs/DESIGN.md §4 摄入渠道。
+
+ALTER TABLE sources ADD COLUMN config JSONB NOT NULL DEFAULT '{}';
+-- NULL = 仅手动同步
+ALTER TABLE sources ADD COLUMN sync_interval_minutes INTEGER;
+ALTER TABLE sources ADD COLUMN last_sync_at TIMESTAMPTZ;
+ALTER TABLE sources ADD COLUMN last_sync_status TEXT NOT NULL DEFAULT 'never'
+ CHECK (last_sync_status IN ('never', 'queued', 'running', 'ok', 'failed'));
+ALTER TABLE sources ADD COLUMN last_sync_error TEXT;
+ALTER TABLE sources ADD COLUMN last_sync_added INTEGER NOT NULL DEFAULT 0;
+
+-- 文档标签(过滤与批量组织;不做实体文件夹)
+ALTER TABLE documents ADD COLUMN tags TEXT[] NOT NULL DEFAULT '{}';
+CREATE INDEX documents_tags_idx ON documents USING gin (tags);
diff --git a/migrations/0008_doc_identity.sql b/migrations/0008_doc_identity.sql
new file mode 100644
index 00000000..802e9389
--- /dev/null
+++ b/migrations/0008_doc_identity.sql
@@ -0,0 +1,19 @@
+-- 0008: 文档逻辑身份 —— 摄入的三路判定(新增 / 变更 / 未变)。
+-- external_key = 来源内的逻辑身份(watch_folder 相对路径 / url / rss guid / api external_id);
+-- 内容变更时原地替换文档(不再堆积新文档),旧版本记入 document_versions(版本回放的原料,
+-- 文件 blob 内容寻址不删)。目录里消失的文件标记 missing_since(默认保留不删)。
+
+ALTER TABLE documents ADD COLUMN external_key TEXT;
+ALTER TABLE documents ADD COLUMN missing_since TIMESTAMPTZ;
+CREATE UNIQUE INDEX documents_source_key_idx
+ ON documents (source_id, external_key) WHERE external_key IS NOT NULL;
+
+CREATE TABLE document_versions (
+ id UUID PRIMARY KEY,
+ document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
+ version INTEGER NOT NULL,
+ sha256 TEXT NOT NULL,
+ size_bytes BIGINT NOT NULL DEFAULT 0,
+ ingested_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (document_id, version)
+);
diff --git a/migrations/0009_source_icon.sql b/migrations/0009_source_icon.sql
new file mode 100644
index 00000000..35890bcb
--- /dev/null
+++ b/migrations/0009_source_icon.sql
@@ -0,0 +1,2 @@
+-- 0009: 来源自定义图标(lucide 图标名,NULL 时前端按 kind 取默认图标)
+ALTER TABLE sources ADD COLUMN icon TEXT;
diff --git a/migrations/0010_sync_cron.sql b/migrations/0010_sync_cron.sql
new file mode 100644
index 00000000..4d8df5b1
--- /dev/null
+++ b/migrations/0010_sync_cron.sql
@@ -0,0 +1,3 @@
+-- 0010: 来源定时同步支持 cron 表达式(标准 5 段,与 sync_interval_minutes 互斥;
+-- UI 提供可视化选择器构建,Advanced 模式才暴露原生表达式)
+ALTER TABLE sources ADD COLUMN sync_cron TEXT;
diff --git a/migrations/0011_sync_runs.sql b/migrations/0011_sync_runs.sql
new file mode 100644
index 00000000..ed59a21f
--- /dev/null
+++ b/migrations/0011_sync_runs.sql
@@ -0,0 +1,14 @@
+-- 0011: 来源同步运行记录 —— 每次同步一行(时间/状态/产出/错误),渠道的可审计历史。
+-- 每来源仅保留最近 50 条(finish_run 时修剪)。
+
+CREATE TABLE source_sync_runs (
+ id UUID PRIMARY KEY,
+ source_id UUID NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ finished_at TIMESTAMPTZ,
+ status TEXT NOT NULL DEFAULT 'running' CHECK (status IN ('running', 'ok', 'failed')),
+ created_docs INTEGER NOT NULL DEFAULT 0,
+ updated_docs INTEGER NOT NULL DEFAULT 0,
+ error TEXT
+);
+CREATE INDEX source_sync_runs_source_idx ON source_sync_runs (source_id, started_at DESC);
diff --git a/migrations/0012_kb_access.sql b/migrations/0012_kb_access.sql
new file mode 100644
index 00000000..6b3e79ba
--- /dev/null
+++ b/migrations/0012_kb_access.sql
@@ -0,0 +1,28 @@
+-- 0012: KB 级访问控制 + 部署配置。
+-- 设计(2026-08-26 拍板):部署角色挂隐形 workspace(memberships 不动);
+-- 每个 KB 自带角色矩阵(kb_members,viewer|editor|admin),在库自己的 Settings 里配置;
+-- open 库无矩阵记录时按部署角色行事,restricted 库仅矩阵成员可见(外人 NotFound)。
+-- 注册开关从 env 升级为库内配置(/admin 可切)。
+
+ALTER TABLE knowledge_bases ADD COLUMN visibility TEXT NOT NULL DEFAULT 'open'
+ CHECK (visibility IN ('open', 'restricted'));
+-- 默认库永远 open(is_default 列见 0001;规则在 API 强制,这里 DB 级双保险)
+ALTER TABLE knowledge_bases ADD CONSTRAINT kb_default_open
+ CHECK (NOT is_default OR visibility = 'open');
+
+CREATE TABLE kb_members (
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ role TEXT NOT NULL CHECK (role IN ('viewer', 'editor', 'admin')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kb_id, user_id)
+);
+
+CREATE TABLE deployment_settings (
+ singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton),
+ open_registration BOOLEAN NOT NULL DEFAULT TRUE,
+ -- 任务 worker 并发数(系统设置可改;调度循环热读,改动即时生效)
+ worker_concurrency INT NOT NULL DEFAULT 4
+ CHECK (worker_concurrency BETWEEN 1 AND 32)
+);
+INSERT INTO deployment_settings DEFAULT VALUES;
diff --git a/migrations/0013_entity_shape.sql b/migrations/0013_entity_shape.sql
new file mode 100644
index 00000000..644a72f1
--- /dev/null
+++ b/migrations/0013_entity_shape.sql
@@ -0,0 +1,6 @@
+-- 0013: 实体类型形状升格为本体属性(此前 organization/product = 方形是前端写死的)。
+-- 图谱节点按类型的 shape 渲染:circle(四层圆)| square(四层方)。
+ALTER TABLE entity_types ADD COLUMN shape TEXT NOT NULL DEFAULT 'circle'
+ CHECK (shape IN ('circle', 'square'));
+-- 保持现有观感:内置的组织/产品沿用方形
+UPDATE entity_types SET shape = 'square' WHERE key IN ('organization', 'product');
diff --git a/migrations/0014_type_descriptions.sql b/migrations/0014_type_descriptions.sql
new file mode 100644
index 00000000..00aef261
--- /dev/null
+++ b/migrations/0014_type_descriptions.sql
@@ -0,0 +1,4 @@
+-- 类型描述:不是给人看的装饰,是喂给抽取 prompt 的语义指引
+-- ("Event: 有明确时间点的事件,如发布、收购、会议"),直接影响抽取质量。
+ALTER TABLE entity_types ADD COLUMN description TEXT NOT NULL DEFAULT '';
+ALTER TABLE relation_types ADD COLUMN description TEXT NOT NULL DEFAULT '';
diff --git a/migrations/0015_source_ingest_tokens.sql b/migrations/0015_source_ingest_tokens.sql
new file mode 100644
index 00000000..4cc704e3
--- /dev/null
+++ b/migrations/0015_source_ingest_tokens.sql
@@ -0,0 +1,3 @@
+-- api 来源的专属推送密钥:只存 sha256 十六进制哈希,明文仅在创建/轮换时返回一次。
+-- KB 级 /ingest 改为落入 Uploads(普通上传语义);带身份的推送走 api 来源 + 本密钥。
+ALTER TABLE sources ADD COLUMN ingest_token_hash TEXT;
diff --git a/migrations/0016_source_token_plaintext.sql b/migrations/0016_source_token_plaintext.sql
new file mode 100644
index 00000000..c5d77676
--- /dev/null
+++ b/migrations/0016_source_token_plaintext.sql
@@ -0,0 +1,4 @@
+-- 自部署威胁模型下"只看一次"是自找麻烦:改存明文,随时可查(Editor 权限专用端点)。
+-- DB 失守时文档本体早已泄露,密钥哈希化没有额外收益;Rotate 保留应对泄露。
+ALTER TABLE sources DROP COLUMN ingest_token_hash;
+ALTER TABLE sources ADD COLUMN ingest_token TEXT;
diff --git a/migrations/0017_kb_member_added_by.sql b/migrations/0017_kb_member_added_by.sql
new file mode 100644
index 00000000..a3fff611
--- /dev/null
+++ b/migrations/0017_kb_member_added_by.sql
@@ -0,0 +1,4 @@
+-- 加入信息:记录把成员加进库的人(历史行留 NULL,展示退化为只有时间)。
+-- IF NOT EXISTS:允许开发期手动预应用与启动迁移共存。
+ALTER TABLE kb_members
+ ADD COLUMN IF NOT EXISTS added_by uuid REFERENCES users(id) ON DELETE SET NULL;
diff --git a/migrations/0018_audit_events.sql b/migrations/0018_audit_events.sql
new file mode 100644
index 00000000..fcf92186
--- /dev/null
+++ b/migrations/0018_audit_events.sql
@@ -0,0 +1,14 @@
+-- 审计日志:谁在何时对什么做了什么(纯审计,不承载回滚等衍生功能)。
+-- detail 存变更要点(jsonb,按 action 语义自定),actor 删号后置 NULL 保留事件。
+CREATE TABLE IF NOT EXISTS audit_events (
+ id UUID PRIMARY KEY,
+ kb_id UUID REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ actor_id UUID REFERENCES users(id) ON DELETE SET NULL,
+ action TEXT NOT NULL,
+ target_kind TEXT NOT NULL,
+ target_id UUID,
+ detail JSONB NOT NULL DEFAULT '{}',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS audit_events_kb_time_idx
+ ON audit_events (kb_id, created_at DESC);
diff --git a/migrations/0019_conversations.sql b/migrations/0019_conversations.sql
new file mode 100644
index 00000000..370eb07d
--- /dev/null
+++ b/migrations/0019_conversations.sql
@@ -0,0 +1,26 @@
+-- 0019: Chat 会话持久化——对话、消息、行动轨迹与引用随消息落库。
+-- 上下文由服务端从这里拼装(前端只传 conversation_id + 新消息);
+-- steps/sources 与实时 SSE 事件同构,历史回放与流式渲染共用一套组件。
+
+CREATE TABLE conversations (
+ id UUID PRIMARY KEY,
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ title TEXT NOT NULL DEFAULT '',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX conversations_kb_user_idx ON conversations (kb_id, user_id, updated_at DESC);
+
+CREATE TABLE conversation_messages (
+ id UUID PRIMARY KEY,
+ conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
+ content TEXT NOT NULL,
+ -- 行动轨迹(工具调用步骤)与引用清单(历史回放;与 SSE step/sources 同构)
+ steps JSONB NOT NULL DEFAULT '[]',
+ sources JSONB NOT NULL DEFAULT '[]',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX conversation_messages_conv_idx
+ ON conversation_messages (conversation_id, created_at);
diff --git a/migrations/0020_data_sources.sql b/migrations/0020_data_sources.sql
new file mode 100644
index 00000000..b66f7e21
--- /dev/null
+++ b/migrations/0020_data_sources.sql
@@ -0,0 +1,23 @@
+-- 问数刀 1:数据源两层模型(应用后按迭代期策略折入基础迁移并删除本文件)。
+-- 系统层注册连接(凭据集中、跨 KB 复用),知识库层挂载授权(问数权限跟 KB 走)。
+
+CREATE TABLE data_sources (
+ id UUID PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ -- 首发仅 postgres;mysql/clickhouse 后续加驱动
+ engine TEXT NOT NULL CHECK (engine IN ('postgres')),
+ -- 连接串(含凭据)。与 llm_settings 的 api key 同待遇:静态加密是发布前统一硬化项
+ conn_string TEXT NOT NULL,
+ created_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ last_test_at TIMESTAMPTZ,
+ last_test_ok BOOLEAN
+);
+
+-- KB 挂载:本库的 Chat 才能问到挂载的源
+CREATE TABLE kb_data_sources (
+ kb_id UUID NOT NULL REFERENCES knowledge_bases(id) ON DELETE CASCADE,
+ data_source_id UUID NOT NULL REFERENCES data_sources(id) ON DELETE CASCADE,
+ mounted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (kb_id, data_source_id)
+);
diff --git a/scripts/e2e_type_drift.mjs b/scripts/e2e_type_drift.mjs
new file mode 100644
index 00000000..4a6c67a8
--- /dev/null
+++ b/scripts/e2e_type_drift.mjs
@@ -0,0 +1,248 @@
+#!/usr/bin/env node
+// 端到端:实体消解的类型漂移处理。
+//
+// 场景:同一团队名被三份文档抽成三种类型——organization / project / team(白名单外,
+// 降级 concept 兜底)。期望:漂移对进审核队列 → mock 裁决全部 "same" → 链式合并收敛为
+// 一个实体(类型调和后非 concept),leads 时间线连贯(前任在新任起点自动闭合)。
+//
+// 本脚本内嵌 mock LLM(OpenAI 兼容 /chat/completions:按分块标记回放抽取结果,
+// 按提示词特征识别裁决请求并全判 same)。无 embedding 配置 → 走"无上下文可比"的
+// 宁分勿合 + 审核对路径。
+//
+// 前置:utopia-server 已启动并连到一个干净的库。编排见 scripts/e2e_type_drift.sh。
+// 环境变量:E2E_BASE(默认 http://127.0.0.1:8317)、E2E_MOCK_PORT(默认 9317)。
+
+import http from "node:http";
+
+const BASE = process.env.E2E_BASE || "http://127.0.0.1:8317";
+const MOCK_PORT = Number(process.env.E2E_MOCK_PORT || 9317);
+
+// ---------------------------------------------------------------------------
+// mock LLM
+// ---------------------------------------------------------------------------
+
+const EXTRACTIONS = {
+ "E2E-DOC1": {
+ entities: [
+ { name: "Orion platform team", type: "organization" },
+ { name: "Alice Zhang", type: "person" },
+ ],
+ facts: [
+ {
+ subject: "Alice Zhang",
+ predicate: "leads",
+ object: "Orion platform team",
+ valid_from: "2023-01-15",
+ confidence: 0.95,
+ quote: "Alice Zhang has led the Orion platform team since 2023-01-15.",
+ },
+ ],
+ },
+ "E2E-DOC2": {
+ entities: [
+ { name: "Orion platform team", type: "project" },
+ { name: "Bob Li", type: "person" },
+ ],
+ facts: [
+ {
+ subject: "Bob Li",
+ predicate: "leads",
+ object: "Orion platform team",
+ valid_from: "2024-05-20",
+ confidence: 0.95,
+ quote: "Bob Li took over as lead of the Orion platform team on 2024-05-20.",
+ },
+ ],
+ },
+ // "team" 不在内置本体白名单 → 抽取端降级 concept(record_miss + 兜底),
+ // 正是类型漂移的第三条腿
+ "E2E-DOC3": {
+ entities: [
+ { name: "Orion platform team", type: "team" },
+ { name: "Utopia Labs", type: "organization" },
+ ],
+ facts: [
+ {
+ subject: "Orion platform team",
+ predicate: "part_of",
+ object: "Utopia Labs",
+ confidence: 0.9,
+ quote: "The Orion platform team is part of Utopia Labs.",
+ },
+ ],
+ },
+};
+
+function mockReply(messages) {
+ const all = messages.map((m) => m.content).join("\n");
+ let payload;
+ if (all.includes("entity-resolution adjudicator")) {
+ const pairs = [...all.matchAll(/^Pair (\d+):/gm)].map((m) => Number(m[1]));
+ payload = {
+ verdicts: pairs.map((i) => ({ i, verdict: "same", confidence: 0.95 })),
+ };
+ } else {
+ const marker = Object.keys(EXTRACTIONS).find((k) => all.includes(k));
+ payload = marker ? EXTRACTIONS[marker] : { entities: [], facts: [] };
+ }
+ return "```json\n" + JSON.stringify(payload) + "\n```";
+}
+
+function startMock() {
+ return new Promise((resolve) => {
+ const srv = http.createServer((req, res) => {
+ let body = "";
+ req.on("data", (c) => (body += c));
+ req.on("end", () => {
+ if (!req.url.endsWith("/chat/completions")) {
+ res.writeHead(404).end();
+ return;
+ }
+ const messages = JSON.parse(body).messages || [];
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(
+ JSON.stringify({
+ choices: [{ message: { content: mockReply(messages) } }],
+ }),
+ );
+ });
+ });
+ srv.listen(MOCK_PORT, "127.0.0.1", () => resolve(srv));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// API driver
+// ---------------------------------------------------------------------------
+
+let cookie = "";
+
+async function api(method, path, body) {
+ const res = await fetch(`${BASE}/api/v1${path}`, {
+ method,
+ headers: {
+ "content-type": "application/json",
+ ...(cookie ? { cookie } : {}),
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ const setCookie = res.headers.get("set-cookie");
+ if (setCookie) cookie = setCookie.split(";")[0];
+ const text = await res.text();
+ if (!res.ok) throw new Error(`${method} ${path} -> ${res.status}: ${text}`);
+ return text ? JSON.parse(text) : {};
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function poll(desc, timeoutMs, fn) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const v = await fn();
+ if (v !== undefined) return v;
+ if (Date.now() > deadline) throw new Error(`timeout waiting for: ${desc}`);
+ await sleep(1500);
+ }
+}
+
+let failures = 0;
+function check(cond, label) {
+ console.log(`${cond ? "PASS" : "FAIL"}: ${label}`);
+ if (!cond) failures++;
+}
+
+async function pushDocAndWait(kbId, filename, content) {
+ await api("POST", `/kbs/${kbId}/ingest`, { filename, content });
+ // 逐篇等抽取完成:消解按落库顺序看见前一篇的实体,漂移路径确定性触发
+ await poll(`${filename} graph done`, 120000, async () => {
+ const documents = await api("GET", `/kbs/${kbId}/documents`);
+ const d = documents.find((d) => d.filename === filename);
+ if (d && d.graph_status === "failed") throw new Error(`${filename} extraction failed`);
+ return d && d.graph_status === "done" ? true : undefined;
+ });
+}
+
+async function main() {
+ const mock = await startMock();
+ console.log(`mock LLM on 127.0.0.1:${MOCK_PORT}`);
+
+ const stamp = Date.now();
+ await api("POST", "/auth/register", {
+ email: `e2e-drift-${stamp}@test.local`,
+ password: "password123",
+ display_name: "Drift E2E",
+ });
+ const wsId = (await api("POST", "/workspaces", { name: `Drift WS ${stamp}` })).id;
+ const kbId = (await api("POST", `/workspaces/${wsId}/kbs`, { name: "Drift KB" })).id;
+
+ await api("PUT", `/workspaces/${wsId}/settings`, {
+ chat_base_url: `http://127.0.0.1:${MOCK_PORT}/v1`,
+ chat_api_key: "mock",
+ chat_model: "mock-adjudicator",
+ });
+
+ await pushDocAndWait(kbId, "orion-org-chart.md",
+ "[E2E-DOC1] Org chart update. Alice Zhang has led the Orion platform team since 2023-01-15.");
+ await pushDocAndWait(kbId, "orion-roadmap.md",
+ "[E2E-DOC2] Roadmap. Bob Li took over as lead of the Orion platform team on 2024-05-20.");
+ await pushDocAndWait(kbId, "orion-wiki.md",
+ "[E2E-DOC3] Wiki. The Orion platform team is part of Utopia Labs.");
+
+ // 攒批裁决在后台链式合并:等审核队列清空且同名实体收敛为一个
+ const survivor = await poll("adjudication converges to one entity", 90000, async () => {
+ const review = await api("GET", `/kbs/${kbId}/review`);
+ const { entities } = await api("GET", `/kbs/${kbId}/entities?q=Orion`);
+ return review.reviews.length === 0 && entities.length === 1 ? entities[0] : undefined;
+ });
+
+ check(survivor.name === "Orion platform team", `survivor name (${survivor.name})`);
+ check(survivor.type_key !== "concept",
+ `type reconciled to a specific type, not the concept fallback (${survivor.type_key})`);
+ check(survivor.disambiguator === null || survivor.disambiguator === undefined,
+ "no disambiguator once the group collapsed to one entity");
+
+ const review = await api("GET", `/kbs/${kbId}/review`);
+ check(review.merges.length >= 2,
+ `chain merges recorded in entity_merges ledger (${review.merges.length})`);
+ check(review.merges.every((m) => /auto-merge/.test(m.reason ?? "")),
+ "merges came from LLM adjudication, not manual action");
+
+ const { facts } = await api("GET", `/kbs/${kbId}/entities/${survivor.id}`);
+ const leads = facts.filter((f) => f.predicate_key === "leads" && f.direction === "in");
+ check(leads.length === 2, `one coherent leads timeline with 2 live facts (${leads.length})`);
+ const alice = leads.find((f) => f.other_name === "Alice Zhang");
+ const bob = leads.find((f) => f.other_name === "Bob Li");
+ check(!!alice && (alice.valid_from ?? "").startsWith("2023-01-15"),
+ "Alice's tenure starts 2023-01-15");
+ check(!!alice && (alice.valid_to ?? "").startsWith("2024-05-20"),
+ `Alice's tenure auto-closed at Bob's start (valid_to=${alice?.valid_to})`);
+ check(!!bob && (bob.valid_from ?? "").startsWith("2024-05-20") && bob.valid_to === null,
+ "Bob's tenure open from 2024-05-20");
+ const partOf = facts.find((f) => f.predicate_key === "part_of" && f.direction === "out");
+ check(!!partOf && partOf.other_name === "Utopia Labs",
+ "concept-side fact (part_of Utopia Labs) survived the merge onto the survivor");
+
+ // 可回滚:撤销最近一次合并 → 被并方复活、类型恢复快照、同名组重新出现
+ await api("POST", `/kbs/${kbId}/merges/${review.merges[0].id}/revert`);
+ const after = await api("GET", `/kbs/${kbId}/entities?q=Orion`);
+ check(after.entities.length === 2,
+ `revert revives the merged-away entity (${after.entities.length} entities)`);
+ const revived = after.entities.find((e) => e.id !== survivor.id);
+ check(!!revived && revived.type_key !== survivor.type_key,
+ `revived entity keeps its own original type (${revived?.type_key})`);
+ const ledger = await api("GET", `/kbs/${kbId}/review`);
+ check(ledger.merges.some((m) => m.reverted_at !== null),
+ "ledger marks the merge as reverted");
+
+ mock.close();
+ if (failures > 0) {
+ console.error(`\n${failures} assertion(s) failed`);
+ process.exit(1);
+ }
+ console.log("\nE2E type-drift: all assertions passed");
+}
+
+main().catch((e) => {
+ console.error(`E2E error: ${e.message}`);
+ process.exit(1);
+});
diff --git a/scripts/e2e_type_drift.sh b/scripts/e2e_type_drift.sh
new file mode 100644
index 00000000..a17cdd2b
--- /dev/null
+++ b/scripts/e2e_type_drift.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# 类型漂移 E2E 编排:独立数据库 + 独立端口起 server,跑 scripts/e2e_type_drift.mjs。
+# 前置:compose 的 db 容器已在跑(docker compose up -d db)、node ≥ 18。
+# 用法: ./scripts/e2e_type_drift.sh
+set -euo pipefail
+cd "$(dirname "$0")/.."
+
+DB_CONTAINER="${E2E_DB_CONTAINER:-landscapebi-db-1}"
+DB_NAME="utopia_e2e"
+PORT="${E2E_PORT:-8317}"
+DATA_DIR="$(mktemp -d)"
+
+echo "--- 重建隔离数据库 $DB_NAME"
+docker exec "$DB_CONTAINER" psql -U utopia -d postgres \
+ -c "DROP DATABASE IF EXISTS $DB_NAME;" -c "CREATE DATABASE $DB_NAME;" >/dev/null
+
+echo "--- 构建 utopia-server"
+cargo build -p utopia-server
+
+echo "--- 启动 server (127.0.0.1:$PORT, db=$DB_NAME)"
+UTOPIA_DATABASE_URL="postgres://utopia:utopia@localhost:5432/$DB_NAME" \
+UTOPIA_BIND_ADDR="127.0.0.1:$PORT" \
+UTOPIA_DATA_DIR="$DATA_DIR" \
+ ./target/debug/utopia-server &
+SERVER_PID=$!
+trap 'kill $SERVER_PID 2>/dev/null || true; rm -rf "$DATA_DIR"' EXIT
+
+for i in $(seq 1 30); do
+ curl -sf "http://127.0.0.1:$PORT/api/v1/health" >/dev/null 2>&1 && break
+ sleep 1
+done
+curl -sf "http://127.0.0.1:$PORT/api/v1/health" >/dev/null || { echo "server 未就绪" >&2; exit 1; }
+
+echo "--- 运行 E2E"
+E2E_BASE="http://127.0.0.1:$PORT" node scripts/e2e_type_drift.mjs
diff --git a/scripts/smoke.sh b/scripts/smoke.sh
new file mode 100644
index 00000000..c08bc439
--- /dev/null
+++ b/scripts/smoke.sh
@@ -0,0 +1,83 @@
+#!/usr/bin/env bash
+# 端到端冒烟测试:注册 → 登录态 → 工作区 → 知识库 → 权限 → 任务队列
+# 用法: ./scripts/smoke.sh [BASE_URL] (默认 http://localhost:8080)
+# JSON body 走临时文件,避免 Windows shell 的编码转换问题。
+set -euo pipefail
+
+BASE="${1:-http://localhost:8080}"
+EMAIL="smoke-$(date +%s)@test.local"
+JAR="$(mktemp)"
+BODY="$(mktemp)"
+trap 'rm -f "$JAR" "$BODY"' EXIT
+
+step() { echo "--- $1"; }
+fail() { echo "FAIL: $1" >&2; exit 1; }
+
+step "health"
+curl -sf "$BASE/api/v1/health" | grep -q '"ok"' || fail "health"
+
+step "register ($EMAIL)"
+printf '{"email":"%s","password":"password123","display_name":"Smoke Tester"}' "$EMAIL" > "$BODY"
+curl -sf -c "$JAR" -H 'Content-Type: application/json' --data-binary @"$BODY" \
+ "$BASE/api/v1/auth/register" | grep -q '"user"' || fail "register"
+
+step "me (cookie 认证)"
+curl -sf -b "$JAR" "$BASE/api/v1/auth/me" | grep -q "$EMAIL" || fail "me"
+
+step "workspaces(应至少含默认工作区)"
+curl -sf -b "$JAR" "$BASE/api/v1/workspaces" | grep -q '"id"' || fail "workspace list 为空"
+
+step "创建自己的工作区(成为 owner)"
+printf '{"name":"Smoke WS"}' > "$BODY"
+WS_ID=$(curl -sf -b "$JAR" -H 'Content-Type: application/json' --data-binary @"$BODY" \
+ "$BASE/api/v1/workspaces" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p' | head -1)
+[ -n "$WS_ID" ] || fail "create workspace"
+echo " workspace: $WS_ID"
+
+step "创建知识库"
+printf '{"name":"Smoke KB"}' > "$BODY"
+KB_ID=$(curl -sf -b "$JAR" -H 'Content-Type: application/json' --data-binary @"$BODY" \
+ "$BASE/api/v1/workspaces/$WS_ID/kbs" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p' | head -1)
+[ -n "$KB_ID" ] || fail "create kb"
+echo " kb: $KB_ID"
+
+step "上传文档(中英混合 markdown)"
+# 注意:不要用 curl 的 ";filename=" 语法——Git Bash 的 MSYS 路径转换会把含分号的参数弄坏
+DOCDIR="$(mktemp -d)"
+DOC="$DOCDIR/smoke.md"
+# “凤凰项目由张三负责。” 以 UTF-8 字节写入,绕开 Windows shell 编码转换
+printf '# Phoenix Handbook\n\n\xe5\x87\xa4\xe5\x87\xb0\xe9\xa1\xb9\xe7\x9b\xae\xe7\x94\xb1\xe5\xbc\xa0\xe4\xb8\x89\xe8\xb4\x9f\xe8\xb4\xa3\xe3\x80\x82 Budget is 12 million CNY.\n' > "$DOC"
+curl -sf -b "$JAR" -F "files=@$DOC" \
+ "$BASE/api/v1/kbs/$KB_ID/documents" | grep -q '"created"' || fail "upload"
+rm -rf "$DOCDIR"
+
+step "等待摄入管道完成"
+for i in $(seq 1 20); do
+ S=$(curl -sf -b "$JAR" "$BASE/api/v1/kbs/$KB_ID/documents" | grep -o '"status":"[^"]*"' | head -1)
+ case "$S" in
+ *ready*) break;;
+ *failed*) fail "文档处理失败";;
+ esac
+ sleep 2
+done
+case "$S" in *ready*) ;; *) fail "处理超时(当前 $S)";; esac
+
+step "中文搜索(凤凰项目)"
+printf '{"q":"\xe5\x87\xa4\xe5\x87\xb0\xe9\xa1\xb9\xe7\x9b\xae"}' > "$BODY"
+curl -sf -b "$JAR" -H 'Content-Type: application/json' --data-binary @"$BODY" \
+ "$BASE/api/v1/kbs/$KB_ID/search" | grep -q '"filename":"smoke.md"' || fail "中文搜索未命中"
+
+step "未认证访问应 401"
+CODE=$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/v1/workspaces")
+[ "$CODE" = "401" ] || fail "预期 401,实际 $CODE"
+
+step "登录(第二会话)"
+printf '{"email":"%s","password":"password123"}' "$EMAIL" > "$BODY"
+curl -sf -c "$JAR.2" -H 'Content-Type: application/json' --data-binary @"$BODY" \
+ "$BASE/api/v1/auth/login" | grep -q '"token"' || fail "login"
+rm -f "$JAR.2"
+
+step "入队 noop 任务"
+curl -sf -b "$JAR" -X POST "$BASE/api/v1/jobs/noop" | grep -q '"job_id"' || fail "enqueue"
+
+echo "=== 冒烟测试全部通过 ==="
diff --git a/web/data/files/dbf6e5cc9155834907dece9b23e3bbc80244fcb22ce8162ef6a17f1f99f2ec94 b/web/data/files/dbf6e5cc9155834907dece9b23e3bbc80244fcb22ce8162ef6a17f1f99f2ec94
new file mode 100644
index 00000000..f6a0993f
--- /dev/null
+++ b/web/data/files/dbf6e5cc9155834907dece9b23e3bbc80244fcb22ce8162ef6a17f1f99f2ec94
@@ -0,0 +1,20 @@
+# 凤凰项目管理制度
+
+## 项目背景
+
+凤凰项目是公司 2024 年启动的核心数字化转型项目,目标是在两年内完成全部业务系统的云原生改造。
+
+## 负责人安排
+
+凤凰项目自 2023 年 1 月起由张三担任项目负责人。2024 年 7 月起,项目负责人调整为李四,张三转任技术顾问。
+
+## 预算与周期
+
+项目总预算为 1200 万元,分三期执行:
+- 第一期(2024 年上半年):基础设施迁移,预算 400 万
+- 第二期(2024 年下半年):核心业务系统改造,预算 500 万
+- 第三期(2025 年):数据平台建设,预算 300 万
+
+## 汇报机制
+
+项目负责人每月向技术委员会汇报进展,每季度向董事会提交书面报告。重大风险事项须在 48 小时内上报。
diff --git a/web/data/files/ff94ce5e2550340460a922bdaea59ba05f82b716540b5104ed89771bbb1689df b/web/data/files/ff94ce5e2550340460a922bdaea59ba05f82b716540b5104ed89771bbb1689df
new file mode 100644
index 00000000..61437f79
--- /dev/null
+++ b/web/data/files/ff94ce5e2550340460a922bdaea59ba05f82b716540b5104ed89771bbb1689df
@@ -0,0 +1,3 @@
+# Phoenix Handbook
+
+凤凰项目由张三负责。 Budget is 12 million CNY.
diff --git a/web/data/index/.managed.json b/web/data/index/.managed.json
new file mode 100644
index 00000000..2b8079a5
--- /dev/null
+++ b/web/data/index/.managed.json
@@ -0,0 +1 @@
+["c7717e57324544a1a198b5ffa16ef125.term","762d0901b09f48c781c83b41dd9e9a21.idx","c7717e57324544a1a198b5ffa16ef125.idx","8cac7b9961c2420590015c1f94a74e9b.fieldnorm","c7717e57324544a1a198b5ffa16ef125.store","00684c79ed564b48b38b3e50d60e83f1.fieldnorm","8cac7b9961c2420590015c1f94a74e9b.idx","762d0901b09f48c781c83b41dd9e9a21.term","8cac7b9961c2420590015c1f94a74e9b.store","00684c79ed564b48b38b3e50d60e83f1.pos","762d0901b09f48c781c83b41dd9e9a21.pos","00684c79ed564b48b38b3e50d60e83f1.idx","meta.json","8cac7b9961c2420590015c1f94a74e9b.pos","c7717e57324544a1a198b5ffa16ef125.fieldnorm","c7717e57324544a1a198b5ffa16ef125.fast","8cac7b9961c2420590015c1f94a74e9b.term","762d0901b09f48c781c83b41dd9e9a21.store","c7717e57324544a1a198b5ffa16ef125.pos","00684c79ed564b48b38b3e50d60e83f1.fast","8cac7b9961c2420590015c1f94a74e9b.fast","762d0901b09f48c781c83b41dd9e9a21.fieldnorm","00684c79ed564b48b38b3e50d60e83f1.store","00684c79ed564b48b38b3e50d60e83f1.term","762d0901b09f48c781c83b41dd9e9a21.fast"]
diff --git a/web/data/index/.tantivy-meta.lock b/web/data/index/.tantivy-meta.lock
new file mode 100644
index 00000000..e69de29b
diff --git a/web/data/index/.tantivy-writer.lock b/web/data/index/.tantivy-writer.lock
new file mode 100644
index 00000000..e69de29b
diff --git a/web/data/index/00684c79ed564b48b38b3e50d60e83f1.fast b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.fast
new file mode 100644
index 00000000..e93b75f9
Binary files /dev/null and b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.fast differ
diff --git a/web/data/index/00684c79ed564b48b38b3e50d60e83f1.fieldnorm b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.fieldnorm
new file mode 100644
index 00000000..ae8c5f41
Binary files /dev/null and b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.fieldnorm differ
diff --git a/web/data/index/00684c79ed564b48b38b3e50d60e83f1.idx b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.idx
new file mode 100644
index 00000000..9678170d
Binary files /dev/null and b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.idx differ
diff --git a/web/data/index/00684c79ed564b48b38b3e50d60e83f1.pos b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.pos
new file mode 100644
index 00000000..fab6d450
Binary files /dev/null and b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.pos differ
diff --git a/web/data/index/00684c79ed564b48b38b3e50d60e83f1.store b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.store
new file mode 100644
index 00000000..cb995d6a
Binary files /dev/null and b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.store differ
diff --git a/web/data/index/00684c79ed564b48b38b3e50d60e83f1.term b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.term
new file mode 100644
index 00000000..f610e6b5
Binary files /dev/null and b/web/data/index/00684c79ed564b48b38b3e50d60e83f1.term differ
diff --git a/web/data/index/762d0901b09f48c781c83b41dd9e9a21.fast b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.fast
new file mode 100644
index 00000000..e93b75f9
Binary files /dev/null and b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.fast differ
diff --git a/web/data/index/762d0901b09f48c781c83b41dd9e9a21.fieldnorm b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.fieldnorm
new file mode 100644
index 00000000..ae8c5f41
Binary files /dev/null and b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.fieldnorm differ
diff --git a/web/data/index/762d0901b09f48c781c83b41dd9e9a21.idx b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.idx
new file mode 100644
index 00000000..9678170d
Binary files /dev/null and b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.idx differ
diff --git a/web/data/index/762d0901b09f48c781c83b41dd9e9a21.pos b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.pos
new file mode 100644
index 00000000..fab6d450
Binary files /dev/null and b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.pos differ
diff --git a/web/data/index/762d0901b09f48c781c83b41dd9e9a21.store b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.store
new file mode 100644
index 00000000..6196e7de
Binary files /dev/null and b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.store differ
diff --git a/web/data/index/762d0901b09f48c781c83b41dd9e9a21.term b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.term
new file mode 100644
index 00000000..9f59ac01
Binary files /dev/null and b/web/data/index/762d0901b09f48c781c83b41dd9e9a21.term differ
diff --git a/web/data/index/8cac7b9961c2420590015c1f94a74e9b.fast b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.fast
new file mode 100644
index 00000000..e93b75f9
Binary files /dev/null and b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.fast differ
diff --git a/web/data/index/8cac7b9961c2420590015c1f94a74e9b.fieldnorm b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.fieldnorm
new file mode 100644
index 00000000..ae8c5f41
Binary files /dev/null and b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.fieldnorm differ
diff --git a/web/data/index/8cac7b9961c2420590015c1f94a74e9b.idx b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.idx
new file mode 100644
index 00000000..9678170d
Binary files /dev/null and b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.idx differ
diff --git a/web/data/index/8cac7b9961c2420590015c1f94a74e9b.pos b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.pos
new file mode 100644
index 00000000..fab6d450
Binary files /dev/null and b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.pos differ
diff --git a/web/data/index/8cac7b9961c2420590015c1f94a74e9b.store b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.store
new file mode 100644
index 00000000..fc0264ad
Binary files /dev/null and b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.store differ
diff --git a/web/data/index/8cac7b9961c2420590015c1f94a74e9b.term b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.term
new file mode 100644
index 00000000..d6e016dc
Binary files /dev/null and b/web/data/index/8cac7b9961c2420590015c1f94a74e9b.term differ
diff --git a/web/data/index/c7717e57324544a1a198b5ffa16ef125.fast b/web/data/index/c7717e57324544a1a198b5ffa16ef125.fast
new file mode 100644
index 00000000..e93b75f9
Binary files /dev/null and b/web/data/index/c7717e57324544a1a198b5ffa16ef125.fast differ
diff --git a/web/data/index/c7717e57324544a1a198b5ffa16ef125.fieldnorm b/web/data/index/c7717e57324544a1a198b5ffa16ef125.fieldnorm
new file mode 100644
index 00000000..0b942bf9
Binary files /dev/null and b/web/data/index/c7717e57324544a1a198b5ffa16ef125.fieldnorm differ
diff --git a/web/data/index/c7717e57324544a1a198b5ffa16ef125.idx b/web/data/index/c7717e57324544a1a198b5ffa16ef125.idx
new file mode 100644
index 00000000..d564ab52
Binary files /dev/null and b/web/data/index/c7717e57324544a1a198b5ffa16ef125.idx differ
diff --git a/web/data/index/c7717e57324544a1a198b5ffa16ef125.pos b/web/data/index/c7717e57324544a1a198b5ffa16ef125.pos
new file mode 100644
index 00000000..5727e04f
Binary files /dev/null and b/web/data/index/c7717e57324544a1a198b5ffa16ef125.pos differ
diff --git a/web/data/index/c7717e57324544a1a198b5ffa16ef125.store b/web/data/index/c7717e57324544a1a198b5ffa16ef125.store
new file mode 100644
index 00000000..a75f28ce
Binary files /dev/null and b/web/data/index/c7717e57324544a1a198b5ffa16ef125.store differ
diff --git a/web/data/index/c7717e57324544a1a198b5ffa16ef125.term b/web/data/index/c7717e57324544a1a198b5ffa16ef125.term
new file mode 100644
index 00000000..4334f058
Binary files /dev/null and b/web/data/index/c7717e57324544a1a198b5ffa16ef125.term differ
diff --git a/web/data/index/meta.json b/web/data/index/meta.json
new file mode 100644
index 00000000..cc1179c4
--- /dev/null
+++ b/web/data/index/meta.json
@@ -0,0 +1,83 @@
+{
+ "index_settings": {
+ "docstore_compression": "lz4",
+ "docstore_blocksize": 16384
+ },
+ "segments": [
+ {
+ "segment_id": "8cac7b99-61c2-4205-9001-5c1f94a74e9b",
+ "max_doc": 1,
+ "deletes": null
+ },
+ {
+ "segment_id": "762d0901-b09f-48c7-81c8-3b41dd9e9a21",
+ "max_doc": 1,
+ "deletes": null
+ },
+ {
+ "segment_id": "00684c79-ed56-4b48-b38b-3e50d60e83f1",
+ "max_doc": 1,
+ "deletes": null
+ },
+ {
+ "segment_id": "c7717e57-3245-44a1-a198-b5ffa16ef125",
+ "max_doc": 1,
+ "deletes": null
+ }
+ ],
+ "schema": [
+ {
+ "name": "chunk_id",
+ "type": "text",
+ "options": {
+ "indexing": {
+ "record": "basic",
+ "fieldnorms": true,
+ "tokenizer": "raw"
+ },
+ "stored": true,
+ "fast": false
+ }
+ },
+ {
+ "name": "kb_id",
+ "type": "text",
+ "options": {
+ "indexing": {
+ "record": "basic",
+ "fieldnorms": true,
+ "tokenizer": "raw"
+ },
+ "stored": false,
+ "fast": false
+ }
+ },
+ {
+ "name": "document_id",
+ "type": "text",
+ "options": {
+ "indexing": {
+ "record": "basic",
+ "fieldnorms": true,
+ "tokenizer": "raw"
+ },
+ "stored": false,
+ "fast": false
+ }
+ },
+ {
+ "name": "text",
+ "type": "text",
+ "options": {
+ "indexing": {
+ "record": "position",
+ "fieldnorms": true,
+ "tokenizer": "jieba"
+ },
+ "stored": false,
+ "fast": false
+ }
+ }
+ ],
+ "opstamp": 16
+}
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 00000000..b5aecf3f
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,18 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link
+ rel="stylesheet"
+ href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Inter:wght@400;500;600;700&family=Marcellus&display=swap"
+ />
+ <title>Utopia</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>
diff --git a/web/package.json b/web/package.json
new file mode 100644
index 00000000..f0c077de
--- /dev/null
+++ b/web/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "utopia-web",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "tsc --noEmit && vite build",
+ "typecheck": "tsc --noEmit",
+ "preview": "vite preview"
+ },
+ "dependencies": {
+ "@sigma/node-border": "^3.0.0",
+ "@sigma/node-square": "^3.0.0",
+ "@tanstack/react-query": "^5.62.0",
+ "@tanstack/react-router": "^1.95.0",
+ "graphology": "^0.26.0",
+ "graphology-layout": "^0.6.1",
+ "graphology-layout-forceatlas2": "^0.10.1",
+ "lucide-react": "^1.34.0",
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1",
+ "react-markdown": "^10.1.0",
+ "rehype-highlight": "^7.0.2",
+ "remark-gfm": "^4.0.1",
+ "remend": "^1.3.1",
+ "sigma": "^3.0.3",
+ "thinking-orbs": "^0.3.1"
+ },
+ "devDependencies": {
+ "@tailwindcss/typography": "^0.5.20",
+ "@tailwindcss/vite": "^4.0.0",
+ "@types/node": "^26.3.0",
+ "@types/react": "^18.3.12",
+ "@types/react-dom": "^18.3.1",
+ "@vitejs/plugin-react": "^4.3.4",
+ "tailwindcss": "^4.0.0",
+ "typescript": "^5.7.2",
+ "vite": "^6.0.0"
+ }
+}
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
new file mode 100644
index 00000000..23a34ad8
--- /dev/null
+++ b/web/pnpm-lock.yaml
@@ -0,0 +1,2713 @@
+lockfileVersion: '9.0'
+
+settings:
+ autoInstallPeers: true
+ excludeLinksFromLockfile: false
+
+importers:
+
+ .:
+ dependencies:
+ '@sigma/node-border':
+ specifier: ^3.0.0
+ '@sigma/node-square':
+ specifier: ^3.0.0
+ '@tanstack/react-query':
+ specifier: ^5.62.0
+ version: 5.102.3([email protected])
+ '@tanstack/react-router':
+ specifier: ^1.95.0
+ graphology:
+ specifier: ^0.26.0
+ version: 0.26.0([email protected])
+ graphology-layout:
+ specifier: ^0.6.1
+ version: 0.6.1([email protected])
+ graphology-layout-forceatlas2:
+ specifier: ^0.10.1
+ version: 0.10.1([email protected])
+ lucide-react:
+ specifier: ^1.34.0
+ version: 1.34.0([email protected])
+ react:
+ specifier: ^18.3.1
+ version: 18.3.1
+ react-dom:
+ specifier: ^18.3.1
+ version: 18.3.1([email protected])
+ react-markdown:
+ specifier: ^10.1.0
+ version: 10.1.0(@types/[email protected])([email protected])
+ rehype-highlight:
+ specifier: ^7.0.2
+ version: 7.0.2
+ remark-gfm:
+ specifier: ^4.0.1
+ version: 4.0.1
+ remend:
+ specifier: ^1.3.1
+ version: 1.3.1
+ sigma:
+ specifier: ^3.0.3
+ version: 3.0.3([email protected])
+ thinking-orbs:
+ specifier: ^0.3.1
+ version: 0.3.1([email protected])
+ devDependencies:
+ '@tailwindcss/typography':
+ specifier: ^0.5.20
+ version: 0.5.20([email protected])
+ '@tailwindcss/vite':
+ specifier: ^4.0.0
+ '@types/node':
+ specifier: ^26.3.0
+ version: 26.3.0
+ '@types/react':
+ specifier: ^18.3.12
+ version: 18.3.31
+ '@types/react-dom':
+ specifier: ^18.3.1
+ version: 18.3.7(@types/[email protected])
+ '@vitejs/plugin-react':
+ specifier: ^4.3.4
+ tailwindcss:
+ specifier: ^4.0.0
+ version: 4.3.3
+ typescript:
+ specifier: ^5.7.2
+ version: 5.9.3
+ vite:
+ specifier: ^6.0.0
+
+packages:
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==}
+ engines: {node: '>=6.9.0'}
+ peerDependencies:
+ '@babel/core': ^7.0.0
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==}
+ engines: {node: '>=6.9.0'}
+ peerDependencies:
+ '@babel/core': ^7.0.0-0
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==}
+ engines: {node: '>=6.9.0'}
+ peerDependencies:
+ '@babel/core': ^7.0.0-0
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==}
+ engines: {node: '>=6.9.0'}
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
+ engines: {node: '>=6.9.0'}
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [aix]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [android]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==}
+ engines: {node: '>=18'}
+ cpu: [arm]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==}
+ engines: {node: '>=18'}
+ cpu: [loong64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==}
+ engines: {node: '>=18'}
+ cpu: [mips64el]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==}
+ engines: {node: '>=18'}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==}
+ engines: {node: '>=18'}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==}
+ engines: {node: '>=18'}
+ cpu: [s390x]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [linux]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [netbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [sunos]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==}
+ engines: {node: '>=18'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==}
+ engines: {node: '>=18'}
+ cpu: [ia32]
+ os: [win32]
+
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==}
+ engines: {node: '>=18'}
+ cpu: [x64]
+ os: [win32]
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
+ engines: {node: '>=6.0.0'}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
+
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
+
+ '@napi-rs/[email protected]':
+ resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
+ engines: {node: ^22.20 || ^24.12 || >=25}
+ cpu: [x64]
+ os: [linux]
+
+ '@rolldown/[email protected]':
+ resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-70TeIFezKKy65LgAVyQh+w94/gjWhvPWaLaGGeMEgVrPkQhuj/M5bAYYZzIFUj9Y69oHyTm5Um/R6gcLh4A8JA==}
+ cpu: [arm]
+ os: [android]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-YC86tYIHK6M1IV+wbzO+Bxk8RCBr6ZyWYgWxUCzaZD8mc8rrFoIJDNzDrkHBYRc/wKdrsIXmm6/F7NzrAO+OrA==}
+ cpu: [arm64]
+ os: [android]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-oI+ECtUcli0y0fi4xpW82GdPIXdTkI8G8DSjG2LRuw09fPAGykaWYH/hXxiKuTxiAjiPSTIIuYUqof5Z2hShWw==}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-NwV+1s7TiKrMe4owHyKB/dTLD7ZJD0YEBEhIz+hvav1Cu1GReJjF+rsdNwjzENQeIAbE/CoNiaAc5Vz2h5DPAA==}
+ cpu: [x64]
+ os: [darwin]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-tWtHBTu5gOPK4u4Urtk4qAHW3zZ9rQAmbssO8gp7ELvGTGI3aCiq6NqyTQ0PCIg7KbHJF2UkGDDs77YZGxfjCA==}
+ cpu: [arm64]
+ os: [freebsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-2qPoJiwTvtHQ27NnYvTnsgk8laXWYuVmNESG8WFZBcEPKLfZ3I27qBJarjVRQtwGeYyRfq5ZowHXih9lm2BItw==}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-FQwsTRvLNuHoTdICABJQfbPUSEueISGmnpT06tXTMpfprf5NiKLSXKA0A+w45wJnCmZAnzgqBwbt6ARFuyOi5w==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-BBVTXziw8mY1a4ZbWME9tZyfzqXCDPqaC7Z3heQ29p5dkvXzwL0NwelO8zLa8c3RBKvl3YTuSnBgsBhYBtwjIw==}
+ cpu: [arm]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-w2Iyy9+RqKwx3d9qWMKsJg0FfRBsY0/pXNv0mCQ3ueRvJI6+QAScfD4nrMlzFLs2HNVW6Ew+mtZfDl9b7Ew5/Q==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-YK++KtrFRHYE0P6/RtYEAy9t8F37znP+K03RrIuLPYOL6SVlObRumf/0OE4V/h63xL9DwkWbNssZfmA9hawuDA==}
+ cpu: [arm64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-aBfOG6fP7YkkPmTqPwufRJeFyz7WPpECv9XNbnsk9+vg7rxdih0lbtEel7jcRng4LZrrmU3FfitCFyEj4BWDWg==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-LGaHEOeHNAag9VuS1Crs5DFg4RrU9MPi2nVnNJk9DTePx/B6RRYKVmrIXt2h7YOJlwjaFJ6lwtFDliZxScTLrQ==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-jClvk+J0FC3b7Udvegiw5/4hErbHtmsNsQgENnKXDWtNCJXsJYZH5WURvu7imDOO38xYml24eeh5x3A04ppwCw==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-0OJlaGK+8+B777Ql5okIpD7ua5Ro9+VB9Ve0OKa28OQJZ1RbuUBVNHK/e3pr4BROqsyPl1JrPO1ZxJseCNffcA==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Ygsx+HoNH7afwi1bTIXbnTvVnsO+zurPLSYxybV1hHFVU72OWOCl6v05ql/z0hkpAPx+DK7Kn9Bi7MayCcjLTA==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-pDQxtMGb+OvG3fLwR2OkZlSd47hW+kWg4BYMG/++sR6RqorQccwPTDsxda5hPwiIeIErAnCF9ma3SAU06bdQtQ==}
+ cpu: [riscv64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-0BnUG9mS8I4SSHr3XsxVhuCMEiu+rX61xxZF5vujso4LaiAGFZFxvDjg6Xn6tLPNTUAfuCvQYas4LMQMVsKRSQ==}
+ cpu: [s390x]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Adu/VttB1dpPNW+FEacrZ+xVm9tFty84+RrFzsqlFaPxoJB+9XXyDGtp5dCOoBwGBIEVH0To7lExFXEx0BIF4A==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-NQ3bDvjUbFKmP23671xUlXtKmqVsUBd6M4PQCvbmNtOy06hnQIdKHy8oG/6S3R/S6He1JgPk6A5VT+prAJMYEw==}
+ cpu: [x64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-u2eDAl4+0aFvA13GxlGBtTI3SS3sdgwgtV0HyjZ0QaQVCgNE+jqNGey+GtxWiq+wxr/UycAx/OnfJzApCFamvA==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-XvRb5vfW3wAZQ+ZUG21AnHHDKtNcw99eigzEhjr//NZ3u7SoBaPP0seSc7FgP7p1epAEdAoZckMW9WY/+4w70w==}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-iZPmniy4kNBf5yo2RezbkYNNK5HPbXE9+g+twnbqSng7dtLEJy1SKoxiE/ni4FDacjyuZpEeb9U054N4EoKHYw==}
+ cpu: [arm64]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-mFBBd+LF37fnE8JnYUOH+imj0aPFPK30vpar4ehJkgnLj9sZn8ZxiRENmLtgIwxK7TC8klF6N57fxdNBwQoqOA==}
+ cpu: [ia32]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-ujeqEY3B+zbGn3Z4Q03cUBG/LGWnBJncVT36WER31LcOsQk9+1dmINKKtvmmfChUvRbK1G0R8OhMWFgHgaZtAw==}
+ cpu: [x64]
+ os: [win32]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-hncn90N4sOky0L2LKE5oESKLbxCPeVo4eLA2LSMoDzM+879ml4WSr+Rr4DWknNIVVvS1Hirkc9hx02W6YxS8rQ==}
+ cpu: [x64]
+ os: [win32]
+
+ '@sigma/[email protected]':
+ resolution: {integrity: sha512-mE3zUfjvJVuAMhSjiP/zdlkqe0OVTETxd04XHUwof01YqdzTk0OB4ACJIhWrwgsBXl7tTd9lPuKoroafLh8MtQ==}
+ peerDependencies:
+ sigma: '>=3.0.0-beta.17'
+
+ '@sigma/[email protected]':
+ resolution: {integrity: sha512-hPX2oWo7WeaSe6M3D56AXsrLyg3F+7N/YsodaJh4Sw3KTce0GAFVWWPZZklu9CITz0xi3kEmlCGulqAH0cVG2w==}
+ peerDependencies:
+ sigma: '>=3.0.0-beta.17'
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==}
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==}
+ engines: {node: '>= 20'}
+ cpu: [arm64]
+ os: [android]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==}
+ engines: {node: '>= 20'}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [darwin]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==}
+ engines: {node: '>= 20'}
+ cpu: [arm]
+ os: [linux]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==}
+ engines: {node: '>= 20'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==}
+ engines: {node: '>= 20'}
+ cpu: [arm64]
+ os: [linux]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [linux]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [linux]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==}
+ engines: {node: '>=14.0.0'}
+ cpu: [wasm32]
+ bundledDependencies:
+ - '@napi-rs/wasm-runtime'
+ - '@emnapi/core'
+ - '@emnapi/runtime'
+ - '@tybys/wasm-util'
+ - '@emnapi/wasi-threads'
+ - tslib
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==}
+ engines: {node: '>= 20'}
+ cpu: [arm64]
+ os: [win32]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==}
+ engines: {node: '>= 20'}
+ cpu: [x64]
+ os: [win32]
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==}
+ engines: {node: '>= 20'}
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-hwbzQuNUfcPvbegQFatVPl/MY/tcM9KLl963hQ5laJKPh81TEZ1+dNG9PirGvcaDBkp+BCshExAyKVPW91dozw==}
+ peerDependencies:
+ tailwindcss: '>=3.0.0 || >=4.0.0 || insiders'
+
+ '@tailwindcss/[email protected]':
+ resolution: {integrity: sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==}
+ peerDependencies:
+ vite: ^5.2.0 || ^6 || ^7 || ^8
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-DR9t6lfLVdrjgCwpglrR9DR7Ok8/HlXjcOE+goWXF3zyuLUO/ug7vMbSFxTqrQTtbRghJfyhmIZ0S6LhPIy44w==}
+ engines: {node: '>=20.19'}
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-5O2VEceonqC4uaTLUGglb0hgPouWCJ4K1ykVWyeV8aThhdNCzwpwu01bYoaRNJ9mgFUXS7Kf9utJ46ysT8m+bw==}
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-nHazxUEUQSGJOswGgSL2DI77f2K75WRCowDgaiyEi0ACocZTFKewTv+A/rJfq6QkuE35rVPff1QUT3ClbaePGQ==}
+ peerDependencies:
+ react: ^18 || ^19
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-SIpxvaTKco100a5ZR3ePmArbhtm3XOx+w1dpGYY9gxHDta4iXSKDdQuhLonwJbIMkVJsU1rwXf0UDHMrF/1snw==}
+ engines: {node: '>=20.19'}
+ peerDependencies:
+ react: '>=18.0.0 || >=19.0.0'
+ react-dom: '>=18.0.0 || >=19.0.0'
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-wDwSLvoLwIaNcnx9UNcN9Mb7Y8QwCYq1U1RQZwyN186gnkIoIYI2SOxy8VqH1vFigbkHkk4FmwMAQlghPgDK2g==}
+ engines: {node: '>=20.19'}
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-L3fgrnchriRC2ExBflb8j4uZZURHZfQsmQeyVzhjcHW4kkwVyo8/0h1B2MVzMTrYUJYu6G7EWs14hW/L9putqw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==}
+ peerDependencies:
+ '@types/react': ^18.0.0
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
+
+ '@ungap/[email protected]':
+ resolution: {integrity: sha512-JL+CF0GeLHyPWI0rXu7UnxgiuOm9UQWzadi0OYOJNhNO2q6EZElpwlgXkNkfU1PzANDHq3YcwKVZprdvS+BrbQ==}
+
+ '@vitejs/[email protected]':
+ resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}
+ engines: {node: ^14.18.0 || >=16.0.0}
+ peerDependencies:
+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
+
+ resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}
+
+ resolution: {integrity: sha512-Grytf1xOxOEMTGRwx6rLGKkTabd4vMg3VrKdj/7joCmV0qgh4QwMMO6xh34YEXQqirAuUdgQGa5orJQQ+69RBw==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==}
+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
+ hasBin: true
+
+ resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==}
+
+ resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
+
+ resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}
+
+ resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}
+
+ resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}
+
+ resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}
+
+ resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
+
+ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+
+ resolution: {integrity: sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==}
+
+ resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
+ engines: {node: '>=4'}
+ hasBin: true
+
+ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
+
+ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
+ engines: {node: '>=6.0'}
+ peerDependencies:
+ supports-color: '*'
+ peerDependenciesMeta:
+ supports-color:
+ optional: true
+
+ resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==}
+
+ resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
+
+ resolution: {integrity: sha512-aYlviXiaXBbzvKgyALpcMmqa3Np3sDr0XnZbEG62n2UpZFbEcjQ4EEMOLGzVPhwVnwTz0lvKY+GcARbunuHekw==}
+
+ resolution: {integrity: sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==}
+ engines: {node: '>=10.13.0'}
+
+ resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}
+
+ resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
+ engines: {node: '>=0.8.x'}
+
+ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
+
+ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
+ engines: {node: '>=12.0.0'}
+ peerDependencies:
+ picomatch: ^3 || ^4
+ peerDependenciesMeta:
+ picomatch:
+ optional: true
+
+ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
+ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
+ engines: {node: '>=6.9.0'}
+
+ resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
+
+ resolution: {integrity: sha512-ogzBeF1FvWzjkikrIFwxhlZXvD2+wlY54lqhsrWprcdPjopM2J9HoMweUmIgwaTvY4bUYVimpSsOdvDv1gPRFQ==}
+ peerDependencies:
+ graphology-types: '>=0.19.0'
+
+ resolution: {integrity: sha512-m9aMvbd0uDPffUCFPng5ibRkb2pmfNvdKjQWeZrf71RS1aOoat5874+DcyNfMeCT4aQguKC7Lj9eCbqZj/h8Ag==}
+ peerDependencies:
+ graphology-types: '>=0.19.0'
+
+ resolution: {integrity: sha512-hDRKYXa8TsoZHjgEaysSRyPdT6uB78Ci8WnjgbStlQysz7xR52PInxNsmnB7IBOM1BhikxkNyCVEFgmPKnpx3Q==}
+
+ resolution: {integrity: sha512-ckHg8MXrXJkOARk56ZaSCM1g1Wihe2d6iTmz1enGOz4W/l831MBCKSayeFQfowgF8wd+PQ4rlch/56Vs/VZLDQ==}
+ peerDependencies:
+ graphology-types: '>=0.23.0'
+
+ resolution: {integrity: sha512-8SSImzgUUYC89Z042s+0r/vMibY7GX/Emz4LDO5e7jYXhuoWfHISPFJYjpRLUSJGq6UQ6xlenvX1p/hJdfXuXg==}
+ peerDependencies:
+ graphology-types: '>=0.24.0'
+
+ resolution: {integrity: sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==}
+
+ resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
+
+ resolution: {integrity: sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==}
+
+ resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
+
+ resolution: {integrity: sha512-oaXMACAU0kzOMXBjWpNcX+vlwSBCIAiZ9BHa7gA15NOTtT2L/l8OSZDuqS2XppOhZBPJ7hm4o8ep2kyuip2uEQ==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
+
+ resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}
+
+ resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}
+
+ resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}
+
+ resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}
+
+ resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}
+
+ resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-dJ+LpKyClQZ7NG+j3OensC/mAZkGpukE9YUrgPYvAZj2doVL0edfDgywTUh5CXa0o+nW9a1V9e5+CJTX8+SxRw==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
+ hasBin: true
+
+ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
+
+ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}
+ engines: {node: '>=6'}
+ hasBin: true
+
+ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
+ engines: {node: '>=6'}
+ hasBin: true
+
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
+ engines: {node: '>= 12.0.0'}
+
+ resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
+
+ resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
+ hasBin: true
+
+ resolution: {integrity: sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ==}
+
+ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
+
+ resolution: {integrity: sha512-vnjGJNI7Htk5+oWW8gXGuaLgwgAb0T6/iZbBrp9JCfRFwdNWZ0YTm3eyxjOLgwN6r8iyAf3UA70zNmBRBNv7yg==}
+ peerDependencies:
+ react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
+ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+
+ resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
+
+ resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}
+
+ resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==}
+
+ resolution: {integrity: sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==}
+
+ resolution: {integrity: sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==}
+
+ resolution: {integrity: sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==}
+
+ resolution: {integrity: sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==}
+
+ resolution: {integrity: sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==}
+
+ resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
+
+ resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
+
+ resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==}
+
+ resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}
+
+ resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}
+
+ resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}
+
+ resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}
+
+ resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}
+
+ resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}
+
+ resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}
+
+ resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==}
+
+ resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==}
+
+ resolution: {integrity: sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==}
+
+ resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==}
+
+ resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==}
+
+ resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}
+
+ resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}
+
+ resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==}
+
+ resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==}
+
+ resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==}
+
+ resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==}
+
+ resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==}
+
+ resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==}
+
+ resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==}
+
+ resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==}
+
+ resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==}
+
+ resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}
+
+ resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}
+
+ resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==}
+
+ resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==}
+
+ resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==}
+
+ resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==}
+
+ resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==}
+
+ resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==}
+
+ resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==}
+
+ resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==}
+
+ resolution: {integrity: sha512-vyWo2K3fjrUw8YeeZ1zF0fy6Mu59RHokURlld8ymdUPjMlD9EC9ov1/YPqTgqRvUN9nTr3Gqfz29LYAmu0PHPQ==}
+
+ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
+
+ resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}
+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
+ hasBin: true
+
+ resolution: {integrity: sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ==}
+ engines: {node: '>=18'}
+
+ resolution: {integrity: sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==}
+
+ resolution: {integrity: sha512-wRqjisUyiUfXowgm7MFH2rwJzKIr20rca5FsHXCMNm1W5YPP1hCtrZfgmQ62kP7OZ7Xt+cR858aB28lu5NX55g==}
+
+ resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}
+
+ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
+
+ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
+ engines: {node: '>=12'}
+
+ resolution: {integrity: sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==}
+ engines: {node: '>=4'}
+
+ resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}
+ engines: {node: ^10 || ^12 || >=14}
+
+ resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==}
+
+ resolution: {integrity: sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==}
+ peerDependencies:
+ react: ^18.3.1
+
+ resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
+ peerDependencies:
+ '@types/react': '>=18'
+ react: '>=18'
+
+ resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA==}
+
+ resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
+
+ resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
+
+ resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}
+
+ resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
+
+ resolution: {integrity: sha512-N3DiY5qbRPoa5vkxn1oDLMyXOVTeo6Hp+XOj6SIqJAYUgLS0Q587gILPMom/qm86AQ/ZrcOdwEIzCz8V3J0nxQ==}
+
+ resolution: {integrity: sha512-T5vnZ2y4QqC3/4P+w2+JO+Q/OVdnPsv4XcSYJYMEn0R9/jjl5AgLwO9LAZMzP2lN71O6pypn91rB7lDstUkfrQ==}
+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}
+
+ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
+ hasBin: true
+
+ resolution: {integrity: sha512-R0f1U9hmn38+dFMz6b6ab8lwucmw4AtiY7St+JPWudy1dm+Bs3g884nyrsH9Cy6rKpZKLYayXuMda9GZ/fl8JQ==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ seroval: ^1.0
+
+ resolution: {integrity: sha512-LErWMNS2RRFdu2RMA5u/PA59/IWs0XsikyEXGQ2/36iEWFrdG0ABmg17E17cikrv76891kOAMq3TkTFXpwAHXw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-5H0zFlx6/NTQpqBg4Rm569ZOpnBOXMaS25UQThIWMU3XyzI5AhmorK/gnl87BvJBLhQd0tW4C0LIp3enWzMoNw==}
+
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
+ engines: {node: '>=0.10.0'}
+
+ resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}
+
+ resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}
+
+ resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}
+
+ resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}
+
+ resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==}
+
+ resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
+ engines: {node: '>=6'}
+
+ resolution: {integrity: sha512-3BG1aeB1RUTxItCml/BBuIz5JRM4kZqGuyx+vouv0fXTtcR9ZNoKjWGneHPx94y74GxgArwJZ1qbJR5dt54kSw==}
+ peerDependencies:
+ react: '>=18.0.0'
+
+ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
+ engines: {node: '>=12.0.0'}
+
+ resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
+
+ resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}
+
+ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
+
+ resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
+
+ resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
+
+ resolution: {integrity: sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==}
+
+ resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}
+
+ resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
+
+ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
+
+ resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==}
+
+ resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==}
+
+ resolution: {integrity: sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==}
+ hasBin: true
+ peerDependencies:
+ browserslist: '>= 4.21.0'
+
+ resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
+ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
+
+ resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}
+
+ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}
+
+ resolution: {integrity: sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
+ hasBin: true
+ peerDependencies:
+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
+ jiti: '>=1.21.0'
+ less: '*'
+ lightningcss: ^1.21.0
+ sass: '*'
+ sass-embedded: '*'
+ stylus: '*'
+ sugarss: '*'
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+ jiti:
+ optional: true
+ less:
+ optional: true
+ lightningcss:
+ optional: true
+ sass:
+ optional: true
+ sass-embedded:
+ optional: true
+ stylus:
+ optional: true
+ sugarss:
+ optional: true
+ terser:
+ optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
+
+ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
+
+ resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
+
+snapshots:
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/helper-validator-identifier': 7.29.7
+ js-tokens: 4.0.0
+ picocolors: 1.1.1
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.7
+ '@babel/generator': 7.29.8
+ '@babel/helper-compilation-targets': 7.29.7
+ '@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
+ '@babel/helpers': 7.29.7
+ '@babel/parser': 7.29.8
+ '@babel/template': 7.29.7
+ '@babel/traverse': 7.29.8
+ '@babel/types': 7.29.8
+ '@jridgewell/remapping': 2.3.5
+ convert-source-map: 2.0.0
+ debug: 4.4.3
+ gensync: 1.0.0-beta.2
+ json5: 2.2.3
+ semver: 6.3.1
+ transitivePeerDependencies:
+ - supports-color
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/parser': 7.29.8
+ '@babel/types': 7.29.8
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+ jsesc: 3.1.0
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/compat-data': 7.29.7
+ '@babel/helper-validator-option': 7.29.7
+ browserslist: 4.28.8
+ lru-cache: 5.1.1
+ semver: 6.3.1
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/traverse': 7.29.8
+ '@babel/types': 7.29.8
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@babel/core': 7.29.7
+ '@babel/helper-module-imports': 7.29.7
+ '@babel/helper-validator-identifier': 7.29.7
+ '@babel/traverse': 7.29.8
+ transitivePeerDependencies:
+ - supports-color
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/template': 7.29.7
+ '@babel/types': 7.29.8
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.8
+
+ dependencies:
+ '@babel/core': 7.29.7
+ '@babel/helper-plugin-utils': 7.29.7
+
+ dependencies:
+ '@babel/core': 7.29.7
+ '@babel/helper-plugin-utils': 7.29.7
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.7
+ '@babel/parser': 7.29.8
+ '@babel/types': 7.29.8
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.7
+ '@babel/generator': 7.29.8
+ '@babel/helper-globals': 7.29.7
+ '@babel/parser': 7.29.8
+ '@babel/template': 7.29.7
+ '@babel/types': 7.29.8
+ debug: 4.4.3
+ transitivePeerDependencies:
+ - supports-color
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/helper-string-parser': 7.29.7
+ '@babel/helper-validator-identifier': 7.29.7
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@esbuild/[email protected]':
+ optional: true
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
+ '@jridgewell/[email protected]': {}
+
+ '@jridgewell/[email protected]': {}
+
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/resolve-uri': 3.1.2
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+ '@napi-rs/[email protected]':
+ optional: true
+
+ '@rolldown/[email protected]': {}
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ '@rollup/[email protected]':
+ optional: true
+
+ dependencies:
+ sigma: 3.0.3([email protected])
+
+ dependencies:
+ sigma: 3.0.3([email protected])
+
+ '@tailwindcss/[email protected]':
+ dependencies:
+ '@jridgewell/remapping': 2.3.5
+ enhanced-resolve: 5.24.5
+ jiti: 2.7.0
+ lightningcss: 1.32.0
+ magic-string: 0.30.21
+ source-map-js: 1.2.1
+ tailwindcss: 4.3.3
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optional: true
+
+ '@tailwindcss/[email protected]':
+ optionalDependencies:
+ '@tailwindcss/oxide-android-arm64': 4.3.3
+ '@tailwindcss/oxide-darwin-arm64': 4.3.3
+ '@tailwindcss/oxide-darwin-x64': 4.3.3
+ '@tailwindcss/oxide-freebsd-x64': 4.3.3
+ '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.3
+ '@tailwindcss/oxide-linux-arm64-gnu': 4.3.3
+ '@tailwindcss/oxide-linux-arm64-musl': 4.3.3
+ '@tailwindcss/oxide-linux-x64-gnu': 4.3.3
+ '@tailwindcss/oxide-linux-x64-musl': 4.3.3
+ '@tailwindcss/oxide-wasm32-wasi': 4.3.3
+ '@tailwindcss/oxide-win32-arm64-msvc': 4.3.3
+ '@tailwindcss/oxide-win32-x64-msvc': 4.3.3
+
+ dependencies:
+ postcss-selector-parser: 6.0.10
+ tailwindcss: 4.3.3
+
+ dependencies:
+ '@tailwindcss/node': 4.3.3
+ '@tailwindcss/oxide': 4.3.3
+ tailwindcss: 4.3.3
+
+ '@tanstack/[email protected]': {}
+
+ '@tanstack/[email protected]': {}
+
+ dependencies:
+ '@tanstack/query-core': 5.102.3
+ react: 18.3.1
+
+ dependencies:
+ '@tanstack/history': 1.162.1
+ '@tanstack/react-store': 0.9.3([email protected]([email protected]))([email protected])
+ '@tanstack/router-core': 1.171.27
+ isbot: 5.2.1
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+
+ dependencies:
+ '@tanstack/store': 0.9.3
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ use-sync-external-store: 1.6.0([email protected])
+
+ '@tanstack/[email protected]':
+ dependencies:
+ '@tanstack/history': 1.162.1
+ cookie-es: 3.1.1
+ seroval: 1.6.4
+ seroval-plugins: 1.6.4([email protected])
+
+ '@tanstack/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/parser': 7.29.8
+ '@babel/types': 7.29.8
+ '@types/babel__generator': 7.27.0
+ '@types/babel__template': 7.4.4
+ '@types/babel__traverse': 7.28.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.8
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/parser': 7.29.8
+ '@babel/types': 7.29.8
+
+ '@types/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.8
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/ms': 2.1.0
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/estree': 1.0.9
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/unist': 3.0.3
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/unist': 3.0.3
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]':
+ dependencies:
+ undici-types: 8.3.0
+
+ '@types/[email protected]': {}
+
+ dependencies:
+ '@types/react': 18.3.31
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/prop-types': 15.7.15
+ csstype: 3.2.3
+
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
+ '@ungap/[email protected]': {}
+
+ dependencies:
+ '@babel/core': 7.29.7
+ '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/[email protected])
+ '@rolldown/pluginutils': 1.0.0-beta.27
+ '@types/babel__core': 7.20.5
+ react-refresh: 0.17.0
+ transitivePeerDependencies:
+ - supports-color
+
+
+
+ dependencies:
+ baseline-browser-mapping: 2.11.19
+ caniuse-lite: 1.0.30001810
+ electron-to-chromium: 1.5.414
+ node-releases: 2.0.53
+ update-browserslist-db: 1.3.1([email protected])
+
+
+
+
+
+
+
+
+
+
+
+
+ dependencies:
+ ms: 2.1.3
+
+ dependencies:
+ character-entities: 2.0.2
+
+
+
+ dependencies:
+ dequal: 2.0.3
+
+
+ dependencies:
+ graceful-fs: 4.2.11
+ tapable: 2.3.3
+
+ optionalDependencies:
+ '@esbuild/aix-ppc64': 0.25.12
+ '@esbuild/android-arm': 0.25.12
+ '@esbuild/android-arm64': 0.25.12
+ '@esbuild/android-x64': 0.25.12
+ '@esbuild/darwin-arm64': 0.25.12
+ '@esbuild/darwin-x64': 0.25.12
+ '@esbuild/freebsd-arm64': 0.25.12
+ '@esbuild/freebsd-x64': 0.25.12
+ '@esbuild/linux-arm': 0.25.12
+ '@esbuild/linux-arm64': 0.25.12
+ '@esbuild/linux-ia32': 0.25.12
+ '@esbuild/linux-loong64': 0.25.12
+ '@esbuild/linux-mips64el': 0.25.12
+ '@esbuild/linux-ppc64': 0.25.12
+ '@esbuild/linux-riscv64': 0.25.12
+ '@esbuild/linux-s390x': 0.25.12
+ '@esbuild/linux-x64': 0.25.12
+ '@esbuild/netbsd-arm64': 0.25.12
+ '@esbuild/netbsd-x64': 0.25.12
+ '@esbuild/openbsd-arm64': 0.25.12
+ '@esbuild/openbsd-x64': 0.25.12
+ '@esbuild/openharmony-arm64': 0.25.12
+ '@esbuild/sunos-x64': 0.25.12
+ '@esbuild/win32-arm64': 0.25.12
+ '@esbuild/win32-ia32': 0.25.12
+ '@esbuild/win32-x64': 0.25.12
+
+
+
+
+
+
+ optionalDependencies:
+ picomatch: 4.0.7
+
+ optional: true
+
+
+
+ dependencies:
+ graphology-types: 0.24.8
+ graphology-utils: 2.5.2([email protected])
+
+ dependencies:
+ graphology-types: 0.24.8
+ graphology-utils: 2.5.2([email protected])
+ pandemonium: 2.4.1
+
+
+ dependencies:
+ graphology-types: 0.24.8
+
+ dependencies:
+ events: 3.3.0
+ graphology-types: 0.24.8
+
+ dependencies:
+ '@types/hast': 3.0.5
+
+ dependencies:
+ '@types/estree': 1.0.9
+ '@types/hast': 3.0.5
+ '@types/unist': 3.0.3
+ comma-separated-tokens: 2.0.3
+ devlop: 1.1.0
+ estree-util-is-identifier-name: 3.0.0
+ hast-util-whitespace: 3.0.0
+ mdast-util-mdx-expression: 2.0.1
+ mdast-util-mdx-jsx: 3.2.0
+ mdast-util-mdxjs-esm: 2.0.1
+ property-information: 7.2.0
+ space-separated-tokens: 2.0.2
+ style-to-js: 1.1.21
+ unist-util-position: 5.0.0
+ vfile-message: 4.0.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/hast': 3.0.5
+ '@types/unist': 3.0.3
+ hast-util-is-element: 3.0.0
+ unist-util-find-after: 5.0.0
+
+ dependencies:
+ '@types/hast': 3.0.5
+
+
+
+
+
+ dependencies:
+ is-alphabetical: 2.0.1
+ is-decimal: 2.0.1
+
+
+
+
+
+
+
+
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.32.0
+ lightningcss-darwin-arm64: 1.32.0
+ lightningcss-darwin-x64: 1.32.0
+ lightningcss-freebsd-x64: 1.32.0
+ lightningcss-linux-arm-gnueabihf: 1.32.0
+ lightningcss-linux-arm64-gnu: 1.32.0
+ lightningcss-linux-arm64-musl: 1.32.0
+ lightningcss-linux-x64-gnu: 1.32.0
+ lightningcss-linux-x64-musl: 1.32.0
+ lightningcss-win32-arm64-msvc: 1.32.0
+ lightningcss-win32-x64-msvc: 1.32.0
+
+
+ dependencies:
+ js-tokens: 4.0.0
+
+ dependencies:
+ '@types/hast': 3.0.5
+ devlop: 1.1.0
+ highlight.js: 11.11.2
+
+ dependencies:
+ yallist: 3.1.1
+
+ dependencies:
+ react: 18.3.1
+
+ dependencies:
+ '@jridgewell/sourcemap-codec': 1.5.5
+
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ escape-string-regexp: 5.0.0
+ unist-util-is: 6.0.1
+ unist-util-visit-parents: 6.0.2
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ decode-named-character-reference: 1.3.0
+ devlop: 1.1.0
+ mdast-util-to-string: 4.0.0
+ micromark: 4.0.2
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-decode-string: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ unist-util-stringify-position: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-find-and-replace: 3.0.2
+ micromark-util-character: 2.1.1
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ micromark-util-normalize-identifier: 2.0.1
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ markdown-table: 3.0.4
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-gfm-autolink-literal: 2.0.1
+ mdast-util-gfm-footnote: 2.1.0
+ mdast-util-gfm-strikethrough: 2.0.0
+ mdast-util-gfm-table: 2.0.0
+ mdast-util-gfm-task-list-item: 2.0.0
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ parse-entities: 4.0.2
+ stringify-entities: 4.0.4
+ unist-util-stringify-position: 4.0.0
+ vfile-message: 4.0.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ unist-util-is: 6.0.1
+
+ dependencies:
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ '@ungap/structured-clone': 1.3.4
+ devlop: 1.1.0
+ micromark-util-sanitize-uri: 2.0.1
+ trim-lines: 3.0.1
+ unist-util-position: 5.0.0
+ unist-util-visit: 5.1.0
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ longest-streak: 3.1.0
+ mdast-util-phrasing: 4.1.0
+ mdast-util-to-string: 4.0.0
+ micromark-util-classify-character: 2.0.1
+ micromark-util-decode-string: 2.0.1
+ unist-util-visit: 5.1.0
+ zwitch: 2.0.4
+
+ dependencies:
+ '@types/mdast': 4.0.4
+
+ dependencies:
+ decode-named-character-reference: 1.3.0
+ devlop: 1.1.0
+ micromark-factory-destination: 2.0.1
+ micromark-factory-label: 2.0.1
+ micromark-factory-space: 2.0.1
+ micromark-factory-title: 2.0.1
+ micromark-factory-whitespace: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-chunked: 2.0.1
+ micromark-util-classify-character: 2.0.1
+ micromark-util-html-tag-name: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-subtokenize: 2.1.0
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-sanitize-uri: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-core-commonmark: 2.0.3
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-sanitize-uri: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-util-chunked: 2.0.1
+ micromark-util-classify-character: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-extension-gfm-autolink-literal: 2.1.0
+ micromark-extension-gfm-footnote: 2.1.0
+ micromark-extension-gfm-strikethrough: 2.1.0
+ micromark-extension-gfm-table: 2.1.1
+ micromark-extension-gfm-tagfilter: 2.0.0
+ micromark-extension-gfm-task-list-item: 2.1.0
+ micromark-util-combine-extensions: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-chunked: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ decode-named-character-reference: 1.3.0
+ micromark-util-character: 2.1.1
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-symbol: 2.0.1
+
+
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-encode: 2.0.1
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-util-chunked: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+
+
+ dependencies:
+ '@types/debug': 4.1.13
+ debug: 4.4.3
+ decode-named-character-reference: 1.3.0
+ devlop: 1.1.0
+ micromark-core-commonmark: 2.0.3
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-chunked: 2.0.1
+ micromark-util-combine-extensions: 2.0.1
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-encode: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-sanitize-uri: 2.0.1
+ micromark-util-subtokenize: 2.1.0
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ obliterator: 2.0.5
+
+
+
+
+
+ dependencies:
+ mnemonist: 0.39.8
+
+ dependencies:
+ '@types/unist': 2.0.11
+ character-entities-legacy: 3.0.0
+ character-reference-invalid: 2.0.1
+ decode-named-character-reference: 1.3.0
+ is-alphanumerical: 2.0.1
+ is-decimal: 2.0.1
+ is-hexadecimal: 2.0.1
+
+
+
+ dependencies:
+ cssesc: 3.0.0
+ util-deprecate: 1.0.2
+
+ dependencies:
+ nanoid: 3.3.18
+ picocolors: 1.1.1
+ source-map-js: 1.2.1
+
+
+ dependencies:
+ loose-envify: 1.4.0
+ react: 18.3.1
+ scheduler: 0.23.2
+
+ dependencies:
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ '@types/react': 18.3.31
+ devlop: 1.1.0
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ mdast-util-to-hast: 13.2.1
+ react: 18.3.1
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ unified: 11.0.5
+ unist-util-visit: 5.1.0
+ vfile: 6.0.3
+ transitivePeerDependencies:
+ - supports-color
+
+
+ dependencies:
+ loose-envify: 1.4.0
+
+ dependencies:
+ '@types/hast': 3.0.5
+ hast-util-to-text: 4.0.2
+ lowlight: 3.3.0
+ unist-util-visit: 5.1.0
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-gfm: 3.1.0
+ micromark-extension-gfm: 3.0.0
+ remark-parse: 11.0.0
+ remark-stringify: 11.0.0
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-from-markdown: 2.0.3
+ micromark-util-types: 2.0.2
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/hast': 3.0.5
+ '@types/mdast': 4.0.4
+ mdast-util-to-hast: 13.2.1
+ unified: 11.0.5
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-to-markdown: 2.1.2
+ unified: 11.0.5
+
+
+ dependencies:
+ '@types/estree': 1.0.9
+ optionalDependencies:
+ '@napi-rs/lzma-linux-x64-gnu': 1.5.1
+ '@rollup/rollup-android-arm-eabi': 4.63.0
+ '@rollup/rollup-android-arm64': 4.63.0
+ '@rollup/rollup-darwin-arm64': 4.63.0
+ '@rollup/rollup-darwin-x64': 4.63.0
+ '@rollup/rollup-freebsd-arm64': 4.63.0
+ '@rollup/rollup-freebsd-x64': 4.63.0
+ '@rollup/rollup-linux-arm-gnueabihf': 4.63.0
+ '@rollup/rollup-linux-arm-musleabihf': 4.63.0
+ '@rollup/rollup-linux-arm64-gnu': 4.63.0
+ '@rollup/rollup-linux-arm64-musl': 4.63.0
+ '@rollup/rollup-linux-loong64-gnu': 4.63.0
+ '@rollup/rollup-linux-loong64-musl': 4.63.0
+ '@rollup/rollup-linux-ppc64-gnu': 4.63.0
+ '@rollup/rollup-linux-ppc64-musl': 4.63.0
+ '@rollup/rollup-linux-riscv64-gnu': 4.63.0
+ '@rollup/rollup-linux-riscv64-musl': 4.63.0
+ '@rollup/rollup-linux-s390x-gnu': 4.63.0
+ '@rollup/rollup-linux-x64-gnu': 4.63.0
+ '@rollup/rollup-linux-x64-musl': 4.63.0
+ '@rollup/rollup-openbsd-x64': 4.63.0
+ '@rollup/rollup-openharmony-arm64': 4.63.0
+ '@rollup/rollup-win32-arm64-msvc': 4.63.0
+ '@rollup/rollup-win32-ia32-msvc': 4.63.0
+ '@rollup/rollup-win32-x64-gnu': 4.63.0
+ '@rollup/rollup-win32-x64-msvc': 4.63.0
+ fsevents: 2.3.3
+
+ dependencies:
+ loose-envify: 1.4.0
+
+
+ dependencies:
+ seroval: 1.6.4
+
+
+ dependencies:
+ events: 3.3.0
+ graphology-utils: 2.5.2([email protected])
+ transitivePeerDependencies:
+ - graphology-types
+
+
+
+ dependencies:
+ character-entities-html4: 2.1.0
+ character-entities-legacy: 3.0.0
+
+ dependencies:
+ style-to-object: 1.0.14
+
+ dependencies:
+ inline-style-parser: 0.2.7
+
+
+
+ dependencies:
+ react: 18.3.1
+
+ dependencies:
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.7
+
+
+
+
+
+ dependencies:
+ '@types/unist': 3.0.3
+ bail: 2.0.2
+ devlop: 1.1.0
+ extend: 3.0.2
+ is-plain-obj: 4.1.0
+ trough: 2.2.0
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+
+ dependencies:
+ '@types/unist': 3.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+ unist-util-visit-parents: 6.0.2
+
+ dependencies:
+ browserslist: 4.28.8
+ escalade: 3.2.0
+ picocolors: 1.1.1
+
+ dependencies:
+ react: 18.3.1
+
+
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-stringify-position: 4.0.0
+
+ dependencies:
+ '@types/unist': 3.0.3
+ vfile-message: 4.0.3
+
+ dependencies:
+ esbuild: 0.25.12
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.7
+ postcss: 8.5.26
+ rollup: 4.63.0
+ tinyglobby: 0.2.17
+ optionalDependencies:
+ '@types/node': 26.3.0
+ fsevents: 2.3.3
+ jiti: 2.7.0
+ lightningcss: 1.32.0
+
+
diff --git a/web/src/api.ts b/web/src/api.ts
new file mode 100644
index 00000000..6d9c54c3
--- /dev/null
+++ b/web/src/api.ts
@@ -0,0 +1,770 @@
+export class ApiError extends Error {
+ status: number;
+ constructor(status: number, message: string) {
+ super(message);
+ this.status = status;
+ }
+}
+
+async function request<T>(path: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(path, {
+ credentials: "include",
+ headers: init?.body instanceof FormData ? {} : { "Content-Type": "application/json" },
+ ...init,
+ });
+ if (!res.ok) {
+ let message = res.statusText;
+ try {
+ const body = (await res.json()) as { error?: string };
+ if (body.error) message = body.error;
+ } catch {
+ // 非 JSON 响应体,保留 statusText
+ }
+ throw new ApiError(res.status, message);
+ }
+ return res.json() as Promise<T>;
+}
+
+export interface User {
+ id: string;
+ org_id: string;
+ email: string;
+ display_name: string;
+ is_admin: boolean;
+ created_at: string;
+}
+
+export interface Workspace {
+ id: string;
+ org_id: string;
+ name: string;
+ created_at: string;
+}
+
+export interface Kb {
+ id: string;
+ workspace_id: string;
+ name: string;
+ kind: string;
+ description: string | null;
+ visibility: "open" | "restricted";
+ /** 部署的公共默认空间(第一个建的库):永远 open、不可删除 */
+ is_default: boolean;
+}
+
+/** 账户层"我的知识库"行:库 + 我的角色 + 加入信息 + 概览统计。 */
+export interface MyKb {
+ kb: Kb;
+ my_role: "viewer" | "editor" | "admin" | "owner" | null;
+ joined_at: string | null;
+ added_by_name: string | null;
+ doc_count: number;
+ member_count: number;
+}
+
+/** 审计事件(纯审计展示)。 */
+export interface AuditEvent {
+ id: string;
+ action: string;
+ target_kind: string;
+ target_id: string | null;
+ detail: Record<string, unknown>;
+ actor_name: string | null;
+ created_at: string;
+}
+
+export interface KbMember {
+ user_id: string;
+ email: string;
+ display_name: string;
+ role: "viewer" | "editor" | "admin";
+}
+
+export interface Doc {
+ id: string;
+ kb_id: string;
+ source_id: string | null;
+ filename: string;
+ mime: string;
+ size_bytes: number;
+ status: string;
+ graph_status: string;
+ error: string | null;
+ chunk_count: number;
+ tags: string[];
+ missing_since: string | null;
+ created_at: string;
+}
+
+export interface SourceView {
+ id: string;
+ kind: "folder" | "url" | "rss" | "api" | "custom" | "memory" | "upload";
+ name: string;
+ config: { urls?: string[]; feed_url?: string; endpoint?: string } | null;
+ icon: string | null;
+ sync_interval_minutes: number | null;
+ sync_cron: string | null;
+ last_sync_at: string | null;
+ last_sync_status: "never" | "queued" | "running" | "ok" | "failed";
+ last_sync_error: string | null;
+ last_sync_added: number;
+ doc_count: number;
+ missing_count: number;
+}
+
+export interface SearchResult {
+ id: string;
+ document_id: string;
+ seq: number;
+ text: string;
+ filename: string;
+}
+
+export interface LlmSettingsView {
+ chat_base_url?: string | null;
+ chat_model?: string | null;
+ has_chat_key?: boolean;
+ embed_base_url?: string | null;
+ embed_model?: string | null;
+ embed_dim?: number | null;
+ has_embed_key?: boolean;
+}
+
+export interface Member {
+ user_id: string;
+ email: string;
+ display_name: string;
+ role: string;
+ is_admin: boolean;
+}
+
+export interface OrgUser {
+ id: string;
+ email: string;
+ display_name: string;
+ is_admin: boolean;
+}
+
+/** 问数数据源(凭据不下发,只有 host:port/db 摘要)。 */
+export interface DataSourceView {
+ id: string;
+ name: string;
+ engine: string;
+ summary: string;
+ created_at: string;
+ last_test_at: string | null;
+ last_test_ok: boolean | null;
+}
+
+export interface GraphNode {
+ id: string;
+ name: string;
+ type_key: string;
+ type_label: string;
+ color: string;
+ shape: "circle" | "square";
+ degree: number;
+ disambiguator: string | null;
+}
+
+export interface SyncRun {
+ id: string;
+ started_at: string;
+ finished_at: string | null;
+ status: "running" | "ok" | "failed";
+ created_docs: number;
+ updated_docs: number;
+ error: string | null;
+}
+
+/** 分块的抽取产物(文档查看器右栏)。 */
+export interface ChunkFact {
+ chunk_id: string;
+ fact_id: string;
+ subject_id: string;
+ subject: string;
+ predicate: string;
+ object_id: string | null;
+ object: string | null;
+ valid_from: string | null;
+ valid_to: string | null;
+ confidence: number;
+}
+
+export interface ReviewSide {
+ id: string;
+ name: string;
+ type_label: string;
+ color: string;
+ disambiguator: string | null;
+ degree: number;
+ top_facts: string[];
+}
+
+export interface ReviewItem {
+ id: string;
+ score: number;
+ reason: string | null;
+ stage: "adjudicating" | "human";
+ created_at: string;
+ left: ReviewSide;
+ right: ReviewSide;
+}
+
+export interface FactReviewItem {
+ id: string;
+ subject_name: string;
+ predicate_label: string;
+ object_name: string | null;
+ valid_from: string | null;
+ valid_to: string | null;
+ confidence: number;
+ evidence_count: number;
+ quote: string | null;
+}
+
+/** 时态冲突(自动闭合拿不准的那些):旧事实 vs 新事实。 */
+export interface ConflictItem {
+ id: string;
+ reason: "no_time" | "simultaneous" | "low_confidence";
+ created_at: string;
+ predicate_label: string;
+ old_fact_id: string;
+ old_subject: string;
+ old_object: string | null;
+ old_valid_from: string | null;
+ new_fact_id: string;
+ new_subject: string;
+ new_object: string | null;
+ new_valid_from: string | null;
+ new_confidence: number;
+}
+
+/** 决策台账事件(audit_events 的 review 域切片):detail 是决策时的自包含快照。 */
+export interface ReviewHistoryEvent {
+ id: string;
+ action: string;
+ target_kind: string;
+ target_id: string | null;
+ detail: Record<string, unknown>;
+ /** null = 系统(AI 裁决器) */
+ actor_name: string | null;
+ created_at: string;
+}
+
+export interface MergeLog {
+ id: string;
+ source_name: string;
+ target_name: string;
+ merged_by_name: string | null;
+ reason: string | null;
+ created_at: string;
+ reverted_at: string | null;
+}
+
+export interface GraphEdge {
+ id: string;
+ source: string;
+ target: string;
+ predicate: string;
+ label: string;
+ valid_from: string | null;
+ valid_to: string | null;
+ confidence: number;
+}
+
+export interface EntityFact {
+ id: string;
+ direction: "out" | "in";
+ predicate_key: string;
+ predicate_label: string;
+ temporal: string;
+ other_id: string | null;
+ other_name: string | null;
+ /** 字面值宾语(属性事实/问数映射):{"value":…} 或 {"summary":…} */
+ object_value: Record<string, unknown> | null;
+ valid_from: string | null;
+ valid_to: string | null;
+ valid_precision: string;
+ confidence: number;
+ evidence_count: number;
+ /** 证据全部停留在来源文档的旧版(未被现行内容确认;不代表事实失效) */
+ stale: boolean;
+ /** 修正行:区间闭合来自引擎对账/人工裁决而非抽取原文 */
+ corrected: boolean;
+ /** 证据集合里最新的文档时间(开放事实的"最后确认时间") */
+ last_evidence_time: string | null;
+}
+
+export interface Evidence {
+ quote: string | null;
+ chunk_id: string;
+ document_id: string;
+ filename: string;
+ seq: number;
+ /** 证据出自文档的第几版 */
+ doc_version: number;
+ /** 文档已有更新版本(证据停留在旧版;不代表事实失效) */
+ stale: boolean;
+}
+
+export interface ChunkFull {
+ id: string;
+ seq: number;
+ text: string;
+}
+
+export interface EntityTypeView {
+ id: string;
+ key: string;
+ label: string;
+ color: string;
+ shape: "circle" | "square";
+ builtin: boolean;
+ parent_id: string | null;
+ description: string;
+ usage: number;
+}
+
+export interface RelationTypeView {
+ id: string;
+ key: string;
+ label: string;
+ temporal: string;
+ functional: boolean;
+ inverse_functional: boolean;
+ builtin: boolean;
+ description: string;
+ /** relation(宾语是实体)| attribute(宾语是字面值) */
+ kind: "relation" | "attribute";
+ domain_type_id: string | null;
+ datatype: "text" | "number" | "date" | "bool" | null;
+ unit: string | null;
+ usage: number;
+}
+
+export interface OntologyMiss {
+ kind: "entity_type" | "relation_type";
+ key: string;
+ example: string | null;
+ count: number;
+}
+
+export interface OntologyProposals {
+ entity_types: { key: string; label: string; reason?: string }[];
+ relation_types: {
+ key: string;
+ label: string;
+ temporal?: string;
+ functional?: boolean;
+ reason?: string;
+ }[];
+}
+
+export interface Source {
+ n: number;
+ /** 缺省 = 文档 chunk 引用;charter = 内置手册(跳 /docs/{slug}#{anchor}) */
+ kind?: "charter";
+ chunk_id?: string;
+ document_id?: string;
+ slug?: string;
+ anchor?: string;
+ heading?: string;
+ filename: string;
+ excerpt: string;
+}
+
+/** Agentic 对话的行动轨迹(工具调用一步一条)。 */
+export interface ChatStep {
+ kind: "search" | "docs" | "entity" | "facts" | "query" | "tool";
+ label: string;
+ detail: string;
+}
+
+/** 会话行(Chat 左栏列表)。 */
+export interface ConversationRow {
+ id: string;
+ title: string;
+ created_at: string;
+ updated_at: string;
+ message_count: number;
+}
+
+/** 会话消息(含落库的行动轨迹与引用,历史回放用)。 */
+export interface ConversationMessage {
+ id: string;
+ role: "user" | "assistant";
+ content: string;
+ steps: ChatStep[];
+ sources: Source[];
+ created_at: string;
+}
+
+export const api = {
+ health: () => request<{ status: string; name: string; version: string }>("/api/v1/health"),
+ me: () => request<User>("/api/v1/auth/me"),
+ login: (email: string, password: string) =>
+ request<{ user: User }>("/api/v1/auth/login", {
+ method: "POST",
+ body: JSON.stringify({ email, password }),
+ }),
+ register: (email: string, password: string, displayName: string) =>
+ request<{ user: User; workspace: Workspace }>("/api/v1/auth/register", {
+ method: "POST",
+ body: JSON.stringify({ email, password, display_name: displayName }),
+ }),
+ logout: () => request<{ ok: boolean }>("/api/v1/auth/logout", { method: "POST" }),
+ updateMe: (displayName: string) =>
+ request<User>("/api/v1/auth/me", {
+ method: "PATCH",
+ body: JSON.stringify({ display_name: displayName }),
+ }),
+ changePassword: (currentPassword: string, newPassword: string) =>
+ request<{ ok: boolean }>("/api/v1/auth/password", {
+ method: "POST",
+ body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
+ }),
+ workspaces: () => request<Workspace[]>("/api/v1/workspaces"),
+
+ kbs: (workspaceId: string) => request<Kb[]>(`/api/v1/workspaces/${workspaceId}/kbs`),
+ kbAudit: (kbId: string) =>
+ request<{ events: AuditEvent[] }>(`/api/v1/kbs/${kbId}/audit`),
+ myKbs: (workspaceId: string) =>
+ request<{ kbs: MyKb[] }>(`/api/v1/workspaces/${workspaceId}/my-kbs`),
+ createKb: (
+ workspaceId: string,
+ body: { name: string; description?: string | null; visibility?: string },
+ ) =>
+ request<Kb>(`/api/v1/workspaces/${workspaceId}/kbs`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+
+ kbDetail: (kbId: string) => request<Kb>(`/api/v1/kbs/${kbId}`),
+ updateKb: (kbId: string, body: Record<string, unknown>) =>
+ request<Kb>(`/api/v1/kbs/${kbId}`, { method: "PATCH", body: JSON.stringify(body) }),
+ deleteKb: (kbId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}`, { method: "DELETE" }),
+ kbMembers: (kbId: string) => request<{ members: KbMember[] }>(`/api/v1/kbs/${kbId}/members`),
+ setKbMember: (kbId: string, userId: string, role: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, {
+ method: "PUT",
+ body: JSON.stringify({ role }),
+ }),
+ removeKbMember: (kbId: string, userId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/members/${userId}`, { method: "DELETE" }),
+
+ adminDeployment: () =>
+ request<{ open_registration: boolean; worker_concurrency: number }>(
+ "/api/v1/admin/deployment",
+ ),
+ saveAdminDeployment: (openRegistration: boolean, workerConcurrency?: number) =>
+ request<{ ok: boolean }>("/api/v1/admin/deployment", {
+ method: "PUT",
+ body: JSON.stringify({
+ open_registration: openRegistration,
+ ...(workerConcurrency !== undefined ? { worker_concurrency: workerConcurrency } : {}),
+ }),
+ }),
+ adminCreateUser: (body: { email: string; display_name: string; password: string; role: string }) =>
+ request<{ user: User }>("/api/v1/admin/users", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+
+ adminDataSources: () =>
+ request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
+ adminCreateDataSource: (body: { name: string; conn_string: string }) =>
+ request<{ id: string }>("/api/v1/admin/data-sources", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ adminDeleteDataSource: (id: string) =>
+ request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}`, { method: "DELETE" }),
+ adminTestDataSource: (id: string) =>
+ request<{ ok: boolean }>(`/api/v1/admin/data-sources/${id}/test`, { method: "POST" }),
+ kbDataSources: (kbId: string) =>
+ request<{ data_sources: DataSourceView[] }>(`/api/v1/kbs/${kbId}/data-sources`),
+ kbDataSourcesAvailable: (kbId: string) =>
+ request<{ data_sources: DataSourceView[] }>(`/api/v1/kbs/${kbId}/data-sources/available`),
+ mountDataSource: (kbId: string, dsId: string) =>
+ request<{ ok: boolean; schema_tables: number }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, {
+ method: "PUT",
+ }),
+ unmountDataSource: (kbId: string, dsId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/${dsId}`, { method: "DELETE" }),
+ exploreMappings: (kbId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/data-sources/explore`, { method: "POST" }),
+ syncDataSourceSchema: (kbId: string, dsId: string) =>
+ request<{ ok: boolean; schema_tables: number }>(
+ `/api/v1/kbs/${kbId}/data-sources/${dsId}/sync-schema`,
+ { method: "POST" },
+ ),
+
+ documents: (kbId: string) => request<Doc[]>(`/api/v1/kbs/${kbId}/documents`),
+ upload: (kbId: string, files: File[], sourceId?: string) => {
+ const form = new FormData();
+ for (const f of files) form.append("files", f, f.name);
+ const qs = sourceId ? `?source=${sourceId}` : "";
+ return request<{ created: Doc[]; skipped: unknown[] }>(
+ `/api/v1/kbs/${kbId}/documents${qs}`,
+ { method: "POST", body: form },
+ );
+ },
+ deleteDocument: (id: string) =>
+ request<{ ok: boolean }>(`/api/v1/documents/${id}`, { method: "DELETE" }),
+
+ search: (kbId: string, q: string) =>
+ request<{ results: SearchResult[] }>(`/api/v1/kbs/${kbId}/search`, {
+ method: "POST",
+ body: JSON.stringify({ q }),
+ }),
+
+ settings: (workspaceId: string) =>
+ request<LlmSettingsView>(`/api/v1/workspaces/${workspaceId}/settings`),
+ saveSettings: (workspaceId: string, body: Record<string, unknown>) =>
+ request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/settings`, {
+ method: "PUT",
+ body: JSON.stringify(body),
+ }),
+ graphOverview: (kbId: string) =>
+ request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(`/api/v1/kbs/${kbId}/graph/overview`),
+ graphNeighborhood: (kbId: string, entityId: string) =>
+ request<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
+ `/api/v1/kbs/${kbId}/graph/neighborhood?entity=${entityId}&hops=2`,
+ ),
+ searchEntities: (kbId: string, q: string) =>
+ request<{ entities: GraphNode[] }>(
+ `/api/v1/kbs/${kbId}/entities?q=${encodeURIComponent(q)}`,
+ ),
+ entityDetail: (kbId: string, entityId: string) =>
+ request<{ entity: GraphNode; facts: EntityFact[] }>(
+ `/api/v1/kbs/${kbId}/entities/${entityId}`,
+ ),
+ factEvidence: (kbId: string, factId: string) =>
+ request<{ evidence: Evidence[] }>(`/api/v1/kbs/${kbId}/facts/${factId}/evidence`),
+ documentDetail: (id: string) =>
+ request<{ document: Doc; chunks: ChunkFull[] }>(`/api/v1/documents/${id}`),
+ extractDocument: (id: string) =>
+ request<{ job_id: number }>(`/api/v1/documents/${id}/extract`, { method: "POST" }),
+ reprocessDocument: (id: string) =>
+ request<{ job_id: number }>(`/api/v1/documents/${id}/reprocess`, { method: "POST" }),
+
+ ontology: (kbId: string) =>
+ request<{
+ entity_types: EntityTypeView[];
+ relation_types: RelationTypeView[];
+ misses: OntologyMiss[];
+ }>(`/api/v1/kbs/${kbId}/ontology`),
+ createEntityType: (kbId: string, body: Record<string, unknown>) =>
+ request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/entity-types`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ updateEntityType: (kbId: string, id: string, body: Record<string, unknown>) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/entity-types/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
+ deleteEntityType: (kbId: string, id: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/entity-types/${id}`, {
+ method: "DELETE",
+ }),
+ typeEntities: (kbId: string, typeId: string, page: number, per = 12) =>
+ request<{ entities: { id: string; name: string; fact_count: number }[]; total: number }>(
+ `/api/v1/kbs/${kbId}/ontology/entity-types/${typeId}/entities?page=${page}&per=${per}`,
+ ),
+ createRelationType: (kbId: string, body: Record<string, unknown>) =>
+ request<{ id: string }>(`/api/v1/kbs/${kbId}/ontology/relation-types`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ updateRelationType: (kbId: string, id: string, body: Record<string, unknown>) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/relation-types/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
+ deleteRelationType: (kbId: string, id: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/relation-types/${id}`, {
+ method: "DELETE",
+ }),
+ dismissMiss: (kbId: string, kind: string, key: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/ontology/misses/dismiss`, {
+ method: "POST",
+ body: JSON.stringify({ kind, key }),
+ }),
+ suggestOntology: (kbId: string) =>
+ request<OntologyProposals>(`/api/v1/kbs/${kbId}/ontology/suggest`, { method: "POST" }),
+
+ sources: (kbId: string) =>
+ request<{ sources: SourceView[] }>(`/api/v1/kbs/${kbId}/sources`),
+ createSource: (kbId: string, body: Record<string, unknown>) =>
+ request<{ source: SourceView; ingest_token?: string | null }>(
+ `/api/v1/kbs/${kbId}/sources`,
+ {
+ method: "POST",
+ body: JSON.stringify(body),
+ },
+ ),
+ sourceToken: (kbId: string, sourceId: string) =>
+ request<{ ingest_token: string | null }>(
+ `/api/v1/kbs/${kbId}/sources/${sourceId}/token`,
+ ),
+ rotateSourceToken: (kbId: string, sourceId: string) =>
+ request<{ ingest_token: string }>(
+ `/api/v1/kbs/${kbId}/sources/${sourceId}/rotate-token`,
+ { method: "POST" },
+ ),
+ updateSource: (kbId: string, sourceId: string, body: Record<string, unknown>) =>
+ request<{ source: SourceView }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
+ deleteSource: (kbId: string, sourceId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}`, { method: "DELETE" }),
+ cleanupMissing: (kbId: string, sourceId: string) =>
+ request<{ deleted: number }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/missing/cleanup`, {
+ method: "POST",
+ }),
+ syncSource: (kbId: string, sourceId: string) =>
+ request<{ queued: boolean }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/sync`, {
+ method: "POST",
+ }),
+ sourceRuns: (kbId: string, sourceId: string) =>
+ request<{ runs: SyncRun[] }>(`/api/v1/kbs/${kbId}/sources/${sourceId}/runs`),
+ documentExtractions: (docId: string) =>
+ request<{ facts: ChunkFact[] }>(`/api/v1/documents/${docId}/extractions`),
+
+ review: (kbId: string) =>
+ request<{
+ reviews: ReviewItem[];
+ facts: FactReviewItem[];
+ merges: MergeLog[];
+ conflicts: ConflictItem[];
+ unconfirmed: FactReviewItem[];
+ }>(`/api/v1/kbs/${kbId}/review`),
+ closeFact: (kbId: string, factId: string, validTo: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/close`, {
+ method: "POST",
+ body: JSON.stringify({ valid_to: validTo }),
+ }),
+ resolveConflict: (
+ kbId: string,
+ conflictId: string,
+ body: { action: "close" | "keep" | "reject_new"; close_at?: string },
+ ) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conflicts/${conflictId}`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ decideReview: (kbId: string, reviewId: string, action: "merge" | "keep") =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/review/${reviewId}`, {
+ method: "POST",
+ body: JSON.stringify({ action }),
+ }),
+ confirmFact: (kbId: string, factId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/confirm`, { method: "POST" }),
+ rejectFact: (kbId: string, factId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/facts/${factId}/reject`, { method: "POST" }),
+ revertMerge: (kbId: string, mergeId: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/merges/${mergeId}/revert`, { method: "POST" }),
+ reviewHistory: (kbId: string, page: number, per = 20) =>
+ request<{ events: ReviewHistoryEvent[]; total: number }>(
+ `/api/v1/kbs/${kbId}/review/history?page=${page}&per=${per}`,
+ ),
+
+ members: (workspaceId: string) => request<Member[]>(`/api/v1/workspaces/${workspaceId}/members`),
+ orgUsers: () => request<OrgUser[]>("/api/v1/users"),
+ setMemberRole: (workspaceId: string, userId: string, role: string) =>
+ request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/members/${userId}`, {
+ method: "PUT",
+ body: JSON.stringify({ role }),
+ }),
+ removeMember: (workspaceId: string, userId: string) =>
+ request<{ ok: boolean }>(`/api/v1/workspaces/${workspaceId}/members/${userId}`, {
+ method: "DELETE",
+ }),
+
+ testSettings: (workspaceId: string) =>
+ request<{
+ chat: { ok: boolean; reply?: string; error?: string };
+ embed: { ok: boolean; dim?: number; error?: string };
+ }>(`/api/v1/workspaces/${workspaceId}/settings/test`, { method: "POST" }),
+};
+
+/** RAG 对话:SSE 流式。返回中止函数。 */
+export const conversationsApi = {
+ list: (kbId: string) =>
+ request<{ conversations: ConversationRow[] }>(`/api/v1/kbs/${kbId}/conversations`),
+ detail: (kbId: string, id: string) =>
+ request<{ messages: ConversationMessage[] }>(`/api/v1/kbs/${kbId}/conversations/${id}`),
+ remove: (kbId: string, id: string) =>
+ request<{ ok: boolean }>(`/api/v1/kbs/${kbId}/conversations/${id}`, { method: "DELETE" }),
+};
+
+export function streamChat(
+ kbId: string,
+ body: { conversation_id?: string; message: string },
+ handlers: {
+ onConversation: (id: string) => void;
+ onSources: (s: Source[]) => void;
+ onStep: (s: ChatStep) => void;
+ onDelta: (text: string) => void;
+ onDone: () => void;
+ onError: (message: string) => void;
+ },
+): () => void {
+ const controller = new AbortController();
+ (async () => {
+ try {
+ const res = await fetch(`/api/v1/kbs/${kbId}/chat`, {
+ method: "POST",
+ credentials: "include",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ signal: controller.signal,
+ });
+ if (!res.ok || !res.body) {
+ let message = res.statusText;
+ try {
+ const body = (await res.json()) as { error?: string };
+ if (body.error) message = body.error;
+ } catch {
+ /* ignore */
+ }
+ handlers.onError(message);
+ return;
+ }
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = "";
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let idx: number;
+ while ((idx = buf.indexOf("\n\n")) >= 0) {
+ const frame = buf.slice(0, idx);
+ buf = buf.slice(idx + 2);
+ let event = "message";
+ let data = "";
+ for (const line of frame.split("\n")) {
+ if (line.startsWith("event:")) event = line.slice(6).trim();
+ else if (line.startsWith("data:")) data += line.slice(5).trim();
+ }
+ if (event === "conversation")
+ handlers.onConversation((JSON.parse(data) as { id: string }).id);
+ else if (event === "sources") handlers.onSources(JSON.parse(data || "[]"));
+ else if (event === "step") handlers.onStep(JSON.parse(data) as ChatStep);
+ else if (event === "delta") handlers.onDelta((JSON.parse(data) as { text: string }).text);
+ else if (event === "done") handlers.onDone();
+ else if (event === "error") handlers.onError(data);
+ }
+ }
+ handlers.onDone();
+ } catch (e) {
+ if (!controller.signal.aborted) handlers.onError(String(e));
+ }
+ })();
+ return () => controller.abort();
+}
diff --git a/web/src/docs/ingest.md b/web/src/docs/ingest.md
new file mode 100644
index 00000000..3907acad
--- /dev/null
+++ b/web/src/docs/ingest.md
@@ -0,0 +1,114 @@
+# Ingest interfaces
+
+Utopia pulls or receives documents through **sources**. Two source kinds speak JSON and are meant for integration: **Custom** (Utopia polls your service) and **API** (your service pushes to Utopia). Both share the same identity semantics: every item has a stable ID, and pushing or returning the same ID again **updates the same document in place** — the previous content is kept as a version, search re-indexes, and the knowledge graph re-extracts.
+
+## Choosing between them
+
+| | Custom (pull) | API (push) |
+|---|---|---|
+| Who initiates | Utopia, on a schedule | Your service, any time |
+| Auth | Optional header you configure | Per-source Bearer token |
+| Fits | Feeds, exports, periodic snapshots | Event-driven systems, scripts, CI |
+| Deletion signal | `deleted` array in the response | `deleted: true` in a push |
+
+---
+
+## Custom source — the pull interface
+
+Create a **Custom** source and point it at any URL you control. On every sync (manual, interval, or cron) Utopia sends:
+
+```
+GET {endpoint}?since=2026-08-26T19:43:24Z
+Authorization: <your configured header, if any>
+```
+
+- `since` is the last successful sync time (RFC 3339). It is **omitted on the first sync** — return everything then; afterwards you may return only what changed since that moment. Returning unchanged items again is harmless: they are skipped by content hash.
+- If you configured an *Authorization header* on the source, it is sent verbatim in the `Authorization` header. It is stored server-side and never shown again in any API response.
+
+Respond with JSON:
+
+```json
+{
+ "items": [
+ {
+ "id": "note-42",
+ "title": "Deployment runbook",
+ "content": "# Runbook\nRestart the ingest worker before each release.",
+ "doc_time": "2026-08-20T09:00:00Z",
+ "mime": "text/markdown"
+ }
+ ],
+ "deleted": ["note-17"]
+}
+```
+
+Field reference:
+
+| Field | Required | Meaning |
+|---|---|---|
+| `id` | yes | Stable identity within this source. Same `id` + new `content` → the document is updated in place. |
+| `title` | no | Display name; the file extension is inferred from `mime` when missing. Defaults to `id`. |
+| `content` | yes | Full text of the item (not a diff). |
+| `doc_time` | no | RFC 3339. Becomes the document's time axis position — feed the real publish/effective time whenever you have it. |
+| `mime` | no | `text/markdown` (default), `text/plain`, or `text/html`. |
+| `deleted` | no | Array of `id`s your source has retired. Matching documents are **marked "Not in source"**, never auto-deleted — a person decides in the Library. Returning an item again clears the mark. |
+
+Notes:
+
+- Items missing from a response are **not** treated as deleted (the response may be incremental). Only the `deleted` array signals retirement.
+- Endpoints on `localhost` are fetched directly, bypassing any system HTTP proxy.
+
+---
+
+## API source — the push interface
+
+Create an **API** source; it gets its own push token (view or rotate it from the source's Token dialog). Then:
+
+```
+POST {your-utopia-base}/api/v1/sources/{source_id}/ingest
+Authorization: Bearer utp_…
+Content-Type: application/json
+```
+
+```json
+{
+ "filename": "runbook.md",
+ "content": "# Runbook\nRestart the ingest worker before each release.",
+ "doc_time": "2026-08-20T09:00:00Z",
+ "external_id": "note-42"
+}
+```
+
+| Field | Required | Meaning |
+|---|---|---|
+| `filename` | yes | Display name; also the fallback identity when `external_id` is absent. |
+| `content` | yes* | Full text. *Optional when `deleted` is `true`.* |
+| `doc_time` | no | RFC 3339; the document's position on the time axis. |
+| `external_id` | no | Stable identity. Same identity + new content → update in place. Without it, `filename` is the identity. |
+| `deleted` | no | `true` marks the identified document "Not in source" (tombstone). A later normal push of the same identity revives it. |
+
+The response tells you what happened:
+
+```json
+{ "action": "created" }
+```
+
+`created` · `updated` · `moved` (same content, new name) · `unchanged` · `marked_missing`.
+
+Example with curl:
+
+```bash
+curl -X POST "https://utopia.example.com/api/v1/sources/01a0…/ingest" \
+ -H "Authorization: Bearer utp_…" \
+ -H "Content-Type: application/json" \
+ -d '{"filename":"runbook.md","content":"# Runbook v2 …","external_id":"note-42"}'
+```
+
+---
+
+## Shared semantics
+
+- **Identity, not filenames.** Documents are tracked by `custom:{id}` / `api:{external_id}` keys. Renames are recognized as moves; content changes update the same document.
+- **Updates keep history.** Every content change records a version; earlier extracted knowledge keeps its provenance.
+- **Deletion is a marker.** Tombstones set a "Not in source" flag; the Library shows a cleanup action, and a human confirms actual deletion.
+- **`doc_time` drives the time axis.** Documents without it fall back to their ingestion time — real timestamps make the temporal graph meaningfully better.
diff --git a/web/src/i18n.ts b/web/src/i18n.ts
new file mode 100644
index 00000000..530da4dc
--- /dev/null
+++ b/web/src/i18n.ts
@@ -0,0 +1,709 @@
+// i18n shell: all UI strings live here, English-only for now.
+// Later: swap this module for a real i18n runtime (i18next) without touching components.
+export const S = {
+ app: {
+ name: "Utopia",
+ tagline: "The living memory of your organization",
+ siteUrl: "https://utopia.bi",
+ docsUrl: "https://utopia.bi/docs",
+ },
+ toast: {
+ saved: "Saved",
+ created: "Created",
+ deleted: "Deleted",
+ added: "Added to the ontology",
+ },
+ account: {
+ /* 账户区字标:Persona——你在这座城里的身份面具 */
+ brand: "Utopia Persona",
+ /* 网页标题用的短名:`Utopia | Persona` */
+ titleTag: "Persona",
+ profile: "Profile",
+ administration: "Administration",
+ adminChip: "Admin",
+ backToApp: "← Back to app",
+ profileTitle: "Profile",
+ displayName: "Display name",
+ email: "Email",
+ save: "Save",
+ passwordTitle: "Change password",
+ currentPassword: "Current password",
+ newPassword: "New password (min. 8 characters)",
+ changePassword: "Update password",
+ passwordChanged: "Password updated",
+ avatarHint: "Avatars are generated from your name for now.",
+ kbsNav: "Knowledge bases",
+ kbsTitle: "Knowledge bases",
+ kbOpen: "Open",
+ kbRestricted: "Restricted",
+ kbStats: (docs: number, members: number) =>
+ `${docs} doc${docs === 1 ? "" : "s"} · ${members} member${members === 1 ? "" : "s"}`,
+ addedBy: (name: string, date: string) => `Added by ${name} · ${date}`,
+ joinedOn: (date: string) => `Joined ${date}`,
+ openToEveryone: "Open to everyone",
+ deploymentAdmin: "Deployment admin",
+ openKb: "Open",
+ kbSettingsBtn: "Settings",
+ roleNames: {
+ owner: "Owner",
+ admin: "Admin",
+ editor: "Editor",
+ viewer: "Viewer",
+ } as Record<string, string>,
+ },
+ docs: {
+ /* 文档区字标:Charter——理想之城的立城宪章,与主字标同字体同字号 */
+ brand: "Utopia Charter",
+ backTitle: "Back to Utopia",
+ searchPlaceholder: "Search the docs…",
+ noResults: "No matches.",
+ },
+ nav: {
+ workspaceLabel: "Workspace",
+ kbLabel: "Knowledge base",
+ ask: "Chat",
+ askHint: "Converse with your knowledge base — it can remember",
+ search: "Search",
+ searchHint: "Hybrid search",
+ graph: "Graph",
+ graphHint: "Entities & timelines",
+ library: "Library",
+ libraryHint: "Documents & ingestion",
+ settings: "Settings",
+ settingsHint: "Models & members",
+ signOut: "Sign out",
+ docs: "Docs",
+ loading: "Loading…",
+ serverUnreachable: "Punishment 500: Utopia has gone quiet — it isn't answering.",
+ notFound: "Punishment 404: You are lost in Utopia.",
+ returnHome: "Return home",
+ reportIssue: "Report an issue",
+ refresh: "Refresh",
+ },
+ login: {
+ signIn: "Sign in",
+ signUp: "Sign up",
+ displayName: "Display name",
+ email: "Email",
+ password: "Password (min. 8 characters)",
+ submitting: "One moment…",
+ createAccount: "Create account",
+ networkError: "Network error, please try again",
+ // 惯用同意句式:By continuing, you agree to the <Terms> and acknowledge the <Privacy>.
+ agreePrefix: "By continuing, you agree to the ",
+ agreeAnd: " and acknowledge the ",
+ agreeSuffix: ".",
+ githubUrl: "https://github.com/deeplethe/utopia",
+ },
+ legal: {
+ privacyTitle: "Privacy policy",
+ termsTitle: "Terms of use",
+ backToSignIn: "← Back to sign in",
+ privacy: {
+ title: "Privacy policy",
+ note: "Default text bundled with Utopia. The organization operating this deployment may replace it with its own policy.",
+ sections: [
+ {
+ h: "A self-hosted platform",
+ body: [
+ "Utopia runs entirely on infrastructure chosen by the organization that deployed it (the operator). The Utopia project has no access to this deployment: the software sends no telemetry, no analytics and no crash reports to anyone.",
+ ],
+ },
+ {
+ h: "What this instance stores",
+ body: ["Everything below lives on the operator's own servers:"],
+ bullets: [
+ "Account details — your email address, display name and a hash of your password.",
+ "Content — uploaded documents, text extracted from them, search indexes and embeddings, and the knowledge graph (entities, relations and their sources) built from that content.",
+ "Activity — your conversations with the assistant, review decisions and ingestion logs, kept so the features that need them can work.",
+ ],
+ },
+ {
+ h: "Where data can leave this server",
+ body: [
+ "If the operator configures an external model provider for chat or embeddings, excerpts of documents and your messages are sent to that provider to answer questions and index content. Which provider — or whether a fully local model is used — is a deployment setting. Nothing else is sent anywhere.",
+ ],
+ },
+ {
+ h: "Who can see what",
+ body: [
+ "Access follows knowledge-base roles: viewers see the knowledge bases they were granted, editors can change content, admins manage members and settings. Deployment administrators can create accounts and see the user list.",
+ ],
+ },
+ {
+ h: "Retention and deletion",
+ body: [
+ "Deleting a document removes its stored content and index entries. Facts already extracted into the knowledge graph remain, with their provenance, until removed through Review. Deleting a knowledge base permanently removes its documents, graph and sources.",
+ ],
+ },
+ {
+ h: "Questions",
+ body: [
+ "This deployment is run by your organization. For questions about how your data is handled here, contact its administrator.",
+ ],
+ },
+ ],
+ },
+ terms: {
+ title: "Terms of use",
+ note: "Default text bundled with Utopia. The organization operating this deployment may replace it with its own terms.",
+ sections: [
+ {
+ h: "About these terms",
+ body: [
+ "This instance of Utopia is operated by the organization that deployed it, not by the Utopia project. Your use of it is governed by that organization's own policies; these default terms cover the basics until the operator replaces them.",
+ ],
+ },
+ {
+ h: "Your account",
+ body: [
+ "Keep your credentials to yourself. Administrators may create, suspend or remove accounts in line with the operator's policies.",
+ ],
+ },
+ {
+ h: "Acceptable use",
+ body: [],
+ bullets: [
+ "Upload only content you are authorized to store and share within your organization.",
+ "Respect access levels: do not attempt to view or change knowledge bases beyond the roles you were granted.",
+ "Do not use the platform to store or spread unlawful content.",
+ ],
+ },
+ {
+ h: "AI-generated answers",
+ body: [
+ "Answers from the assistant are generated from your organization's documents by a language model, with citations. They can be wrong or incomplete — verify against the cited sources before relying on them.",
+ ],
+ },
+ {
+ h: "The software",
+ body: [
+ "Utopia is open-source software provided “as is”, without warranty of any kind. Responsibility for operating this deployment — including backups, availability and compliance — lies with the operator.",
+ ],
+ },
+ ],
+ },
+ },
+ library: {
+ title: "Library",
+ upload: "Upload files",
+ uploading: "Uploading…",
+ uploadFailed: "Upload failed",
+ dropHint: "Drag files here, or click “Upload files”",
+ formats: "PDF · Word · Excel · PowerPoint · Markdown · HTML · TXT · CSV and more",
+ emptyPull: "No documents yet — they arrive when this source syncs.",
+ filterPlaceholder: "Filter by name",
+ filterNoMatch: "No documents match your filter.",
+ colFile: "File",
+ colStatus: "Status",
+ colGraph: "Graph",
+ colChunks: "Chunks",
+ colSize: "Size",
+ colSource: "Source",
+ delete: "Delete",
+ extract: "Extract",
+ reExtract: "Re-extract",
+ reprocess: "Reprocess",
+ status: {
+ pending: "Queued",
+ parsing: "Parsing",
+ indexing: "Indexing",
+ embedding: "Embedding",
+ ready: "Ready",
+ failed: "Failed",
+ },
+ graphStatus: {
+ none: "—",
+ queued: "Queued",
+ extracting: "Extracting",
+ done: "Done",
+ failed: "Failed",
+ },
+ sources: "Sources",
+ allDocs: "All documents",
+ uploads: "Uploads",
+ addSource: "Add source",
+ sourceKinds: {
+ folder: "Folder",
+ url: "URLs",
+ rss: "RSS feed",
+ api: "API",
+ custom: "Custom",
+ },
+ sourceKindHints: {
+ folder:
+ "A plain folder. Select it and upload (or drag) files straight into it — nothing is watched or synced.",
+ url: "Fetches the listed web pages; changed pages update the same document.",
+ rss: "Subscribes to a feed; each entry becomes a document dated by its publish time.",
+ api: "External systems push JSON documents here, authenticated with this source's own token.",
+ custom:
+ "Polls a URL you control on a schedule — your service returns JSON items and Utopia keeps them in sync.",
+ memory:
+ "Episodes remembered from Chat. Append-only: contradicted memories close their " +
+ "validity range instead of being deleted — the timeline keeps the whole story.",
+ },
+ ingestGuide: "Read the ingest guide →",
+ ingestGuideTitle: "Ingest interface guide",
+ endpointField: "Endpoint URL",
+ endpointCopied: "Endpoint URL copied",
+ copyEndpoint: "Click to copy the full URL",
+ // api 来源的推送状态(queued/running 不会出现,仅为类型完备)
+ pushStatus: {
+ never: "No pushes yet",
+ queued: "—",
+ running: "—",
+ ok: "Push received",
+ failed: "Push failed",
+ },
+ tokenTitle: "Source token",
+ tokenWarning:
+ "Anyone holding this token can push documents into this source. Rotate it if it leaks — the old token stops working immediately.",
+ tokenUsage: "Send it with every push as:",
+ tokenCopied: "Token copied",
+ viewToken: "Token",
+ rotateToken: "Rotate",
+ noToken: "This source has no token yet — generate one to start pushing.",
+ generateToken: "Generate token",
+ close: "Close",
+ authHeaderField: "Authorization header (optional, never shown again)",
+ syncNow: "Sync now",
+ syncStatus: {
+ never: "Never synced",
+ queued: "Queued",
+ running: "Syncing…",
+ ok: "Synced",
+ failed: "Sync failed",
+ },
+ lastSyncAdded: (n: number) => `+${n} last sync`,
+ sourceName: "Name",
+ urlsField: "Page URLs (one per line)",
+ feedUrl: "Feed URL",
+ interval: "Sync schedule",
+ intervalManual: "Manual only",
+ intervalEvery: (m: number) => (m < 60 ? `Every ${m} min` : `Every ${m / 60} h`),
+ schedule: {
+ manual: "Manual",
+ interval: "Interval",
+ daily: "Daily",
+ weekly: "Weekly",
+ advanced: "Advanced",
+ every: "Every",
+ minutes: "minutes",
+ hours: "hours",
+ at: "at",
+ cronPlaceholder: "Enter a cron expression",
+ whatIsCron: "What is cron?",
+ cronDocsUrl: "https://crontab.guru",
+ daysShort: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
+ dailyAt: (t: string) => `Daily ${t}`,
+ },
+ createSource: "Create",
+ cancel: "Cancel",
+ deleteSource: "Delete source",
+ deleteSourceHint: "Documents are kept and move to Uploads.",
+ newSourceTitle: "New source",
+ iconLabel: "Icon",
+ pageOf: (from: number, to: number, total: number) => `${from}–${to} of ${total}`,
+ syncHistory: "History",
+ runNew: (n: number) => `+${n} new`,
+ runUpdated: (n: number) => `~${n} updated`,
+ runNothing: "no changes",
+ noRuns: "No syncs recorded yet.",
+ sourceSettings: "Source settings",
+ editSourceTitle: "Source settings",
+ saveChanges: "Save changes",
+ authHeaderEditField: "Authorization header",
+ authKeepHint: "Leave blank to keep the current value.",
+ editKeepNote:
+ "Changing what this source fetches never deletes existing documents. " +
+ "Items the new configuration no longer returns are marked “Not in source” " +
+ "after the next sync. Switching to a different service entirely? Create a new source instead.",
+ notInSource: "Not in source",
+ cleanupMissing: (n: number) => `Clean up ${n} missing`,
+ cleanupTitle: "Delete missing documents",
+ cleanupHint: (n: number, name: string) =>
+ `${n} document${n === 1 ? "" : "s"} in “${name}” ${n === 1 ? "is" : "are"} no longer ` +
+ "present in the source. Deleting removes their content and search entries permanently. " +
+ "Facts already extracted into the graph remain, with their provenance.",
+ cleanupConfirm: "Delete them",
+ deleteSourceTitle: "Delete this source",
+ deleteSourceBody: (name: string) =>
+ `Type “${name}” to confirm. Documents are kept and move to Uploads; ` +
+ "scheduled syncing stops.",
+ dangerZone: "Danger zone",
+ },
+ search: {
+ placeholder: "Search the knowledge base… (keyword + semantic)",
+ button: "Search",
+ searching: "Searching…",
+ noResults: "No results found",
+ chunkOf: (filename: string, seq: number) => `${filename} · section ${seq}`,
+ },
+ ask: {
+ /* 新对话首屏问候:碑铭衬线,品牌名入句(标题不带句号) */
+ greeting: "Ask Utopia what it remembers",
+ emptyTitle: "Chat",
+ emptyBody:
+ "Converse with your knowledge base — cited answers, temporal questions, and it can remember.\nUpload documents in Library and configure a model in Settings first.",
+ placeholder: "Ask anything…",
+ composerHint: "Enter to send · Shift+Enter for a new line",
+ scopeLabel: "Knowledge base",
+ send: "Send",
+ stop: "Stop",
+ thinking: "Thinking…",
+ newChat: "New chat",
+ untitled: "Untitled",
+ noConversations: "No conversations yet.",
+ deleteConversation: "Delete conversation",
+ deleteTitle: "Delete conversation?",
+ deleteHint: (name: string) => `“${name}” and its messages will be permanently removed.`,
+ deleteBtn: "Delete",
+ cancel: "Cancel",
+ },
+ graph: {
+ zoomIn: "Zoom in",
+ zoomOut: "Zoom out",
+ fitView: "Fit view",
+ layoutForce: "Force layout",
+ layoutCircular: "Circular layout",
+ layoutPack: "Cluster by type",
+ searchEntity: "Search entities…",
+ searchInSubgraph: "Search in subgraph…",
+ backToOverview: "← Full graph",
+ emptyBody:
+ "The graph is empty. Upload documents and configure a chat model in Settings — entities and relations are extracted automatically.",
+ facts: "facts",
+ noFacts: "No facts for this entity yet",
+ confidence: "confidence",
+ evidence: "evidence",
+ noEvidence: "No evidence recorded",
+ noQuote: "(no quote)",
+ sectionRef: (filename: string, seq: number) => `${filename} · section ${seq} →`,
+ fromVersion: (v: number) => `v${v}`,
+ staleEvidenceHint:
+ "This evidence comes from an earlier version of the document. " +
+ "The document has since been updated; the fact itself is unaffected.",
+ staleFactChip: "unconfirmed",
+ staleFactHint:
+ "All evidence for this fact comes from earlier versions of its source documents — " +
+ "the current content no longer states it. It may still be true; review it under Review.",
+ viewRelations: "Relations",
+ viewTimeline: "Timeline",
+ historicalNote: (n: number) =>
+ `${n} past fact${n === 1 ? "" : "s"} not shown — see Timeline →`,
+ undated: "Undated",
+ timelineEmpty: "No dated facts yet.",
+ lastConfirmed: (d: string) => `confirmed ${d}`,
+ correctedHint:
+ "This interval was closed by reconciliation (automatic succession or a review decision), " +
+ "not stated verbatim in a document. The superseded assertion remains in the ledger.",
+ ongoing: "now",
+ stats: (n: number, e: number, active: number) =>
+ `${n} entities · ${e} facts · ${active} active`,
+ stabilizing: "Stabilizing layout",
+ allTime: "All time",
+ nowBtn: "Now",
+ play: "Play timeline",
+ pause: "Pause",
+ },
+ doc: {
+ backToLibrary: "← Back to Library",
+ sections: "sections",
+ section: "Section",
+ citedHere: "← cited here",
+ loading: "Loading…",
+ extracted: "Extracted",
+ ongoing: "now",
+ },
+ settings: {
+ title: "System settings",
+ tabModels: "Models",
+ tabMembers: "Users",
+ tabKbs: "Knowledge bases",
+ tabDeployment: "Deployment",
+ newUser: "Create user",
+ initialPassword: "Initial password (min. 8 characters)",
+ createUserBtn: "Create",
+ searchUsers: "Filter by name or email…",
+ deployment: {
+ openReg: "Allow self-registration",
+ openRegHint:
+ "When off, the sign-up form is closed and only admins can create accounts here.",
+ workers: "Background workers",
+ workersHint:
+ "How many ingestion and extraction jobs run in parallel (1–32). More workers process " +
+ "documents faster but issue more concurrent model calls. Takes effect immediately.",
+ workersApply: "Apply",
+ },
+ datasources: {
+ tab: "Data sources",
+ title: "Data sources",
+ hint:
+ "Read-only database connections for asking questions about your data in Chat. " +
+ "Register connections here; each knowledge base mounts the ones it may query.",
+ name: "Name",
+ connString: "Connection string (postgres://user:pass@host:5432/db)",
+ add: "Add data source",
+ test: "Test",
+ testOk: "Connected",
+ testFail: "Failed",
+ neverTested: "Untested",
+ remove: "Remove",
+ },
+ kbs: {
+ hint:
+ "Every knowledge base in this deployment. Open ones are readable by all members; " +
+ "restricted ones are invite-only. Creating a knowledge base is an admin action — " +
+ "members switch between them from the top bar.",
+ defaultChip: "Default",
+ newKb: "New knowledge base",
+ name: "Name",
+ description: "Description",
+ visibility: "Visibility",
+ visOpen: "Open — everyone in this deployment",
+ visRestricted: "Invited only",
+ create: "Create",
+ openSettings: "Settings",
+ docs: (n: number) => `${n} docs`,
+ },
+ modelsIntro:
+ "OpenAI-compatible protocol — DeepSeek, Qwen, GLM, Ollama, vLLM all work. Fully on-prem friendly.",
+ chatModel: "Chat model",
+ embedModel: "Embedding model (optional, enables semantic search)",
+ baseUrl: "Base URL",
+ model: "Model",
+ apiKey: "API key",
+ keyConfigured: "(configured — leave blank to keep)",
+ save: "Save",
+ saving: "Saving…",
+ saved: "Saved",
+ test: "Test connection",
+ testing: "Testing…",
+ chatLabel: "Chat",
+ embedLabel: "Embedding",
+ ok: (reply: string) => `Connected (${reply})`,
+ okDim: (dim: number) => `Connected (dim ${dim})`,
+ },
+ ontology: {
+ title: "Ontology",
+ hint: "Classes & properties",
+ tabClasses: "Classes",
+ tabProperties: "Properties",
+ newClass: "New class",
+ newSubClass: "+ Sub-class",
+ newProperty: "New property",
+ filter: "Filter…",
+ missesShort: "Unmatched",
+ instances: "Instances",
+ instanceFacts: (n: number) => `${n} facts`,
+ description: "Description",
+ descriptionHint:
+ "Guides the extractor: what belongs here, with a couple of examples. Fed straight into the extraction prompt.",
+ overviewHint:
+ "The schema your extractor follows. Select a class or property on the left to edit it, or add new ones with the + buttons.",
+ overviewStats: (c: number, p: number) => `${c} classes · ${p} properties`,
+ attributes: "Attributes",
+ attributesHint:
+ "Literal-valued fields of this class (a person's salary, a contract's amount). Extracted with evidence and history, like any fact.",
+ newAttribute: "New attribute",
+ attrDatatype: "Value type",
+ attrUnit: "Unit",
+ attrUnitHint: "optional — e.g. CNY, %",
+ attrSingle: "Single-valued — a new value closes the previous one",
+ datatypeNames: {
+ text: "Text",
+ number: "Number",
+ date: "Date",
+ bool: "Yes / no",
+ } as Record<string, string>,
+ cancel: "Cancel",
+ key: "Key",
+ label: "Label",
+ color: "Color",
+ shapeColor: "Shape & color",
+ parent: "Parent class",
+ noParent: "(top level)",
+ temporal: "Temporal semantics",
+ temporalState: "State (has interval)",
+ temporalEvent: "Event (point in time)",
+ temporalEternal: "Eternal (timeless)",
+ functional: "Functional (single value at a time)",
+ inverseFunctional: "Inverse functional (one subject per object at a time)",
+ usage: (n: number) => `${n} in use`,
+ builtin: "built-in",
+ save: "Save",
+ delete: "Delete",
+ deleteBlocked: "In use — cannot delete",
+ misses: "Unmatched from extraction",
+ missesHint:
+ "The extractor produced these outside your ontology (they fell back to concept / related to). They are signals for extending the ontology.",
+ dismiss: "Dismiss",
+ suggest: "Suggest with AI",
+ suggesting: "Analyzing…",
+ noMisses: "No unmatched types — the ontology covers your corpus.",
+ approve: "Add",
+ proposals: "AI proposals",
+ keyHint: "lowercase_snake_case",
+ },
+ review: {
+ title: "Review",
+ hint: "Duplicates & low-confidence facts",
+ tabQueue: "Queue",
+ tabHistory: "History",
+ empty: "Nothing to review — the graph is clean.",
+ historyEmpty: "No merges yet.",
+ // 左栏分类导航
+ railDuplicates: "Duplicates",
+ railConflicts: "Conflicts",
+ railUnconfirmed: "Unconfirmed",
+ railLowConfidence: "Low confidence",
+ railDecisions: "Decisions",
+ railMerges: "Merges",
+ categoryEmpty: "This queue is clear.",
+ // 决策台账
+ decisionsTitle: "Decisions",
+ decisionsHint:
+ "Every review decision, by whom and when — snapshots taken at decision time, kept even after the underlying fact is gone.",
+ decisionsEmpty: "No decisions recorded yet.",
+ aiActor: "AI adjudicator",
+ decisionActions: {
+ "review.merge": "Merged",
+ "review.keep": "Kept apart",
+ "fact.confirm": "Confirmed",
+ "fact.reject": "Rejected",
+ "fact.close": "Closed",
+ "conflict.close_old": "Closed old",
+ "conflict.keep_both": "Kept both",
+ "conflict.reject_new": "Rejected new",
+ "merge.revert": "Reverted merge",
+ "merge.manual": "Merged manually",
+ } as Record<string, string>,
+ duplicates: "Possible duplicates",
+ duplicatesHint:
+ "Same name, different context. The AI adjudicates clear cases in the background; the rest wait for you. Merging is always reversible.",
+ stageAdjudicating: "AI adjudicating",
+ stageHuman: "Needs your decision",
+ similarity: (pct: number) => `${pct}% context similarity`,
+ factsCount: (n: number) => `${n} facts`,
+ noFacts: "No recorded facts",
+ merge: "Merge",
+ keep: "Keep separate",
+ lowConfidence: "Low-confidence facts",
+ lowConfidenceHint:
+ "Extracted with confidence below 75%. Confirm to trust, reject to remove from the graph (the ledger keeps the record).",
+ confirm: "Confirm",
+ reject: "Reject",
+ confidence: (pct: number) => `${pct}%`,
+ mergeHistory: "Merge history",
+ mergedBy: (name: string) => `by ${name}`,
+ mergedByAi: "by AI adjudicator",
+ revert: "Revert",
+ reverted: "Reverted",
+ ongoing: "now",
+ conflicts: "Temporal conflicts",
+ conflictsHint:
+ "Two facts claim the same single-valued relation. Clear successions close automatically; " +
+ "these need a human call. Closing is reversible through the ledger.",
+ conflictReason: {
+ no_time: "new fact has no date",
+ simultaneous: "same start date",
+ low_confidence: "low confidence",
+ } as Record<string, string>,
+ conflictVs: "vs",
+ conflictSince: (d: string) => `since ${d}`,
+ closeOld: "Close old",
+ closeOldAt: (d: string) => `Close old at ${d}`,
+ keepBoth: "Keep both",
+ rejectNew: "Reject new",
+ closeAtPlaceholder: "YYYY-MM-DD",
+ unconfirmed: "No longer stated",
+ unconfirmedHint:
+ "Every source that stated these facts has since been updated without them. " +
+ "Nothing is deleted automatically — absence isn't negation. Reject extraction " +
+ "errors, or close a fact that genuinely ended (pick the date it ended).",
+ closeFact: "Close",
+ closeFactAt: (d: string) => `Close at ${d}`,
+ },
+ /** 通用组件文案(SearchSelect 等) */
+ ui: {
+ noMatches: "No matches",
+ keepTyping: (n: number) => `${n} more — keep typing to narrow down`,
+ },
+ kbset: {
+ title: "Knowledge base settings",
+ general: "General",
+ members: "Members",
+ defaultOpenLabel: "Open to everyone",
+ defaultOpenNote:
+ "This is the deployment's default knowledge base, so visibility is locked: every member " +
+ "gets at least viewer access here, which guarantees nobody signs in to an empty screen. " +
+ "It can't be deleted for the same reason. To give someone more than viewing, grant a " +
+ "role under Members; for a private space, create a separate knowledge base and set it " +
+ "to Restricted.",
+ data: "Data",
+ dataHint:
+ "Mounted read-only databases this knowledge base may query from Chat. " +
+ "Mounting ingests the database schema so the assistant knows the tables.",
+ dataMount: "Mount",
+ dataUnmount: "Unmount",
+ dataSyncSchema: "Refresh schema",
+ dataSchemaSynced: (n: number) => `Schema ingested (${n} tables)`,
+ dataExplore: "Explore mappings",
+ dataExploreHint:
+ "An agent reads the schemas and proposes metric/dimension definitions — review them in Review before Chat uses them.",
+ dataExploreQueued: "Exploration queued — proposals will appear in Review shortly.",
+ dataNone: "No data sources mounted.",
+ dataNoneAvailable: "No data sources registered yet — ask a deployment admin to register one.",
+ dataNewConn: "Register a new connection",
+ activity: "Activity",
+ activityHint:
+ "Who changed what in this knowledge base. Pure audit — records are append-only.",
+ activityEmpty: "Nothing recorded yet.",
+ deletedUser: "a removed user",
+ auditActions: {
+ "entity_type.created": "created entity type",
+ "entity_type.updated": "updated entity type",
+ "entity_type.deleted": "deleted an entity type",
+ "relation_type.created": "created relation type",
+ "relation_type.updated": "updated relation type",
+ "relation_type.deleted": "deleted a relation type",
+ "kb.updated": "updated knowledge base settings",
+ "kb.member_set": "set a member role",
+ "kb.member_removed": "removed a member",
+ "source.created": "created source",
+ "source.updated": "updated source",
+ "source.deleted": "deleted a source",
+ "document.deleted": "deleted document",
+ } as Record<string, string>,
+ membersHint:
+ "Everyone in the deployment can read an open KB; write access is granted here " +
+ "(deployment admins always have it). On an invited-only KB, only people listed here can see it.",
+ addMember: "Add…",
+ roles: { viewer: "Viewer", editor: "Editor", admin: "Admin" },
+ remove: "Remove",
+ noMembers: "No per-KB roles set.",
+ save: "Save",
+ saved: "Saved",
+ danger: "Danger zone",
+ deleteKb: "Delete this knowledge base",
+ deleteHint: (name: string) => `Type “${name}” to confirm. Documents, graph and sources are permanently removed.`,
+ deleteBtn: "Delete permanently",
+ deleteRowTitle: "Delete this knowledge base",
+ deleteRowHint: "Documents, graph and sources are removed permanently.",
+ deleteRowBtn: "Delete",
+ },
+ members: {
+ title: "Deployment users",
+ systemAdmin: "System admin",
+ remove: "Remove",
+ pickUser: "Select a user to add…",
+ add: "Add",
+ allAdded: "Everyone in this deployment is already a member. New signups will appear here.",
+ roles: {
+ owner: "Owner",
+ admin: "Admin",
+ editor: "Editor",
+ viewer: "Viewer",
+ },
+ },
+} as const;
diff --git a/web/src/kb.tsx b/web/src/kb.tsx
new file mode 100644
index 00000000..41c5492c
--- /dev/null
+++ b/web/src/kb.tsx
@@ -0,0 +1,52 @@
+// 当前工作区/知识库上下文:均可切换且 localStorage 记忆;工作区无 KB 时自动创建 "General"。
+import { useSyncExternalStore } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { api, type Kb, type Workspace } from "./api";
+import { kbStore, wsStore } from "./wsStore";
+
+export function useKb(): {
+ kb: Kb | null;
+ kbs: Kb[];
+ workspace: Workspace | null;
+ workspaces: Workspace[];
+ setWorkspace: (id: string) => void;
+ setKb: (id: string) => void;
+} {
+ const queryClient = useQueryClient();
+ const selectedId = useSyncExternalStore(wsStore.subscribe, wsStore.get);
+ const selectedKbId = useSyncExternalStore(kbStore.subscribe, kbStore.get);
+
+ const workspaces = useQuery({ queryKey: ["workspaces"], queryFn: api.workspaces });
+ const list = workspaces.data ?? [];
+ const ws = list.find((w) => w.id === selectedId) ?? list[0] ?? null;
+
+ const kbs = useQuery({
+ queryKey: ["kbs", ws?.id],
+ queryFn: async () => {
+ const existing = await api.kbs(ws!.id);
+ if (existing.length > 0) return existing;
+ // 空工作区自动创建 General——建库现在是管理员动作,非管理员会 403:
+ // 静默等管理员来创建(现实中首个用户即管理员,General 总在)
+ try {
+ const created = await api.createKb(ws!.id, { name: "General" });
+ queryClient.invalidateQueries({ queryKey: ["kbs", ws!.id] });
+ return [created];
+ } catch {
+ return [];
+ }
+ },
+ enabled: !!ws,
+ });
+
+ const kbList = kbs.data ?? [];
+ const kb = kbList.find((k) => k.id === selectedKbId) ?? kbList[0] ?? null;
+
+ return {
+ kb,
+ kbs: kbList,
+ workspace: ws,
+ workspaces: list,
+ setWorkspace: wsStore.set,
+ setKb: kbStore.set,
+ };
+}
diff --git a/web/src/main.tsx b/web/src/main.tsx
new file mode 100644
index 00000000..3a56b467
--- /dev/null
+++ b/web/src/main.tsx
@@ -0,0 +1,22 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { RouterProvider } from "@tanstack/react-router";
+import { router } from "./router";
+import { ToastHost } from "./toast";
+import "./styles.css";
+
+const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, refetchOnWindowFocus: false },
+ },
+});
+
+createRoot(document.getElementById("root")!).render(
+ <StrictMode>
+ <QueryClientProvider client={queryClient}>
+ <RouterProvider router={router} />
+ <ToastHost />
+ </QueryClientProvider>
+ </StrictMode>,
+);
diff --git a/web/src/pages/Account.tsx b/web/src/pages/Account.tsx
new file mode 100644
index 00000000..4613c80b
--- /dev/null
+++ b/web/src/pages/Account.tsx
@@ -0,0 +1,119 @@
+/* 个人信息页:头像(首字母占位)、显示名、邮箱、改密码。 */
+import { useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { S } from "../i18n";
+import { Loading } from "../ui";
+import { toast } from "../toast";
+import { Avatar } from "./UserMenu";
+
+export function Account() {
+ const queryClient = useQueryClient();
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+
+ const [name, setName] = useState<string | null>(null);
+ const [curPw, setCurPw] = useState("");
+ const [newPw, setNewPw] = useState("");
+
+ const saveName = useMutation({
+ mutationFn: (n: string) => api.updateMe(n),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["me"] });
+ setName(null);
+ toast.success(S.toast.saved);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+
+ const changePw = useMutation({
+ mutationFn: () => api.changePassword(curPw, newPw),
+ onSuccess: () => {
+ setCurPw("");
+ setNewPw("");
+ toast.success(S.account.passwordChanged);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+
+ if (!me.data) return <Loading>{S.nav.loading}</Loading>;
+ const displayName = name ?? me.data.display_name;
+ const nameDirty = displayName.trim() !== me.data.display_name && displayName.trim();
+
+ const field = (label: string, node: React.ReactNode) => (
+ <div className="mb-4">
+ <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
+ {node}
+ </div>
+ );
+
+ return (
+ <div className="max-w-lg p-8">
+ <h1 className="u-title text-lg mb-6">{S.account.profileTitle}</h1>
+
+ <div className="glass rounded-2xl p-5 mb-4">
+ <div className="flex items-center gap-4 mb-5">
+ <Avatar name={me.data.display_name} size={56} />
+ <p className="text-xs text-neutral-500">{S.account.avatarHint}</p>
+ </div>
+
+ {field(
+ S.account.displayName,
+ <div className="flex gap-2">
+ <input
+ className="input-dark flex-1 px-3 py-2 text-sm"
+ value={displayName}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <button
+ className="u-btn u-btn-primary px-3.5 text-xs"
+ disabled={!nameDirty || saveName.isPending}
+ onClick={() => saveName.mutate(displayName.trim())}
+ >
+ {S.account.save}
+ </button>
+ </div>,
+ )}
+
+ {field(
+ S.account.email,
+ <div className="text-sm text-neutral-400 px-0.5">{me.data.email}</div>,
+ )}
+ </div>
+
+ <div className="glass rounded-2xl p-5">
+ <h2 className="text-[13px] font-medium text-neutral-200 mb-4">
+ {S.account.passwordTitle}
+ </h2>
+ {field(
+ S.account.currentPassword,
+ <input
+ type="password"
+ autoComplete="current-password"
+ className="input-dark w-full px-3 py-2 text-sm"
+ value={curPw}
+ onChange={(e) => setCurPw(e.target.value)}
+ />,
+ )}
+ {field(
+ S.account.newPassword,
+ <input
+ type="password"
+ autoComplete="new-password"
+ className="input-dark w-full px-3 py-2 text-sm"
+ value={newPw}
+ onChange={(e) => setNewPw(e.target.value)}
+ />,
+ )}
+ <div className="flex justify-end">
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!curPw || newPw.length < 8 || changePw.isPending}
+ onClick={() => changePw.mutate()}
+ >
+ {S.account.changePassword}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/AccountShell.tsx b/web/src/pages/AccountShell.tsx
new file mode 100644
index 00000000..fc6de541
--- /dev/null
+++ b/web/src/pages/AccountShell.tsx
@@ -0,0 +1,97 @@
+/* 账户层壳:Profile / Administration 的宿主。
+ 与 KB 无关,所以没有 KB 切换器、没有 tab 导航——只有字标、返回、用户菜单。 */
+import { useQuery } from "@tanstack/react-query";
+import { Link, Outlet, useNavigate } from "@tanstack/react-router";
+import { usePageTitle } from "../useTitle";
+import { BookMarked, ShieldCheck, UserRound } from "lucide-react";
+import { api, ApiError } from "../api";
+import { S } from "../i18n";
+import { GithubMark, RAIL_CLS, SectionMark } from "../ui";
+import { ServerDown } from "./ServerDown";
+import { UserMenu } from "./UserMenu";
+
+export function AccountShell() {
+ const navigate = useNavigate();
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });
+ // 标题:`Utopia | Persona`——账户区整体一个名字,不逐页细分
+ usePageTitle(S.app.name, S.account.titleTag);
+
+ if (me.isPending) {
+ return (
+ <div className="min-h-screen flex items-center justify-center text-neutral-500 text-sm">
+ {S.nav.loading}
+ </div>
+ );
+ }
+ if (me.isError) {
+ if (me.error instanceof ApiError && me.error.status === 401) {
+ navigate({ to: "/login" });
+ return null;
+ }
+ return <ServerDown />;
+ }
+
+ const rail =
+ "flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200";
+ const railActive = "flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] u-nav-active";
+
+ return (
+ <div className="h-screen flex flex-col overflow-hidden u-arrive">
+ {/* 顶栏与 Docs 页同构:分区字标(点击回城)+ 返回 + GitHub·版本 + 用户 */}
+ <header className="glass-strong relative z-40 border-x-0 border-t-0 h-14 shrink-0 flex items-center px-5">
+ <SectionMark text={S.account.brand} title={S.docs.backTitle} />
+ <div className="ml-auto flex items-center gap-1.5">
+ <Link
+ to="/graph"
+ className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
+ >
+ {S.account.backToApp}
+ </Link>
+ <a
+ href={S.login.githubUrl}
+ target="_blank"
+ rel="noreferrer"
+ title="GitHub"
+ className="flex items-center gap-1.5 rounded-full border border-white/10 px-2.5 py-1 text-neutral-500 hover:text-neutral-200 hover:border-white/25 transition-colors"
+ >
+ <GithubMark size={13} />
+ {health.data && <span className="u-num text-[11px]">v{health.data.version}</span>}
+ </a>
+ <div className="ml-1.5">
+ <UserMenu user={me.data} />
+ </div>
+ </div>
+ </header>
+
+ <div className="flex-1 min-h-0 flex">
+ {/* 账户导航栏(仅两项,管理员多一项) */}
+ <aside className={`${RAIL_CLS} p-3 space-y-0.5`}>
+ {/* exact:/account 是 /account/kbs 的前缀,默认前缀匹配会双亮 */}
+ <Link
+ to="/account"
+ activeOptions={{ exact: true }}
+ className={rail}
+ activeProps={{ className: railActive }}
+ >
+ <UserRound size={14} />
+ {S.account.profile}
+ </Link>
+ <Link to="/account/kbs" className={rail} activeProps={{ className: railActive }}>
+ <BookMarked size={14} />
+ {S.account.kbsNav}
+ </Link>
+ {me.data.is_admin && (
+ <Link to="/admin" className={rail} activeProps={{ className: railActive }}>
+ <ShieldCheck size={14} />
+ {S.account.administration}
+ </Link>
+ )}
+ </aside>
+ <main className="flex-1 min-w-0 overflow-y-auto u-scroll">
+ <Outlet />
+ </main>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsx
new file mode 100644
index 00000000..a281d990
--- /dev/null
+++ b/web/src/pages/Chat.tsx
@@ -0,0 +1,571 @@
+/* Chat:agentic 对话(检索/图谱工具 + remember 记忆)。
+ 会话持久化:左栏会话列表;上下文由服务端拼,前端只发 conversation_id + 新消息;
+ 行动轨迹(steps)与引用(sources)随消息落库,历史回放与实时流共用渲染。 */
+import { useEffect, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Link, useNavigate, useParams } from "@tanstack/react-router";
+import Markdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import rehypeHighlight from "rehype-highlight";
+import remend from "remend";
+import {
+ ArrowUp,
+ BookOpen,
+ Check,
+ ChevronDown,
+ Database,
+ History,
+ Search as SearchIcon,
+ Square,
+ SquarePen,
+ Trash2,
+ Waypoints,
+ Wrench,
+} from "lucide-react";
+import { ThinkingOrb, type OrbState } from "thinking-orbs";
+import {
+ conversationsApi,
+ streamChat,
+ type ChatStep,
+ type ConversationRow,
+ type Source,
+} from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { DangerConfirm, RAIL_CLS } from "../ui";
+
+interface Turn {
+ role: "user" | "assistant";
+ content: string;
+ sources?: Source[];
+ steps?: ChatStep[];
+ error?: string;
+}
+
+/** 同标签页记忆:上次会话(按库)与未发送草稿——切页回来还原,新标签页从头开始 */
+const lastKey = (kbId: string) => `chat:last:${kbId}`;
+const DRAFT_KEY = "chat:draft";
+
+export function Chat() {
+ const { kb, kbs, setKb } = useKb();
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ // 会话即路由:/chat/$conversationId,URL 是当前会话的唯一事实来源(刷新/回退天然可用)
+ const { conversationId: routeConvId } = useParams({ strict: false }) as {
+ conversationId?: string;
+ };
+ const [activeId, setActiveId] = useState<string | null>(null);
+ // 路由同步 effect 的判据:state 的提交时序晚于 navigate 触发的重渲染,
+ // 用 ref 同步写入才能让"流式新建后仅换 URL"的守卫可靠命中
+ const activeIdRef = useRef<string | null>(null);
+ const [turns, setTurns] = useState<Turn[]>([]);
+ const [input, setInput] = useState(() => sessionStorage.getItem(DRAFT_KEY) ?? "");
+ const [streaming, setStreaming] = useState(false);
+ const [scopeOpen, setScopeOpen] = useState(false);
+ const [pendingDelete, setPendingDelete] = useState<ConversationRow | null>(null);
+ const abortRef = useRef<(() => void) | null>(null);
+ const scopeRef = useRef<HTMLDivElement>(null);
+ const bottomRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+
+ // 作用域弹层:点外面 / Esc 关闭(与 ui/Dropdown 同惯例)
+ useEffect(() => {
+ if (!scopeOpen) return;
+ const onDoc = (e: MouseEvent) => {
+ if (!scopeRef.current?.contains(e.target as Node)) setScopeOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setScopeOpen(false);
+ };
+ document.addEventListener("mousedown", onDoc);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDoc);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [scopeOpen]);
+
+ const convs = useQuery({
+ queryKey: ["conversations", kb?.id],
+ queryFn: () => conversationsApi.list(kb!.id),
+ enabled: !!kb,
+ });
+
+ // 直落底部(instant):平滑滚动在流式追加下会一路慢爬
+ useEffect(() => {
+ bottomRef.current?.scrollIntoView({ behavior: "instant" });
+ }, [turns]);
+
+ // 切库回到新会话(首次拿到 kb 不算切换——直刷 /chat/$id 时不能把 URL 冲掉)
+ const prevKbRef = useRef<string | null>(null);
+ useEffect(() => {
+ const prev = prevKbRef.current;
+ prevKbRef.current = kb?.id ?? null;
+ if (prev && kb && prev !== kb.id) {
+ if (streaming) abortRef.current?.();
+ setStreaming(false);
+ activeIdRef.current = null;
+ setActiveId(null);
+ setTurns([]);
+ navigate({ to: "/chat", replace: true });
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [kb?.id]);
+
+ // 路由 → 会话装载;裸 /chat 还原本库上次会话(切页回来仍在原对话)
+ useEffect(() => {
+ if (!kb) return;
+ if (!routeConvId) {
+ const last = sessionStorage.getItem(lastKey(kb.id));
+ if (last) {
+ navigate({
+ to: "/chat/$conversationId",
+ params: { conversationId: last },
+ replace: true,
+ });
+ }
+ return;
+ }
+ if (routeConvId === activeIdRef.current) return; // 流式新建会话后仅 URL 同步,勿重载
+ loadConversation(routeConvId);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [kb?.id, routeConvId]);
+
+ // 还原的草稿撑开输入框(高度平时由 onChange 维护)
+ useEffect(() => {
+ const el = inputRef.current;
+ if (el && el.value) {
+ el.style.height = "auto";
+ el.style.height = `${Math.min(el.scrollHeight, 192)}px`;
+ }
+ }, []);
+
+ const invalidateList = () =>
+ queryClient.invalidateQueries({ queryKey: ["conversations", kb?.id] });
+
+ /** 列表点击只改 URL,装载由路由同步 effect 负责 */
+ const openConversation = (id: string) =>
+ navigate({ to: "/chat/$conversationId", params: { conversationId: id } });
+
+ const loadConversation = async (id: string) => {
+ if (streaming) abortRef.current?.();
+ setStreaming(false);
+ activeIdRef.current = id;
+ setActiveId(id);
+ try {
+ const { messages } = await conversationsApi.detail(kb!.id, id);
+ sessionStorage.setItem(lastKey(kb!.id), id);
+ setTurns(
+ messages.map((m) => ({
+ role: m.role,
+ content: m.content,
+ steps: m.steps.length ? m.steps : undefined,
+ sources: m.sources.length ? m.sources : undefined,
+ })),
+ );
+ } catch {
+ // 失效链接(会话已删 / 属于别的库):安静回到新对话
+ sessionStorage.removeItem(lastKey(kb!.id));
+ activeIdRef.current = null;
+ setActiveId(null);
+ setTurns([]);
+ navigate({ to: "/chat", replace: true });
+ }
+ };
+
+ const newChat = () => {
+ if (streaming) abortRef.current?.();
+ setStreaming(false);
+ if (kb) sessionStorage.removeItem(lastKey(kb.id));
+ activeIdRef.current = null;
+ setActiveId(null);
+ setTurns([]);
+ navigate({ to: "/chat" });
+ inputRef.current?.focus();
+ };
+
+ const removeConversation = async (id: string) => {
+ await conversationsApi.remove(kb!.id, id);
+ if (sessionStorage.getItem(lastKey(kb!.id)) === id) {
+ sessionStorage.removeItem(lastKey(kb!.id));
+ }
+ invalidateList();
+ if (id === activeId) newChat();
+ };
+
+ const send = () => {
+ const q = input.trim();
+ if (!q || streaming || !kb) return;
+ setInput("");
+ sessionStorage.removeItem(DRAFT_KEY);
+ if (inputRef.current) inputRef.current.style.height = "auto";
+ setTurns((prev) => [...prev, { role: "user", content: q }, { role: "assistant", content: "" }]);
+ setStreaming(true);
+
+ abortRef.current = streamChat(
+ kb.id,
+ { conversation_id: activeId ?? undefined, message: q },
+ {
+ onConversation: (id) => {
+ // 先同步写 ref 再换 URL:路由同步 effect 因 id 相等而跳过重载,不打断流
+ activeIdRef.current = id;
+ setActiveId(id);
+ sessionStorage.setItem(lastKey(kb.id), id);
+ navigate({
+ to: "/chat/$conversationId",
+ params: { conversationId: id },
+ replace: true,
+ });
+ invalidateList();
+ },
+ onSources: (sources) =>
+ setTurns((prev) => {
+ const next = [...prev];
+ next[next.length - 1] = { ...next[next.length - 1], sources };
+ return next;
+ }),
+ onStep: (step) =>
+ setTurns((prev) => {
+ const next = [...prev];
+ const last = next[next.length - 1];
+ next[next.length - 1] = { ...last, steps: [...(last.steps ?? []), step] };
+ return next;
+ }),
+ onDelta: (text) =>
+ setTurns((prev) => {
+ const next = [...prev];
+ const last = next[next.length - 1];
+ next[next.length - 1] = { ...last, content: last.content + text };
+ return next;
+ }),
+ onDone: () => {
+ setStreaming(false);
+ invalidateList();
+ },
+ onError: (message) => {
+ setStreaming(false);
+ setTurns((prev) => {
+ const next = [...prev];
+ next[next.length - 1] = { ...next[next.length - 1], error: message };
+ return next;
+ });
+ },
+ },
+ );
+ };
+
+ /* Composer 卡:新对话首屏居中出场,进入对话后停靠底部(同一块 JSX 两处复用) */
+ const composerCard = (
+ <div className="rounded-2xl border border-white/[0.12] bg-white/[0.04] backdrop-blur-md focus-within:border-white/30 transition-colors px-4 pt-3 pb-2">
+ <textarea
+ ref={inputRef}
+ rows={1}
+ className="w-full bg-transparent outline-none text-sm resize-none leading-relaxed max-h-48 u-scroll placeholder:text-neutral-600"
+ placeholder={S.ask.placeholder}
+ value={input}
+ onChange={(e) => {
+ setInput(e.target.value);
+ sessionStorage.setItem(DRAFT_KEY, e.target.value);
+ const el = e.currentTarget;
+ el.style.height = "auto";
+ el.style.height = `${Math.min(el.scrollHeight, 192)}px`;
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ send();
+ }
+ }}
+ />
+ <div className="flex items-center justify-between gap-3 pt-1">
+ <div className="flex items-center gap-2.5 min-w-0">
+ {/* 作用域 chip:提问点位可见"在问哪个库",切库沿用现有语义(开新会话) */}
+ <div ref={scopeRef} className="relative shrink-0">
+ <button
+ onClick={() => setScopeOpen((v) => !v)}
+ title={S.ask.scopeLabel}
+ className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-neutral-400 hover:text-neutral-200 hover:bg-white/[0.07] transition-colors max-w-52"
+ >
+ <Database size={12} className="shrink-0 text-neutral-500" />
+ <span className="truncate">{kb?.name ?? "…"}</span>
+ <ChevronDown
+ size={11}
+ className={`shrink-0 text-neutral-600 transition-transform ${
+ scopeOpen ? "rotate-180" : ""
+ }`}
+ />
+ </button>
+ {scopeOpen && (
+ <div className="u-pop u-pop-up absolute bottom-full mb-1.5 left-0 z-50 w-56 rounded-lg shadow-xl overflow-hidden">
+ <div className="px-2.5 pt-2 pb-1 text-[9.5px] font-medium uppercase tracking-[0.1em] text-neutral-600 border-b border-white/5">
+ {S.ask.scopeLabel}
+ </div>
+ <div className="u-scroll max-h-60 overflow-y-auto">
+ {kbs.map((k) => (
+ <button
+ key={k.id}
+ onClick={() => {
+ setScopeOpen(false);
+ if (k.id !== kb?.id) setKb(k.id);
+ }}
+ className={`w-full flex items-center gap-2 text-left px-2.5 py-1.5 text-xs ${
+ k.id === kb?.id
+ ? "bg-white/[0.12] text-white"
+ : "text-neutral-300 hover:bg-white/[0.06] hover:text-white"
+ }`}
+ >
+ <span className="flex-1 min-w-0 truncate">{k.name}</span>
+ {k.id === kb?.id && <Check size={12} className="shrink-0 text-neutral-400" />}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ <span className="text-[11px] text-neutral-600 truncate">{S.ask.composerHint}</span>
+ </div>
+ {streaming ? (
+ <button
+ onClick={() => {
+ abortRef.current?.();
+ setStreaming(false);
+ }}
+ title={S.ask.stop}
+ className="h-8 w-8 shrink-0 rounded-lg grid place-items-center bg-white/[0.08] text-neutral-200 hover:bg-white/[0.14] transition-colors"
+ >
+ <Square size={11} fill="currentColor" />
+ </button>
+ ) : (
+ <button
+ onClick={send}
+ disabled={!input.trim()}
+ title={S.ask.send}
+ className={`h-8 w-8 shrink-0 rounded-lg grid place-items-center transition-colors ${
+ input.trim()
+ ? "bg-white text-black hover:bg-neutral-200"
+ : "bg-white/[0.07] text-neutral-600"
+ }`}
+ >
+ <ArrowUp size={15} strokeWidth={2.4} />
+ </button>
+ )}
+ </div>
+ </div>
+ );
+
+ return (
+ <div className="h-full flex">
+ {/* 会话栏 */}
+ <aside className={`${RAIL_CLS} flex flex-col`}>
+ <div className="px-2 pt-3 pb-1">
+ {/* 与会话行同一套样式:左栏是一列同质的行,新对话只是第一行 */}
+ <button
+ onClick={newChat}
+ className="w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-left text-[13px] text-neutral-300 hover:bg-white/[0.05] hover:text-white transition-colors"
+ >
+ <SquarePen size={14} className="shrink-0 text-neutral-500" />
+ {S.ask.newChat}
+ </button>
+ </div>
+ <div className="u-scroll flex-1 overflow-y-auto px-2 pb-3 space-y-0.5">
+ {(convs.data?.conversations ?? []).map((c: ConversationRow) => (
+ <div
+ key={c.id}
+ className={`group relative rounded-lg transition-colors ${
+ c.id === activeId ? "u-nav-active" : "hover:bg-white/[0.05]"
+ }`}
+ >
+ {/* 单行标题;删除键悬停浮现(弹确认,不直接删) */}
+ <button
+ onClick={() => openConversation(c.id)}
+ className="w-full text-left px-2.5 py-2"
+ >
+ <span
+ className={`block truncate pr-5 text-[13px] ${
+ c.id === activeId ? "text-white" : "text-neutral-300"
+ }`}
+ >
+ {c.title || S.ask.untitled}
+ </span>
+ </button>
+ <button
+ onClick={() => setPendingDelete(c)}
+ title={S.ask.deleteConversation}
+ className="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:block text-neutral-600 hover:text-[var(--u-danger)]"
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ ))}
+ {convs.data?.conversations.length === 0 && (
+ <p className="px-2.5 py-2 text-xs text-neutral-600">{S.ask.noConversations}</p>
+ )}
+ </div>
+ </aside>
+
+ {/* 对话区:新对话首屏 = 问候 + 居中 composer(ChatGPT/Claude 惯例);
+ 有消息后 composer 停靠底部 */}
+ <div className="flex-1 min-w-0 flex flex-col">
+ {turns.length === 0 ? (
+ /* 锚定上三分之一而非垂直居中:居中在高窗口下会显得下坠。
+ 22vh + 顶部 chrome(~100px) ≈ 问候落在 37% 高度、composer 中心 ~49% */
+ <div className="flex-1 px-4 pt-[22vh]">
+ <div className="w-full max-w-3xl mx-auto">
+ <h1
+ className="text-center text-[26px] text-neutral-100 mb-9"
+ style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.03em" }}
+ >
+ {S.ask.greeting}
+ </h1>
+ {composerCard}
+ </div>
+ </div>
+ ) : (
+ <>
+ <div className="flex-1 overflow-y-auto u-scroll px-4 py-6">
+ <div className="max-w-3xl mx-auto space-y-4">
+ {turns.map((t, i) => (
+ <TurnView key={i} turn={t} live={streaming && i === turns.length - 1} />
+ ))}
+ <div ref={bottomRef} />
+ </div>
+ </div>
+ <div className="px-4 pb-4 pt-2">
+ <div className="max-w-3xl mx-auto">{composerCard}</div>
+ </div>
+ </>
+ )}
+ </div>
+
+ {pendingDelete && (
+ <DangerConfirm
+ title={S.ask.deleteTitle}
+ hint={S.ask.deleteHint(pendingDelete.title || S.ask.untitled)}
+ confirmLabel={S.ask.deleteBtn}
+ cancelLabel={S.ask.cancel}
+ onConfirm={() => {
+ removeConversation(pendingDelete.id);
+ setPendingDelete(null);
+ }}
+ onCancel={() => setPendingDelete(null)}
+ />
+ )}
+ </div>
+ );
+}
+
+function stepIcon(kind: ChatStep["kind"]) {
+ if (kind === "search") return <SearchIcon size={11} />;
+ if (kind === "docs") return <BookOpen size={11} />;
+ if (kind === "entity") return <Waypoints size={11} />;
+ if (kind === "facts") return <History size={11} />;
+ if (kind === "query") return <Database size={11} />;
+ return <Wrench size={11} />;
+}
+
+/** 工具步骤 → 球体状态:思考球讲当前动作的语言 */
+function orbState(kind?: ChatStep["kind"]): OrbState {
+ if (kind === "search" || kind === "docs") return "searching";
+ if (kind === "entity") return "connecting";
+ if (kind === "facts") return "solving";
+ if (kind === "query" || kind === "tool") return "working";
+ return "listening"; // 尚无步骤:刚接到消息
+}
+
+/** 思考指示:thinking-orbs 球体 + 当前动作(应用是深色定妆,theme 钉死 dark)。 */
+function Thinking({ step }: { step?: ChatStep }) {
+ return (
+ <span className="inline-flex items-center gap-2.5 text-neutral-500">
+ <ThinkingOrb state={orbState(step?.kind)} size={20} theme="dark" />
+ {step && (
+ <span className="text-xs truncate">
+ {step.label} · {step.detail}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {
+ if (turn.role === "user") {
+ return (
+ <div className="flex justify-end">
+ <div className="u-bubble-user max-w-[85%] rounded-2xl rounded-tr-sm px-4 py-2 text-sm whitespace-pre-wrap text-neutral-100">
+ {turn.content}
+ </div>
+ </div>
+ );
+ }
+
+ const thinking = live && !turn.content && !turn.error;
+ const lastStep = turn.steps?.[turn.steps.length - 1];
+
+ return (
+ <div className="max-w-[95%]">
+ {/* agent 回复无气泡:正文直接落在画布上(用户消息保留气泡以区分角色) */}
+ <div className="py-1 text-sm text-neutral-200 leading-relaxed">
+ {turn.steps && turn.steps.length > 0 && (
+ <div className="mb-2.5 space-y-1 border-l border-white/15 pl-2.5">
+ {turn.steps.map((s, i) => (
+ <div key={i} className="flex items-center gap-1.5 text-xs">
+ <span className="text-neutral-600">{stepIcon(s.kind)}</span>
+ <span className="text-neutral-400 truncate">{s.label}</span>
+ <span className="text-neutral-600 shrink-0">· {s.detail}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ {turn.content && (
+ /* react-markdown 承载渲染(皮肤全归 u-chat-prose 设计系统),
+ 流式中经 remend 修补未闭合语法(粗体/围栏/链接),
+ rehype-highlight 做代码高亮——成熟件组装,观感自持 */
+ <div className="u-chat-prose">
+ <Markdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
+ {live ? remend(turn.content) : turn.content}
+ </Markdown>
+ </div>
+ )}
+ {thinking && <Thinking step={lastStep} />}
+ {turn.error && <div className="text-rose-400">{turn.error}</div>}
+ </div>
+ {turn.sources && turn.sources.length > 0 && (
+ <div className="mt-2 space-y-1">
+ {turn.sources.map((s) =>
+ s.kind === "charter" ? (
+ /* 手册引用:视觉上与数据引用隔离(BookOpen),跳排版好的 /docs 小节 */
+ <Link
+ key={s.n}
+ to="/docs/$slug"
+ params={{ slug: s.slug! }}
+ hash={s.anchor || undefined}
+ title={s.excerpt}
+ className="flex items-center gap-1.5 text-xs text-neutral-500 glass rounded-lg px-3 py-1.5 glass-hover hover:text-neutral-300"
+ >
+ <span className="u-num text-[var(--u-accent)]">[{s.n}]</span>
+ <BookOpen size={11} className="shrink-0 text-neutral-600" />
+ <span className="truncate">
+ {/* 引言节 heading 即文章名,避免 "X › X" */}
+ {s.heading && s.heading !== s.filename
+ ? `${s.filename} › ${s.heading}`
+ : s.filename}
+ </span>
+ </Link>
+ ) : (
+ <Link
+ key={s.n}
+ to="/doc/$docId"
+ params={{ docId: s.document_id! }}
+ search={{ chunk: s.chunk_id }}
+ title={s.excerpt}
+ className="block text-xs text-neutral-500 glass rounded-lg px-3 py-1.5 glass-hover hover:text-neutral-300"
+ >
+ <span className="u-num text-[var(--u-accent)]">[{s.n}]</span> {s.filename} ·{" "}
+ {s.excerpt.slice(0, 60)}…
+ </Link>
+ ),
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/pages/DocViewer.tsx b/web/src/pages/DocViewer.tsx
new file mode 100644
index 00000000..2a5b4093
--- /dev/null
+++ b/web/src/pages/DocViewer.tsx
@@ -0,0 +1,169 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
+import { api, type ChunkFact } from "../api";
+import { S } from "../i18n";
+import { Pager, pageSlice } from "../ui";
+import { SourcesRail } from "./SourcesRail";
+
+const DOC_PAGE = 12;
+
+const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
+
+function factRange(f: ChunkFact): string | null {
+ if (!f.valid_from && !f.valid_to) return null;
+ return `${ym(f.valid_from) ?? "…"} → ${ym(f.valid_to) ?? S.doc.ongoing}`;
+}
+
+export function DocViewer() {
+ const { docId } = useParams({ from: "/app/doc/$docId" });
+ const { chunk } = useSearch({ from: "/app/doc/$docId" });
+ const navigate = useNavigate();
+
+ const detail = useQuery({
+ queryKey: ["docDetail", docId],
+ queryFn: () => api.documentDetail(docId),
+ });
+ // 反向证据链:各分块抽出的事实(一次取整文档,按 chunk 分组)
+ const extractions = useQuery({
+ queryKey: ["docExtractions", docId],
+ queryFn: () => api.documentExtractions(docId),
+ });
+ const factsByChunk = useMemo(() => {
+ const map = new Map<string, ChunkFact[]>();
+ for (const f of extractions.data?.facts ?? []) {
+ if (!map.has(f.chunk_id)) map.set(f.chunk_id, []);
+ map.get(f.chunk_id)!.push(f);
+ }
+ return map;
+ }, [extractions.data]);
+
+ // null = 自动定位:有引用跳转时翻到目标分块所在页
+ const [page, setPage] = useState<number | null>(null);
+ useEffect(() => setPage(null), [chunk, docId]);
+
+ const highlightRef = useRef<HTMLDivElement>(null);
+ // 引用跳转:滚动到目标分块点亮一下,稍候淡出恢复普通状态(不常驻高亮)
+ const [flash, setFlash] = useState(false);
+ useEffect(() => {
+ if (detail.data && highlightRef.current) {
+ highlightRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
+ setFlash(true);
+ // 平滑滚动本身耗几百毫秒,点亮窗口要留足滚动后的可视时间
+ const t = setTimeout(() => setFlash(false), 2600);
+ return () => clearTimeout(t);
+ }
+ }, [detail.data, chunk]);
+
+ if (detail.isPending)
+ return <div className="p-8 text-sm text-neutral-500">{S.doc.loading}</div>;
+ if (detail.isError)
+ return (
+ <div className="p-8 text-sm text-rose-400">
+ {(detail.error as Error).message}
+ </div>
+ );
+
+ const { document: doc, chunks } = detail.data;
+ const targetIdx = chunk ? chunks.findIndex((c) => c.id === chunk) : -1;
+ const curPage = page ?? (targetIdx >= 0 ? Math.floor(targetIdx / DOC_PAGE) : 0);
+ const { rows: pagedChunks, safe: safePage } = pageSlice(chunks, curPage, DOC_PAGE);
+
+ return (
+ <div className="h-full flex">
+ {/* 来源栏常驻:当前文档所属文件夹高亮,点其他文件夹跳回 Library 对应视图 */}
+ <SourcesRail
+ kbId={doc.kb_id}
+ active={doc.source_id ?? "uploads"}
+ onSelect={(sel) => navigate({ to: "/library", search: { src: sel } })}
+ />
+ <div className="flex-1 min-w-0 overflow-y-auto u-scroll">
+ <div className="max-w-4xl mx-auto p-6">
+ <div className="mb-4 flex items-baseline justify-between gap-4">
+ <div>
+ <h2 className="text-lg font-bold text-neutral-100 break-all">{doc.filename}</h2>
+ <p className="mt-0.5 text-xs text-neutral-500">
+ {chunks.length} {S.doc.sections} · {(doc.size_bytes / 1024).toFixed(0)} KB ·{" "}
+ {new Date(doc.created_at).toLocaleDateString()}
+ </p>
+ </div>
+ <Link to="/library" className="shrink-0 text-sm text-[var(--u-accent)] hover:underline">
+ {S.doc.backToLibrary}
+ </Link>
+ </div>
+
+ <div className="space-y-3">
+ {pagedChunks.map((c) => {
+ const hit = c.id === chunk;
+ const facts = factsByChunk.get(c.id) ?? [];
+ return (
+ <div key={c.id} ref={hit ? highlightRef : undefined} className="flex gap-3">
+ <div
+ className={`flex-1 min-w-0 rounded-xl border p-4 text-sm leading-relaxed whitespace-pre-wrap border-white/10 transition-[border-color,background-color,box-shadow] duration-700 ${
+ hit && flash ? "u-flash" : "bg-white/[0.04]"
+ }`}
+ >
+ <div className="mb-1.5 text-xs text-neutral-500">
+ {S.doc.section} {c.seq + 1}
+ {hit && (
+ <span
+ className={`ml-2 text-[var(--u-accent)] transition-opacity duration-700 ${
+ flash ? "opacity-100" : "opacity-0"
+ }`}
+ >
+ {S.doc.citedHere}
+ </span>
+ )}
+ </div>
+ {c.text}
+ </div>
+
+ {/* 抽取对照栏:这个分块产出了哪些事实(实体可跳图谱) */}
+ {facts.length > 0 && (
+ <aside className="w-64 shrink-0 rounded-xl border border-white/10 bg-white/[0.02] p-3">
+ <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600">
+ {S.doc.extracted} · {facts.length}
+ </div>
+ <div className="space-y-2">
+ {facts.map((f) => {
+ const range = factRange(f);
+ return (
+ <div key={f.fact_id} className="text-xs leading-snug">
+ <div>
+ <Link
+ to="/graph"
+ search={{ entity: f.subject_id }}
+ className="text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
+ >
+ {f.subject}
+ </Link>
+ <span className="text-neutral-600"> {f.predicate} </span>
+ {f.object_id ? (
+ <Link
+ to="/graph"
+ search={{ entity: f.object_id }}
+ className="text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
+ >
+ {f.object}
+ </Link>
+ ) : (
+ <span className="text-neutral-300">{f.object ?? ""}</span>
+ )}
+ </div>
+ {range && <div className="u-num text-[10.5px] text-neutral-500">{range}</div>}
+ </div>
+ );
+ })}
+ </div>
+ </aside>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ <Pager total={chunks.length} pageSize={DOC_PAGE} page={safePage} onPage={setPage} />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/Docs.tsx b/web/src/pages/Docs.tsx
new file mode 100644
index 00000000..beaa706e
--- /dev/null
+++ b/web/src/pages/Docs.tsx
@@ -0,0 +1,341 @@
+/* 内置文档:随应用打包(私有部署离线可用),版本与部署一致。
+ 公开路由——不依赖会话,登录前也可读(开发者接接口时未必有账号)。 */
+import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { Link, useNavigate, useParams } from "@tanstack/react-router";
+import { Command, Search } from "lucide-react";
+import { api } from "../api";
+import { S } from "../i18n";
+import { GithubMark, SectionMark } from "../ui";
+import { UserMenu } from "./UserMenu";
+import { usePageTitle } from "../useTitle";
+import ingestMd from "../docs/ingest.md?raw";
+
+/** 文档清单:slug → 标题 + 内容(构建期打进 bundle) */
+const DOCS: { slug: string; title: string; body: string }[] = [
+ { slug: "ingest", title: "Ingest interfaces", body: ingestMd },
+];
+
+/** 全文检索(客户端,文档已在 bundle 里):命中行 → 文档 + 以命中词为中心的摘录 */
+function searchDocs(q: string): { slug: string; title: string; snippet: string }[] {
+ const needle = q.trim().toLowerCase();
+ if (needle.length < 2) return [];
+ const hits: { slug: string; title: string; snippet: string }[] = [];
+ for (const d of DOCS) {
+ for (const line of d.body.split("\n")) {
+ const cleaned = line.replace(/[#`*|>-]/g, " ").replace(/\s+/g, " ").trim();
+ const idx = cleaned.toLowerCase().indexOf(needle);
+ if (idx < 0) continue;
+ // 摘录窗口以命中词为中心,避免命中被 90 字截断截丢
+ const start = Math.max(0, idx - 30);
+ const snippet = (start > 0 ? "…" : "") + cleaned.slice(start, start + 100);
+ hits.push({ slug: d.slug, title: d.title, snippet });
+ if (hits.length >= 8) return hits;
+ }
+ }
+ return hits;
+}
+
+/** 摘录内高亮命中词(不区分大小写,全部命中都标) */
+function Highlighted({ text, q }: { text: string; q: string }) {
+ const needle = q.trim();
+ if (!needle) return <>{text}</>;
+ const parts = text.split(new RegExp(`(${needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "ig"));
+ return (
+ <>
+ {parts.map((p, i) =>
+ p.toLowerCase() === needle.toLowerCase() ? (
+ /* 命中词用警示琥珀:结果列表里一眼定位到匹配处 */
+ <mark
+ key={i}
+ className="rounded-[3px] bg-[rgba(242,182,109,0.16)] px-0.5 text-[var(--u-warn)]"
+ >
+ {p}
+ </mark>
+ ) : (
+ <span key={i}>{p}</span>
+ ),
+ )}
+ </>
+ );
+}
+
+/** 标题 → 锚点 id(TOC 与正文用同一函数保证对得上) */
+function slugify(s: string): string {
+ return s
+ .toLowerCase()
+ .replace(/[^a-z0-9一-龥]+/g, "-")
+ .replace(/(^-+|-+$)/g, "");
+}
+
+/** React children → 纯文本(h2/h3 里可能嵌 code/strong) */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function textOf(children: any): string {
+ if (typeof children === "string") return children;
+ if (Array.isArray(children)) return children.map(textOf).join("");
+ if (children && typeof children === "object" && "props" in children)
+ return textOf(children.props.children);
+ return "";
+}
+
+/** 从 markdown 源提取 h2/h3 目录 */
+function tocOf(body: string): { id: string; text: string; level: 2 | 3 }[] {
+ const out: { id: string; text: string; level: 2 | 3 }[] = [];
+ for (const line of body.split("\n")) {
+ const m = /^(#{2,3})\s+(.+)$/.exec(line);
+ if (!m) continue;
+ const text = m[2].replace(/[`*]/g, "").trim();
+ out.push({ id: slugify(text), text, level: m[1].length as 2 | 3 });
+ }
+ return out;
+}
+
+const IS_MAC = navigator.platform.toUpperCase().includes("MAC");
+
+export function DocsPage() {
+ const { slug } = useParams({ from: "/docs/$slug" });
+ const doc = DOCS.find((d) => d.slug === slug) ?? DOCS[0];
+ const navigate = useNavigate();
+ const [q, setQ] = useState("");
+ const searchRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const results = searchDocs(q);
+ const toc = tocOf(doc.body);
+ const mainRef = useRef<HTMLElement>(null);
+ const [activeHeading, setActiveHeading] = useState<string | null>(null);
+ // 标题:`Utopia | {文章名}`——Charter 是门脸字标,标题直接给文章
+ usePageTitle(S.app.name, doc.title);
+ // 公开页也感知登录态:已登录给用户菜单,未登录给 Sign in
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me, retry: false });
+ const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });
+
+ // 滚动跟随:视口上沿之上最近的标题为当前小节;
+ // 滚到底强制激活最后一节(短末节永远越不过判定线)
+ const onScrollSpy = () => {
+ const main = mainRef.current;
+ if (!main) return;
+ const top = main.getBoundingClientRect().top;
+ let current: string | null = null;
+ for (const h of toc) {
+ const el = document.getElementById(h.id);
+ if (el && el.getBoundingClientRect().top - top <= 96) current = h.id;
+ }
+ if (main.scrollTop + main.clientHeight >= main.scrollHeight - 8 && toc.length)
+ current = toc[toc.length - 1].id;
+ setActiveHeading(current);
+ };
+
+ useEffect(() => {
+ if (!q) return;
+ const onDown = (e: MouseEvent) => {
+ if (searchRef.current && !searchRef.current.contains(e.target as Node)) setQ("");
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setQ("");
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [q]);
+
+ // 键盘呼起:⌘K / Ctrl+K 任何时候生效;`/` 仅在焦点不在输入框时(别劫持打字)
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const el = document.activeElement;
+ const typing =
+ el instanceof HTMLInputElement ||
+ el instanceof HTMLTextAreaElement ||
+ (el instanceof HTMLElement && el.isContentEditable);
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
+ e.preventDefault();
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ } else if (e.key === "/" && !typing) {
+ e.preventDefault();
+ inputRef.current?.focus();
+ } else if (e.key === "Escape" && el === inputRef.current) {
+ inputRef.current?.blur();
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, []);
+
+ return (
+ <div className="h-screen flex flex-col overflow-hidden">
+ <header className="glass-strong relative z-40 border-x-0 border-t-0 h-14 shrink-0 flex items-center px-5">
+ <SectionMark text={S.docs.brand} title={S.docs.backTitle} />
+ {/* 居中搜索:检索打包在本地的全部文档;宽度对齐正文栏(max-w-3xl 去掉 px-8) */}
+ <div
+ ref={searchRef}
+ className="absolute left-1/2 -translate-x-1/2 w-[min(44rem,55vw)]"
+ >
+ <div className="relative">
+ <Search
+ size={13}
+ className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
+ />
+ <input
+ ref={inputRef}
+ className="input-dark w-full pr-14 py-1.5 text-[13px]"
+ style={{ paddingLeft: "2.1rem" }}
+ placeholder={S.docs.searchPlaceholder}
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ />
+ {/* 快捷键提示:输入中不占视线。⌘ 用 lucide 图标;
+ Ctrl 无图形符号(⌘ 是 Mac 专属键符),Windows 规范写法就是文字 */}
+ {!q && (
+ <kbd className="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1 rounded border border-white/10 bg-white/[0.04] px-1.5 py-0.5 font-sans text-[10px] text-neutral-600">
+ {IS_MAC ? <Command size={9} /> : <span>Ctrl</span>}
+ <span>K</span>
+ </kbd>
+ )}
+ </div>
+ {q.trim().length >= 2 && (
+ <div className="u-pop u-pop-in u-pop-in-tl absolute inset-x-0 top-full mt-2 rounded-xl shadow-2xl overflow-hidden">
+ {results.length === 0 ? (
+ <p className="px-3.5 py-3 text-xs text-neutral-500">{S.docs.noResults}</p>
+ ) : (
+ results.map((r, i) => (
+ <button
+ key={i}
+ onClick={() => {
+ setQ("");
+ navigate({ to: "/docs/$slug", params: { slug: r.slug } });
+ }}
+ className="w-full text-left px-3.5 py-2.5 hover:bg-white/[0.06] border-b border-white/5 last:border-0"
+ >
+ <div className="text-[11px] text-neutral-500">{r.title}</div>
+ <div className="text-[13px] text-neutral-200 truncate">
+ <Highlighted text={r.snippet} q={q} />
+ </div>
+ </button>
+ ))
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* 右侧:显式返回(与字标双路回城)+ GitHub·版本胶囊 + 登录态 */}
+ <div className="ml-auto flex items-center gap-1.5">
+ <Link
+ to="/graph"
+ className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
+ >
+ {S.account.backToApp}
+ </Link>
+ <a
+ href={S.login.githubUrl}
+ target="_blank"
+ rel="noreferrer"
+ title="GitHub"
+ className="flex items-center gap-1.5 rounded-full border border-white/10 px-2.5 py-1 text-neutral-500 hover:text-neutral-200 hover:border-white/25 transition-colors"
+ >
+ <GithubMark size={13} />
+ {health.data && <span className="u-num text-[11px]">v{health.data.version}</span>}
+ </a>
+ {me.data ? (
+ <div className="ml-1">
+ <UserMenu user={me.data} />
+ </div>
+ ) : me.isError ? (
+ <Link
+ to="/login"
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ >
+ {S.login.signIn}
+ </Link>
+ ) : null}
+ </div>
+ </header>
+
+ {/* 整页滚动(滚动条贴窗口最右),侧栏 sticky 钉住——正规文档站布局 */}
+ <main
+ ref={mainRef}
+ onScroll={onScrollSpy}
+ className="flex-1 min-h-0 overflow-y-auto u-scroll"
+ >
+ <div className="flex items-start">
+ <aside className="w-64 shrink-0 sticky top-0 h-[calc(100vh-3.5rem)] glass-strong border-y-0 border-l-0 p-3 space-y-0.5">
+ {DOCS.map((d) => (
+ <Link
+ key={d.slug}
+ to="/docs/$slug"
+ params={{ slug: d.slug }}
+ className={`block rounded-lg px-3 py-2 text-[13px] ${
+ d.slug === doc.slug
+ ? "u-nav-active"
+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200"
+ }`}
+ >
+ {d.title}
+ </Link>
+ ))}
+ </aside>
+
+ {/* 上下都留足空白:标题不顶着头,末段内容能滚到屏幕中部——人读屏幕中间。
+ 排版交给官方 @tailwindcss/typography(prose,16px 基准),
+ 自定义只剩:标题锚点 id、外链新开、表格横向滚动容器 */}
+ {/* prose-neutral:默认 gray 阶带蓝相(oklch 258°),违反 chrome 零色偏 */}
+ <article className="prose prose-neutral prose-invert prose-headings:scroll-mt-6 prose-code:before:content-none prose-code:after:content-none flex-1 min-w-0 max-w-3xl mx-auto px-8 pt-16 pb-[40vh]">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={{
+ h2: ({ children, ...p }) => (
+ <h2 id={slugify(textOf(children))} {...p}>
+ {children}
+ </h2>
+ ),
+ h3: ({ children, ...p }) => (
+ <h3 id={slugify(textOf(children))} {...p}>
+ {children}
+ </h3>
+ ),
+ a: (p) => <a target="_blank" rel="noreferrer" {...p} />,
+ // 不加 u-scroll:overscroll-contain 会把竖向滚轮困在块内,页面滚不动
+ table: (p) => (
+ <div className="overflow-x-auto">
+ <table {...p} />
+ </div>
+ ),
+ }}
+ >
+ {doc.body}
+ </ReactMarkdown>
+ </article>
+
+ {/* 右侧目录:sticky 钉住,与正文标题同一水平线起头 */}
+ {toc.length > 0 && (
+ <aside className="hidden lg:block w-64 shrink-0 sticky top-0 pt-16 pr-8">
+ <nav className="space-y-0.5">
+ {toc.map((h) => (
+ <button
+ key={h.id}
+ onClick={() =>
+ document.getElementById(h.id)?.scrollIntoView({ behavior: "smooth" })
+ }
+ className={`block w-full text-left px-2 py-1.5 text-sm leading-snug transition-colors ${
+ h.level === 3 ? "pl-5" : ""
+ } ${
+ activeHeading === h.id
+ ? "text-white"
+ : "text-neutral-500 hover:text-neutral-300"
+ }`}
+ >
+ {h.text}
+ </button>
+ ))}
+ </nav>
+ </aside>
+ )}
+ </div>
+ </main>
+ </div>
+ );
+}
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
new file mode 100644
index 00000000..92d37583
--- /dev/null
+++ b/web/src/pages/Graph.tsx
@@ -0,0 +1,1570 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Link, useSearch } from "@tanstack/react-router";
+import Graphology from "graphology";
+import { circular, circlepack } from "graphology-layout";
+import forceAtlas2 from "graphology-layout-forceatlas2";
+import FA2Layout from "graphology-layout-forceatlas2/worker";
+import Sigma from "sigma";
+import { createNodeBorderProgram } from "@sigma/node-border";
+import { NodeSquareShellProgram } from "./squareShellProgram";
+import {
+ ArrowLeft,
+ ArrowRight,
+ ChevronRight,
+ CircleDashed,
+ Grape,
+ Maximize2,
+ Orbit,
+ Pause,
+ Play,
+ X,
+ ZoomIn,
+ ZoomOut,
+} from "lucide-react";
+import { api, type EntityFact, type Evidence, type GraphEdge, type GraphNode } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+
+/* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化:
+ Semantica 原版是钢蓝系(#0B1320/#5A7A9E/#7A92AE),按"chrome 零色偏、
+ 彩色只属于数据"的既定原则换成同明度纯灰,类型色混入比例不变 */
+const NODE_SHELL_BASE = "#121212"; // 节点外壳深底(原 #0B1320 的中性化)
+const NODE_CORE_BASE = "#767676"; // 节点核心灰(原 #5A7A9E 的中性化)
+const NODE_BORDER_BASE = "#909090"; // 节点描边(原 #7A92AE 的中性化)
+const NODE_TINT_MIX = 0.14; // 类型色只按 14% 混入外壳(高级感的关键)
+const NODE_CORE_MIX = 0.5; // 核心向类型色的混入比例
+const RING_SELECTED = "#E7C57C"; // 选中金环
+const RING_HOVERED = "#8FE7FF"; // 悬停冰青环
+const EDGE_COLOR = "rgba(163,163,163,0.2)"; // 纯灰(应用户要求,不用钢蓝)
+// 注意:sigma 边着色器在预乘混合(ONE, ONE_MINUS_SRC_ALPHA)下不预乘 RGB,
+// alpha 无法压暗边——暗度必须编码进 RGB(不透明近背景色)
+const EDGE_DIM = "#141414";
+const EDGE_FOCUS = "rgba(255,255,255,0.55)";
+const MUTED_SHELL = "#151515";
+const PILL_BG = "rgba(12,12,12,0.9)";
+const PILL_BORDER = "rgba(255,255,255,0.14)";
+const PILL_TEXT = "#ededed";
+const TRANSPARENT = "rgba(0,0,0,0)";
+const DAY_MS = 24 * 3600 * 1000;
+const MONTH_MS = 30 * DAY_MS;
+
+function hexToRgb(hex: string): [number, number, number] {
+ const m = /^#?([0-9a-f]{6})$/i.exec(hex);
+ if (!m) return [128, 128, 128];
+ const v = parseInt(m[1], 16);
+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
+}
+
+/** c1 向 c2 按 t 比例混色 */
+function mix(c1: string, c2: string, t: number): string {
+ const [r1, g1, b1] = hexToRgb(c1);
+ const [r2, g2, b2] = hexToRgb(c2);
+ const f = (a: number, b: number) => Math.round(a + (b - a) * t);
+ return `rgb(${f(r1, r2)},${f(g1, g2)},${f(b1, b2)})`;
+}
+
+/* 播放淡入:解析 hex / rgb / rgba(含 alpha)并线性插值 */
+function parseRgba(c: string): [number, number, number, number] {
+ if (c.startsWith("#")) {
+ const [r, g, b] = hexToRgb(c);
+ return [r, g, b, 1];
+ }
+ const m = c.match(/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?/);
+ if (!m) return [128, 128, 128, 1];
+ return [+m[1], +m[2], +m[3], m[4] !== undefined ? +m[4] : 1];
+}
+function lerpColor(from: string, to: string, t: number): string {
+ const a = parseRgba(from);
+ const b = parseRgba(to);
+ const f = (i: number) => a[i] + (b[i] - a[i]) * t;
+ return `rgba(${Math.round(f(0))},${Math.round(f(1))},${Math.round(f(2))},${f(3).toFixed(3)})`;
+}
+/** 播放中新元素的淡入时长 */
+const FADE_MS = 320;
+
+/* 世界坐标网格:随相机平移/缩放(Figma/tldraw 式无限画布惯例)。
+ 4 倍细分 LOD:每层 alpha 随其屏幕间距连续淡入(13px 进场 → 52px 满亮 5.5%),
+ 粗层与细层线重合处自然叠亮,形成"大小格"层次;无任何跳变。 */
+const GRID_BASE_WORLD = 24; // 基准世界格距(匹配 ~300 尺度的布局)
+const GRID_FADE_IN_PX = 13;
+const GRID_FULL_PX = 52;
+const GRID_MAX_LEVEL_PX = 480;
+const GRID_MAX_ALPHA = 0.055;
+
+function drawWorldGrid(canvas: HTMLCanvasElement, sigma: Sigma): void {
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ const { width, height } = sigma.getDimensions();
+ const dpr = window.devicePixelRatio || 1;
+ const pw = Math.round(width * dpr);
+ const ph = Math.round(height * dpr);
+ if (canvas.width !== pw || canvas.height !== ph) {
+ canvas.width = pw;
+ canvas.height = ph;
+ }
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, width, height);
+ if (width <= 0 || height <= 0) return;
+
+ // 世界→屏幕:两个探针点求每世界单位像素数与原点位置(无相机旋转场景)
+ const p0 = sigma.graphToViewport({ x: 0, y: 0 });
+ const p1 = sigma.graphToViewport({ x: 1, y: 0 });
+ const ppw = p1.x - p0.x;
+ if (!Number.isFinite(ppw) || ppw <= 0) return;
+
+ // 最细可见层级:屏幕间距 ≥ 淡入阈值的最小 4 幂格距
+ let spacing = GRID_BASE_WORLD;
+ while (spacing * ppw < GRID_FADE_IN_PX) spacing *= 4;
+ while (spacing * ppw >= GRID_FADE_IN_PX * 4) spacing /= 4;
+
+ for (let sp = spacing; sp * ppw < GRID_MAX_LEVEL_PX; sp *= 4) {
+ const ss = sp * ppw;
+ const t = Math.min(1, (ss - GRID_FADE_IN_PX) / (GRID_FULL_PX - GRID_FADE_IN_PX));
+ if (t <= 0) continue;
+ ctx.strokeStyle = `rgba(255,255,255,${(GRID_MAX_ALPHA * t).toFixed(4)})`;
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ const startX = ((p0.x % ss) + ss) % ss;
+ for (let x = startX; x <= width; x += ss) {
+ const px = Math.round(x) + 0.5;
+ ctx.moveTo(px, 0);
+ ctx.lineTo(px, height);
+ }
+ const startY = ((p0.y % ss) + ss) % ss;
+ for (let y = startY; y <= height; y += ss) {
+ const py = Math.round(y) + 0.5;
+ ctx.moveTo(0, py);
+ ctx.lineTo(width, py);
+ }
+ ctx.stroke();
+ }
+}
+
+/* 胶囊标签:深色圆角底 + 柔和文字(学 Semantica 的浮签风格) */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function drawPillLabel(ctx: CanvasRenderingContext2D, data: any, settings: any): void {
+ if (!data.label) return;
+ // hover 时悬浮卡(drawHoverCard)接管展示,底层 pill 隐去,避免双层标签
+ if (data.hideBaseLabel) return;
+ // Semantica chip: fontSize=clamp(10, size*0.25, 11), pad 6/3, radius 6, 位于节点上方,投影 blur 12
+ const size = Math.max(10, Math.min(11, data.size * 0.25));
+ ctx.font = `500 ${size}px Geist, Inter, "Noto Sans SC", sans-serif`;
+ ctx.textBaseline = "middle";
+ const padX = 6;
+ const padY = 3;
+ const w = ctx.measureText(data.label).width + padX * 2;
+ const h = size + padY * 2;
+ const x = data.x + Math.max(data.size * 0.7, 12);
+ const y = data.y - Math.max(data.size * 0.9, 10) - h;
+ ctx.save();
+ ctx.shadowColor = "rgba(0,0,0,0.6)";
+ ctx.shadowBlur = 12;
+ ctx.beginPath();
+ ctx.roundRect(x, y, w, h, 6);
+ ctx.fillStyle = PILL_BG;
+ ctx.fill();
+ ctx.shadowBlur = 0;
+ ctx.strokeStyle = PILL_BORDER;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ ctx.fillStyle = PILL_TEXT;
+ ctx.fillText(data.label, x + padX, y + h / 2);
+ ctx.restore();
+}
+
+/* Hover 悬浮卡(Semantica hoverCard 规格):径向柔光 + 名称 + 类型行 */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function drawHoverCard(ctx: CanvasRenderingContext2D, data: any, _settings: any): void {
+ if (!data.label) return;
+ ctx.save();
+
+ // 柔光: 半径 max(size*4.8, 16), 类型色 alpha 0.18 → 0
+ const glowR = Math.max(data.size * 4.8, 16);
+ const [r, g, b] = hexToRgb((data.typeColor as string) ?? "#888888");
+ const grad = ctx.createRadialGradient(data.x, data.y, 0, data.x, data.y, glowR);
+ grad.addColorStop(0, `rgba(${r},${g},${b},0.18)`);
+ grad.addColorStop(1, `rgba(${r},${g},${b},0)`);
+ ctx.fillStyle = grad;
+ ctx.beginPath();
+ ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2);
+ ctx.fill();
+
+ // 卡片: 标题 700/13 + 类型行 500/10 大写
+ const titleSize = 13;
+ const metaSize = 10;
+ const padX = 10;
+ const padY = 7;
+ const metaGap = 5;
+ const meta = String(data.typeLabel ?? "NODE").toUpperCase();
+ ctx.textBaseline = "top";
+ ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;
+ const titleW = ctx.measureText(data.label).width;
+ ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;
+ const metaW = ctx.measureText(meta).width;
+ const w = Math.max(titleW, metaW) + padX * 2;
+ const h = padY * 2 + titleSize + metaGap + metaSize;
+ const x = data.x + Math.max(data.size * 0.9, 16);
+ const y = data.y - Math.max(data.size * 1.1, 16) - h;
+
+ ctx.shadowColor = "rgba(0,0,0,0.62)";
+ ctx.shadowBlur = 15;
+ ctx.beginPath();
+ ctx.roundRect(x, y, w, h, 8);
+ ctx.fillStyle = "rgba(12,12,12,0.94)";
+ ctx.fill();
+ ctx.shadowBlur = 0;
+ ctx.strokeStyle = "rgba(255,255,255,0.16)";
+ ctx.lineWidth = 1;
+ ctx.stroke();
+
+ ctx.fillStyle = "#f5f5f5";
+ ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;
+ ctx.fillText(data.label, x + padX, y + padY);
+ ctx.fillStyle = "rgba(255,255,255,0.5)";
+ ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;
+ ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap);
+ ctx.restore();
+}
+
+export function Graph() {
+ const { kb } = useKb();
+ // 深链入口:/graph?entity=… 直接聚焦并选中该实体(证据两跳可达的反向路径)
+ const { entity: entityParam } = useSearch({ from: "/app/graph" });
+ const [focusEntity, setFocusEntity] = useState<string | null>(entityParam ?? null);
+ const [selected, setSelected] = useState<string | null>(entityParam ?? null);
+ const [searchInput, setSearchInput] = useState("");
+ const [searchQ, setSearchQ] = useState("");
+ const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set());
+ /** null = 全时段;数值 = as-of 时刻(ms)。
+ 默认 as-of 今天:时态平台的图谱默认呈现"现在的世界",
+ 已闭合的事实不该与现行事实无差别并列(All time 是显式选择) */
+ const [timeT, setTimeT] = useState<number | null>(() => Date.now());
+ const [activeCount, setActiveCount] = useState(0);
+ const [stabilizing, setStabilizing] = useState(false);
+ /* 播放态提升到此层:reducer 需区分"播放推进"(淡入)与"手动拖动"(瞬切) */
+ const [playing, setPlaying] = useState(false);
+ /* 布局模式:force = FA2 斥力;circular = 圆环;pack = 按类型圆填充聚簇 */
+ type LayoutMode = "force" | "circular" | "pack";
+ const [layoutMode, setLayoutMode] = useState<LayoutMode>("force");
+ const layoutModeRef = useRef<LayoutMode>("force");
+ const layoutCtlRef = useRef<{ apply: (m: LayoutMode) => void } | null>(null);
+
+ const data = useQuery({
+ queryKey: ["graph", kb?.id, focusEntity],
+ queryFn: () =>
+ focusEntity ? api.graphNeighborhood(kb!.id, focusEntity) : api.graphOverview(kb!.id),
+ enabled: !!kb,
+ });
+
+ // 全图模式走全库实体搜索;子图模式只在已加载的子图内客户端过滤
+ const inSubgraph = !!focusEntity;
+ const candidates = useQuery({
+ queryKey: ["entitySearch", kb?.id, searchQ],
+ queryFn: () => api.searchEntities(kb!.id, searchQ),
+ enabled: !!kb && searchQ.length > 0 && !inSubgraph,
+ });
+ const subgraphHits = useMemo(() => {
+ if (!inSubgraph || !searchQ || !data.data) return [];
+ const q = searchQ.toLowerCase();
+ return data.data.nodes
+ .filter(
+ (n) =>
+ n.name.toLowerCase().includes(q) ||
+ n.disambiguator?.toLowerCase().includes(q),
+ )
+ .slice(0, 10);
+ }, [inSubgraph, searchQ, data.data]);
+ const searchHits = inSubgraph ? subgraphHits : (candidates.data?.entities ?? []);
+
+ const containerRef = useRef<HTMLDivElement>(null);
+ const gridRef = useRef<HTMLCanvasElement>(null);
+ const sigmaRef = useRef<Sigma | null>(null);
+ /* 焦点 = hover 优先于选中;样式在 reducer 里统一处理 */
+ const selectedRef = useRef<string | null>(null);
+ const hoverRef = useRef<string | null>(null);
+ const filterRef = useRef<{
+ hiddenTypes: Set<string>;
+ activeNodes: Set<string> | null;
+ activeEdges: Set<string> | null;
+ }>({ hiddenTypes: new Set(), activeNodes: null, activeEdges: null });
+ const playingRef = useRef(false);
+ /* 播放淡入表:本轮新激活的节点/边 id → 激活时刻(rAF 循环驱动至到位) */
+ const fadeRef = useRef<Map<string, number>>(new Map());
+ const fadeRafRef = useRef(0);
+
+ const kickFade = useCallback(() => {
+ if (fadeRafRef.current) return;
+ const step = () => {
+ const now = performance.now();
+ for (const [id, start] of fadeRef.current)
+ if (now - start >= FADE_MS) fadeRef.current.delete(id);
+ sigmaRef.current?.refresh();
+ fadeRafRef.current = fadeRef.current.size ? requestAnimationFrame(step) : 0;
+ };
+ fadeRafRef.current = requestAnimationFrame(step);
+ }, []);
+
+ useEffect(() => {
+ playingRef.current = playing;
+ if (!playing) {
+ // 停止播放:未完成的淡入直接到位
+ fadeRef.current.clear();
+ sigmaRef.current?.refresh();
+ }
+ }, [playing]);
+
+ useEffect(() => () => cancelAnimationFrame(fadeRafRef.current), []);
+
+ const types = useMemo(() => {
+ const map = new Map<string, { label: string; color: string; shape: string }>();
+ for (const n of data.data?.nodes ?? []) {
+ if (!map.has(n.type_key))
+ map.set(n.type_key, { label: n.type_label, color: n.color, shape: n.shape });
+ }
+ return [...map.entries()];
+ }, [data.data]);
+
+ /* 时间过滤:计算 T 时刻的活跃边/节点集合 */
+ const recomputeActive = useCallback(
+ (t: number | null) => {
+ const d = data.data;
+ if (!d) return;
+ if (t === null) {
+ filterRef.current.activeNodes = null;
+ filterRef.current.activeEdges = null;
+ setActiveCount(d.edges.length);
+ } else {
+ const prevNodes = filterRef.current.activeNodes;
+ const prevEdges = filterRef.current.activeEdges;
+ const edges = new Set<string>();
+ const nodes = new Set<string>();
+ const touched = new Set<string>();
+ for (const e of d.edges) {
+ const vf = e.valid_from ? Date.parse(e.valid_from) : null;
+ const vt = e.valid_to ? Date.parse(e.valid_to) : null;
+ touched.add(e.source);
+ touched.add(e.target);
+ const active = vf === null ? true : vf <= t && (vt === null || vt > t);
+ if (active) {
+ edges.add(e.id);
+ nodes.add(e.source);
+ nodes.add(e.target);
+ }
+ }
+ // 没有任何边的孤立节点保持可见
+ for (const n of d.nodes) if (!touched.has(n.id)) nodes.add(n.id);
+ // 播放推进时新出现的元素淡入登场;手动拖动保持瞬时切换
+ if (playingRef.current) {
+ const now = performance.now();
+ for (const id of edges) if (prevEdges && !prevEdges.has(id)) fadeRef.current.set(id, now);
+ for (const id of nodes) if (prevNodes && !prevNodes.has(id)) fadeRef.current.set(id, now);
+ if (fadeRef.current.size) kickFade();
+ }
+ filterRef.current.activeNodes = nodes;
+ filterRef.current.activeEdges = edges;
+ setActiveCount(edges.size);
+ }
+ sigmaRef.current?.refresh();
+ },
+ [data.data, kickFade],
+ );
+
+ useEffect(() => {
+ filterRef.current.hiddenTypes = hiddenTypes;
+ sigmaRef.current?.refresh();
+ }, [hiddenTypes]);
+
+ useEffect(() => {
+ selectedRef.current = selected;
+ sigmaRef.current?.refresh();
+ }, [selected]);
+
+ useEffect(() => {
+ recomputeActive(timeT);
+ }, [timeT, recomputeActive]);
+
+ useEffect(() => {
+ if (!containerRef.current || !data.data) return;
+ const g = new Graphology({ multi: true });
+ for (const n of data.data.nodes) {
+ if (!g.hasNode(n.id)) {
+ g.addNode(n.id, {
+ label: n.name,
+ // Semantica 配方:深壳 + 14% 类型 tint,核心 50% tint,钢灰描边微 tint
+ color: mix(NODE_CORE_BASE, n.color, NODE_CORE_MIX),
+ shellColor: mix(NODE_SHELL_BASE, n.color, NODE_TINT_MIX),
+ borderColor: mix(NODE_BORDER_BASE, n.color, 0.3),
+ ringColor: TRANSPARENT,
+ typeColor: n.color,
+ typeLabel: n.type_label,
+ typeKey: n.type_key,
+ type: n.shape === "square" ? "square" : "shell",
+ size: 5 + Math.min(8, Math.sqrt(Number(n.degree)) * 1.6),
+ });
+ }
+ }
+ for (const e of data.data.edges) {
+ if (g.hasNode(e.source) && g.hasNode(e.target)) {
+ g.addEdgeWithKey(e.id, e.source, e.target, {
+ label: e.label.toUpperCase(),
+ size: 1,
+ color: EDGE_COLOR,
+ type: "line",
+ });
+ }
+ }
+ // 布局:先静态铺开,再用 worker 动画稳定 ~2.5s(Semantica 式 stabilizing)
+ let fa2: InstanceType<typeof FA2Layout> | null = null;
+ let stabilizeTimer: ReturnType<typeof setTimeout> | null = null;
+ // 拖拽状态先于 fa2 声明:outputReducer 闭包引用它们
+ let dragged: string | null = null;
+ let dragPos: { x: number; y: number } | null = null;
+ let fa2Settings: ReturnType<typeof forceAtlas2.inferSettings> | null = null;
+ if (g.order > 0) {
+ circular.assign(g, { scale: 300 });
+ const settings = {
+ ...forceAtlas2.inferSettings(g),
+ gravity: 0.35,
+ scalingRatio: 22,
+ outboundAttractionDistribution: true,
+ };
+ fa2Settings = settings;
+ forceAtlas2.assign(g, { iterations: 60, settings });
+ fa2 = new FA2Layout(g, {
+ settings,
+ // 关键:回写时把被拖节点钉回光标(不闪);且提供 outputReducer 后
+ // supervisor 每帧 readGraphPositions —— 光标位置持续进入力模拟
+ outputReducer: (node, attr) => {
+ if (dragged && node === dragged && dragPos) {
+ attr.x = dragPos.x;
+ attr.y = dragPos.y;
+ }
+ return attr;
+ },
+ });
+ fa2.start();
+ setStabilizing(true);
+ stabilizeTimer = setTimeout(() => {
+ fa2?.stop();
+ setStabilizing(false);
+ }, 2500);
+ }
+
+ // 数据重建后布局回到 force(世界重新长出来)
+ setLayoutMode("force");
+ layoutModeRef.current = "force";
+
+ // 任意布局结果统一缩放到 FA2 同量级世界(±target),相机 reset 观感一致
+ const rescaleWorld = (target = 300) => {
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
+ g.forEachNode((_n, a) => {
+ minX = Math.min(minX, a.x as number);
+ maxX = Math.max(maxX, a.x as number);
+ minY = Math.min(minY, a.y as number);
+ maxY = Math.max(maxY, a.y as number);
+ });
+ const span = Math.max(maxX - minX, maxY - minY) || 1;
+ const k = (target * 2) / span;
+ const cx = (minX + maxX) / 2;
+ const cy = (minY + maxY) / 2;
+ g.updateEachNodeAttributes((_n, a) => ({ ...a, x: (a.x - cx) * k, y: (a.y - cy) * k }));
+ };
+
+ // 布局切换控制(挂到 ref 供组件层按钮调用;闭包内直握 g / fa2)
+ layoutCtlRef.current = {
+ apply: (mode) => {
+ if (g.order === 0) return;
+ if (stabilizeTimer) clearTimeout(stabilizeTimer);
+ fa2?.stop();
+ setStabilizing(false);
+ if (mode === "force") {
+ forceAtlas2.assign(g, { iterations: 60, settings: fa2Settings ?? undefined });
+ fa2?.start();
+ setStabilizing(true);
+ stabilizeTimer = setTimeout(() => {
+ fa2?.stop();
+ setStabilizing(false);
+ }, 2500);
+ } else if (mode === "circular") {
+ circular.assign(g, { scale: 300 });
+ } else {
+ // 按实体类型聚簇:同类型挤进同一个圆
+ circlepack.assign(g, { hierarchyAttributes: ["typeKey"] });
+ rescaleWorld(300);
+ }
+ sigma.setCustomBBox(null);
+ sigma.refresh();
+ sigma.getCamera().animatedReset({ duration: 300 });
+ },
+ };
+
+ sigmaRef.current?.kill();
+ const sigma = new Sigma(g, containerRef.current, {
+ allowInvalidContainer: true,
+ defaultNodeType: "shell",
+ nodeProgramClasses: {
+ // Semantica 节点解剖:状态环 → 描边 → 深色壳 → 微彩核心
+ shell: createNodeBorderProgram({
+ borders: [
+ { size: { value: 0.1 }, color: { attribute: "ringColor" } },
+ { size: { value: 0.07 }, color: { attribute: "borderColor" } },
+ { size: { value: 0.3 }, color: { attribute: "shellColor" } },
+ { size: { fill: true }, color: { attribute: "color" } },
+ ],
+ }),
+ square: NodeSquareShellProgram,
+ },
+ renderEdgeLabels: true,
+ defaultEdgeType: "line",
+ labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif',
+ labelSize: 11,
+ labelColor: { color: "#e5e5e5" },
+ labelRenderedSizeThreshold: 6,
+ labelDensity: 0.7,
+ labelGridCellSize: 140,
+ minCameraRatio: 0.04,
+ maxCameraRatio: 8,
+ edgeLabelSize: 9,
+ edgeLabelColor: { color: "#a1a1a1" },
+ edgeLabelFont: '"Geist", "Inter", sans-serif',
+ defaultDrawNodeLabel: drawPillLabel,
+ defaultDrawNodeHover: drawHoverCard,
+ nodeReducer: (node, attrs) => {
+ const f = filterRef.current;
+ const res = { ...attrs };
+ const base = attrs.size as number;
+ if (f.hiddenTypes.has(attrs.typeKey as string)) {
+ res.hidden = true;
+ return res;
+ }
+ // Semantica 状态表: muted { ×0.52, 全层压暗 }
+ const muteNode = () => {
+ res.size = base * 0.52;
+ res.color = mix(MUTED_SHELL, NODE_CORE_BASE, 0.3);
+ res.shellColor = MUTED_SHELL;
+ res.borderColor = TRANSPARENT;
+ res.ringColor = TRANSPARENT;
+ res.label = "";
+ res.zIndex = 0;
+ };
+ // hover 只提亮自身(不压暗全图);压暗聚焦只属于点击选中
+ if (hoverRef.current === node) {
+ res.size = Math.max(base * 1.08, 10.4);
+ res.ringColor = RING_HOVERED;
+ // 悬浮卡接管标签展示;label 本身保留(悬浮卡靠它渲染标题)
+ res.hideBaseLabel = true;
+ res.zIndex = 4;
+ return res;
+ }
+ // 选中实体可能不在当前画布(侧栏跳转/邻域重载间隙)——不在则跳过聚焦压暗逻辑
+ const sel = selectedRef.current && g.hasNode(selectedRef.current) ? selectedRef.current : null;
+ if (sel) {
+ if (node === sel) {
+ res.size = Math.max(base * 1.02, 9.2);
+ res.ringColor = RING_SELECTED;
+ res.forceLabel = true;
+ res.zIndex = 3;
+ return res;
+ }
+ if (g.areNeighbors(sel, node)) {
+ // neighbor {×0.76, min 4, zIndex 2}
+ res.size = Math.max(base * 0.76, 4);
+ res.zIndex = 2;
+ } else {
+ muteNode();
+ return res;
+ }
+ } else {
+ // default {×0.7}
+ res.size = base * 0.7;
+ }
+ if (f.activeNodes && !f.activeNodes.has(node)) {
+ muteNode();
+ return res;
+ }
+ // 播放淡入:从 muted 形态渐变到本帧算出的正常形态
+ const fs = fadeRef.current.get(node);
+ if (fs !== undefined) {
+ const t = Math.min(1, (performance.now() - fs) / FADE_MS);
+ res.size = (res.size as number) * (0.55 + 0.45 * t);
+ res.color = lerpColor(MUTED_SHELL, String(res.color ?? NODE_CORE_BASE), t);
+ res.shellColor = lerpColor(MUTED_SHELL, String(res.shellColor ?? NODE_SHELL_BASE), t);
+ res.borderColor = lerpColor("rgba(0,0,0,0)", String(res.borderColor ?? NODE_BORDER_BASE), t);
+ if (t < 0.7) res.label = "";
+ }
+ return res;
+ },
+ edgeReducer: (edge, attrs) => {
+ const f = filterRef.current;
+ const res = { ...attrs };
+ const [s, t] = g.extremities(edge);
+ const sk = g.getNodeAttribute(s, "typeKey") as string;
+ const tk = g.getNodeAttribute(t, "typeKey") as string;
+ if (f.hiddenTypes.has(sk) || f.hiddenTypes.has(tk)) {
+ res.hidden = true;
+ return res;
+ }
+ // hover: 只提亮关联边;selected: 提亮关联边 + 压暗其余
+ const hov = hoverRef.current;
+ const sel =
+ selectedRef.current && g.hasNode(selectedRef.current) ? selectedRef.current : null;
+ const boost = () => {
+ res.color = EDGE_FOCUS;
+ res.size = Math.max((attrs.size as number) * 1.42, 1.85);
+ res.zIndex = 5;
+ };
+ if (hov && (s === hov || t === hov)) {
+ boost();
+ } else if (sel) {
+ if (s === sel || t === sel) {
+ boost();
+ } else {
+ res.color = EDGE_DIM;
+ res.size = (attrs.size as number) * 0.6;
+ res.label = "";
+ return res;
+ }
+ }
+ if (f.activeEdges && !f.activeEdges.has(edge)) {
+ res.color = EDGE_DIM;
+ res.label = "";
+ return res;
+ }
+ // 播放淡入:边从近背景色渐亮到常规色(alpha 同步插值)
+ const fs = fadeRef.current.get(edge);
+ if (fs !== undefined) {
+ const t = Math.min(1, (performance.now() - fs) / FADE_MS);
+ res.color = lerpColor(EDGE_DIM, String(res.color), t);
+ if (t < 0.8) res.label = "";
+ }
+ return res;
+ },
+ });
+ sigma.on("clickNode", ({ node }) => setSelected(node));
+ sigma.on("doubleClickNode", ({ node, event }) => {
+ event.preventSigmaDefault();
+ setFocusEntity(node);
+ setSelected(node);
+ });
+ sigma.on("clickStage", () => setSelected(null));
+ sigma.on("enterNode", ({ node }) => {
+ hoverRef.current = node;
+ sigma.refresh();
+ });
+ sigma.on("leaveNode", () => {
+ hoverRef.current = null;
+ sigma.refresh();
+ });
+ // 边标签只在放大后出现(默认视距下太密,Semantica 同样克制)
+ const updateEdgeLabels = () =>
+ sigma.setSetting("renderEdgeLabels", sigma.getCamera().ratio < 0.7);
+ sigma.getCamera().on("updated", updateEdgeLabels);
+ updateEdgeLabels();
+
+ // 世界坐标网格:相机变动/容器尺寸变动时重绘
+ const renderGrid = () => {
+ if (gridRef.current) drawWorldGrid(gridRef.current, sigma);
+ };
+ sigma.getCamera().on("updated", renderGrid);
+ sigma.on("resize", renderGrid);
+ renderGrid();
+
+ // 节点拖拽 + 活的力导反馈。按下只记候选:视口位移 >4px 才升格为拖拽
+ //(否则纯点选也会误启 FA2);被拖节点由 fa2 的 outputReducer 钉在光标上(见上),
+ // 松手后稳定 ~1.2s 停机
+ let settleTimer: ReturnType<typeof setTimeout> | null = null;
+ let dragCandidate: string | null = null;
+ let downPoint: { x: number; y: number } | null = null;
+ sigma.on("downNode", (e) => {
+ dragCandidate = e.node;
+ downPoint = { x: e.event.x, y: e.event.y };
+ });
+ sigma.getMouseCaptor().on("mousemovebody", (e) => {
+ if (!dragCandidate) return;
+ if (!dragged) {
+ if (!downPoint || Math.hypot(e.x - downPoint.x, e.y - downPoint.y) < 4) return;
+ // 升格为拖拽
+ dragged = dragCandidate;
+ if (settleTimer) clearTimeout(settleTimer);
+ // 静态布局(circular/pack)下拖拽不唤醒力模拟——否则一碰就散架
+ if (layoutModeRef.current === "force" && fa2 && !fa2.isRunning()) fa2.start();
+ // 固定当前包围盒,避免拖拽时相机自动跟随缩放
+ if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox());
+ }
+ const pos = sigma.viewportToGraph(e);
+ dragPos = pos;
+ g.setNodeAttribute(dragged, "x", pos.x);
+ g.setNodeAttribute(dragged, "y", pos.y);
+ // 阻止相机平移
+ e.preventSigmaDefault();
+ e.original.preventDefault();
+ e.original.stopPropagation();
+ });
+ const endDrag = () => {
+ dragCandidate = null;
+ downPoint = null;
+ if (!dragged) return;
+ dragged = null;
+ dragPos = null;
+ settleTimer = setTimeout(() => fa2?.stop(), 1200);
+ };
+ sigma.getMouseCaptor().on("mouseup", endDrag);
+ sigmaRef.current = sigma;
+ if (import.meta.env.DEV) {
+ // 调试句柄(仅 dev):无头环境下检查 reducer 输出
+ (window as unknown as Record<string, unknown>).__g = g;
+ (window as unknown as Record<string, unknown>).__sigma = sigma;
+ (window as unknown as Record<string, unknown>).__sel = selectedRef;
+ }
+ recomputeActive(timeT);
+ return () => {
+ if (stabilizeTimer) clearTimeout(stabilizeTimer);
+ if (settleTimer) clearTimeout(settleTimer);
+ fa2?.kill();
+ setStabilizing(false);
+ sigma.kill();
+ sigmaRef.current = null;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [data.data]);
+
+ if (!kb) return <div className="p-8 text-sm text-neutral-500">{S.nav.loading}</div>;
+
+ const empty = data.isSuccess && data.data.nodes.length === 0;
+ const nodeCount = data.data?.nodes.length ?? 0;
+ const edgeCount = data.data?.edges.length ?? 0;
+
+ return (
+ <div className="h-full relative">
+ {/* 顶部悬浮条:搜索 + 图例 + 状态 */}
+ <div className="absolute top-3 left-3 right-3 z-10 flex items-start gap-2 pointer-events-none">
+ <div className="relative pointer-events-auto">
+ <input
+ className="input-dark w-60 px-3 py-1.5 text-sm shadow-lg"
+ placeholder={inSubgraph ? S.graph.searchInSubgraph : S.graph.searchEntity}
+ value={searchInput}
+ onChange={(e) => {
+ setSearchInput(e.target.value);
+ setSearchQ(e.target.value.trim());
+ }}
+ />
+ {searchQ && searchHits.length > 0 && (
+ <div className="glass-strong absolute mt-1 w-full rounded-lg shadow-xl overflow-hidden">
+ {searchHits.map((c) => (
+ <button
+ key={c.id}
+ onClick={() => {
+ // 子图内命中:只选中(已在视野里);全图搜索:跳到该实体邻域
+ if (!inSubgraph) setFocusEntity(c.id);
+ setSelected(c.id);
+ setSearchInput("");
+ setSearchQ("");
+ }}
+ className="w-full px-3 py-1.5 text-left text-sm text-neutral-200 hover:bg-white/5 flex items-center gap-2"
+ >
+ <span
+ className="h-2.5 w-2.5 rounded-full shrink-0"
+ style={{ background: c.color }}
+ />
+ <span className="truncate">{c.name}</span>
+ {c.disambiguator && (
+ <span className="text-xs text-neutral-500 truncate">· {c.disambiguator}</span>
+ )}
+ <span className="ml-auto text-xs text-neutral-500">{c.type_label}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ {focusEntity && (
+ <button
+ onClick={() => setFocusEntity(null)}
+ className="u-btn u-btn-ghost glass-strong pointer-events-auto px-3 py-1.5 text-sm shadow-lg"
+ >
+ {S.graph.backToOverview}
+ </button>
+ )}
+
+ {/* 图例(点击切换类型显隐) */}
+ <div className="pointer-events-auto flex flex-wrap gap-1.5 pt-0.5">
+ {types.map(([key, t]) => (
+ <button
+ key={key}
+ onClick={() =>
+ setHiddenTypes((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ })
+ }
+ className={`glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 transition-opacity ${
+ hiddenTypes.has(key) ? "opacity-35" : ""
+ }`}
+ >
+ <span
+ className={`h-2 w-2 ${t.shape === "square" ? "" : "rounded-full"}`}
+ style={{ background: t.color }}
+ />
+ <span className="text-neutral-300">{t.label}</span>
+ </button>
+ ))}
+ </div>
+
+ <div className="ml-auto pointer-events-none pt-0.5 u-num text-[11px] text-neutral-500">
+ {stabilizing && <span className="text-neutral-400">{S.graph.stabilizing} · </span>}
+ {S.graph.stats(nodeCount, edgeCount, timeT === null ? edgeCount : activeCount)}
+ </div>
+ </div>
+
+ {/* 画布:世界坐标网格层(随相机动)垫在 sigma WebGL 层下(全出血,时间岛悬浮其上) */}
+ <div className="absolute inset-0">
+ <canvas ref={gridRef} className="absolute inset-0 h-full w-full" />
+ <div ref={containerRef} className="absolute inset-0" />
+ </div>
+
+ {/* 左下控件塔:布局切换 + 相机(右下归实体侧栏,底部中央归时间岛) */}
+ <div className="absolute bottom-4 left-3 z-10 flex flex-col gap-2">
+ <div className="glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
+ {(
+ [
+ { key: "force", Icon: Orbit, label: S.graph.layoutForce },
+ { key: "circular", Icon: CircleDashed, label: S.graph.layoutCircular },
+ { key: "pack", Icon: Grape, label: S.graph.layoutPack },
+ ] as const
+ ).map(({ key, Icon, label }) => (
+ <button
+ key={key}
+ title={label}
+ onClick={() => {
+ setLayoutMode(key);
+ layoutModeRef.current = key;
+ layoutCtlRef.current?.apply(key);
+ }}
+ className={`p-2 transition-colors ${
+ layoutMode === key
+ ? "text-white bg-white/[0.1]"
+ : "text-neutral-400 hover:text-white hover:bg-white/[0.06]"
+ }`}
+ >
+ <Icon size={15} />
+ </button>
+ ))}
+ </div>
+ <div className="glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
+ <button
+ title={S.graph.zoomIn}
+ onClick={() => sigmaRef.current?.getCamera().animatedZoom({ duration: 220 })}
+ className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
+ >
+ <ZoomIn size={15} />
+ </button>
+ <button
+ title={S.graph.zoomOut}
+ onClick={() => sigmaRef.current?.getCamera().animatedUnzoom({ duration: 220 })}
+ className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
+ >
+ <ZoomOut size={15} />
+ </button>
+ <div className="h-px bg-white/10 mx-1.5" />
+ <button
+ title={S.graph.fitView}
+ onClick={() => sigmaRef.current?.getCamera().animatedReset({ duration: 300 })}
+ className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
+ >
+ <Maximize2 size={15} />
+ </button>
+ </div>
+ </div>
+
+ {empty && (
+ <div className="absolute inset-0 grid place-items-center pointer-events-none">
+ <div className="text-center text-sm text-neutral-500 max-w-xs">
+ <div className="glass mx-auto mb-3 h-14 w-14 rounded-2xl grid place-items-center text-lg font-bold text-neutral-300">
+ {S.nav.graph}
+ </div>
+ {S.graph.emptyBody}
+ </div>
+ </div>
+ )}
+
+ {/* 底部居中悬浮时间岛 */}
+ {edgeCount > 0 && (
+ <TimeScrubber
+ edges={data.data!.edges}
+ value={timeT}
+ onChange={setTimeT}
+ playing={playing}
+ onPlayingChange={setPlaying}
+ />
+ )}
+
+ {/* 实体侧栏 */}
+ {selected && kb && (
+ <EntityPanel
+ kbId={kb.id}
+ entityId={selected}
+ onClose={() => setSelected(null)}
+ onNavigate={(id) => {
+ // 跳转目标可能不在当前画布:同时把图 refocus 到它的邻域(与搜索选择一致)
+ setFocusEntity(id);
+ setSelected(id);
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+/* ============ 时间轴(底部居中悬浮岛:播放 + 密度带 + 拖动) ============ */
+
+/** 轨道 clientX → 对齐天步进的时间值(数据精度即 day,拖动求精细;播放仍按月推进求节奏)。 */
+function scrubValueAt(
+ clientX: number,
+ track: HTMLDivElement | null,
+ minTs: number,
+ maxTs: number,
+): number {
+ if (!track) return maxTs;
+ const rect = track.getBoundingClientRect();
+ // 布局未成形(宽度 0)时避免除零产出 NaN
+ if (rect.width < 1) return maxTs;
+ const frac = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
+ const raw = minTs + frac * (maxTs - minTs);
+ return Math.min(maxTs, minTs + Math.round((raw - minTs) / DAY_MS) * DAY_MS);
+}
+
+function TimeScrubber({
+ edges,
+ value,
+ onChange,
+ playing,
+ onPlayingChange,
+}: {
+ edges: GraphEdge[];
+ value: number | null;
+ onChange: (v: number | null) => void;
+ /* 播放态由 Graph 持有:渲染层要区分播放推进与手动拖动 */
+ playing: boolean;
+ onPlayingChange: (v: boolean) => void;
+}) {
+ const setPlaying = onPlayingChange;
+ const trackRef = useRef<HTMLDivElement>(null);
+ const draggingRef = useRef(false);
+
+ const { minTs, maxTs, bars } = useMemo(() => {
+ const now = Date.now();
+ const froms = edges
+ .map((e) => (e.valid_from ? Date.parse(e.valid_from) : NaN))
+ .filter((t) => !Number.isNaN(t));
+ const min = froms.length ? Math.min(...froms) : now - 5 * 365 * 24 * 3600 * 1000;
+ const minYear = new Date(min).getUTCFullYear();
+ const maxYear = new Date(now).getUTCFullYear();
+ const counts = new Map<number, number>();
+ for (const t of froms) {
+ const y = new Date(t).getUTCFullYear();
+ counts.set(y, (counts.get(y) ?? 0) + 1);
+ }
+ const peak = Math.max(1, ...counts.values());
+ const bars: { year: number; h: number }[] = [];
+ for (let y = minYear; y <= maxYear; y++) {
+ bars.push({ year: y, h: (counts.get(y) ?? 0) / peak });
+ }
+ return { minTs: Date.UTC(minYear, 0, 1), maxTs: now, bars };
+ }, [edges]);
+
+ // 播放按日推进(数据即 day 精度),日子快速翻过;整体节奏仍 ≈ 一个月/260ms。
+ // rAF 时间驱动:帧率无关,内部浮点累加避免取整漂移,值只在跨天时才下发
+ useEffect(() => {
+ if (!playing) return;
+ const SPEED = MONTH_MS / 260; // 每毫秒真实时间推进的时间线毫秒数
+ let raf = 0;
+ let last = performance.now();
+ let acc = value ?? minTs;
+ let lastSnapped = Number.NaN;
+ const step = (now: number) => {
+ acc += (now - last) * SPEED;
+ last = now;
+ if (acc >= maxTs) {
+ setPlaying(false);
+ onChange(null);
+ return;
+ }
+ const snapped = minTs + Math.round((acc - minTs) / DAY_MS) * DAY_MS;
+ if (snapped !== lastSnapped) {
+ lastSnapped = snapped;
+ onChange(snapped);
+ }
+ raf = requestAnimationFrame(step);
+ };
+ raf = requestAnimationFrame(step);
+ return () => cancelAnimationFrame(raf);
+ // 只随播放开关重启:acc 在循环内自持,value 帧帧变不应重建循环
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [playing, minTs, maxTs]);
+
+ // 展示到日:与数据的 day 级 valid_precision 对齐
+ const label = (() => {
+ if (value === null) return S.graph.allTime;
+ const d = new Date(value);
+ const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
+ const dd = String(d.getUTCDate()).padStart(2, "0");
+ return `${d.getUTCFullYear()}-${mm}-${dd}`;
+ })();
+
+ const minYear = bars[0]?.year;
+ const maxYear = bars[bars.length - 1]?.year;
+
+ return (
+ <div className="glass-strong absolute bottom-4 left-1/2 -translate-x-1/2 z-10 w-[min(560px,calc(100%-4rem))] rounded-2xl px-3 py-2 flex items-center gap-2.5 shadow-[0_12px_40px_rgba(0,0,0,0.5)]">
+ <button
+ onClick={() => {
+ if (!playing && value === null) onChange(minTs);
+ setPlaying(!playing);
+ }}
+ title={playing ? S.graph.pause : S.graph.play}
+ className="u-btn u-btn-ghost h-8 w-8 shrink-0 grid place-items-center rounded-lg"
+ >
+ {playing ? <Pause size={13} /> : <Play size={13} />}
+ </button>
+
+ <span className="shrink-0 u-num text-[10px] text-neutral-600">
+ {minYear}
+ </span>
+
+ {/* 密度带轨道:内嵌浅色井 + 每年事实量柱 */}
+ <div ref={trackRef} className="relative flex-1 h-9 rounded-lg bg-white/[0.04]">
+ <div className="absolute inset-x-1.5 top-1.5 bottom-1.5 flex items-end gap-[2px]">
+ {bars.map((b) => {
+ // 进入即亮(年初为判据):播放头脚下的柱子即已覆盖——进度条通用语义
+ const barTs = Date.UTC(b.year, 0, 1);
+ const past = value !== null && barTs <= value;
+ return (
+ <div key={b.year} className="flex-1 flex items-end h-full" title={`${b.year}`}>
+ <div
+ className="w-full rounded-[1px] transition-colors"
+ style={{
+ height: `${Math.max(10, b.h * 100)}%`,
+ // 播放中已扫过的年份提亮,停止后回到常规亮度
+ background:
+ value !== null && past && playing
+ ? "rgba(255,255,255,0.62)"
+ : value === null || past
+ ? "rgba(255,255,255,0.32)"
+ : "rgba(255,255,255,0.09)",
+ }}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <input
+ type="range"
+ className="scrubber-range"
+ min={minTs}
+ max={maxTs}
+ step={DAY_MS}
+ value={value ?? maxTs}
+ onChange={(e) => {
+ setPlaying(false);
+ onChange(Number(e.target.value));
+ }}
+ // 原生 range 的拖拽手势会被页面级鼠标监听(如图上拖节点)干扰——
+ // 自己用 pointer capture 驱动拖动,点击与拖拽都走同一条计算路径
+ onPointerDown={(e) => {
+ setPlaying(false);
+ draggingRef.current = true;
+ try {
+ e.currentTarget.setPointerCapture(e.pointerId);
+ } catch {
+ /* 合成事件的 pointerId 可能无效,忽略 */
+ }
+ onChange(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
+ }}
+ onPointerMove={(e) => {
+ if (draggingRef.current)
+ onChange(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
+ }}
+ onPointerUp={() => {
+ draggingRef.current = false;
+ }}
+ onPointerCancel={() => {
+ draggingRef.current = false;
+ }}
+ />
+ </div>
+
+ <span className="shrink-0 u-num text-[10px] text-neutral-600">
+ {maxYear}
+ </span>
+
+ <div className="w-[5.6rem] shrink-0 text-center u-num text-xs text-neutral-200">
+ {label}
+ </div>
+
+ <div className="h-5 w-px shrink-0 bg-white/10" />
+
+ {/* 双锚点分段:所处锚点高亮、点击即跳;拖在中间某天时两者皆不亮 */}
+ <div className="flex shrink-0 rounded-lg overflow-hidden border border-white/10">
+ {(
+ [
+ { key: "all", label: S.graph.allTime, active: value === null, to: null },
+ {
+ key: "now",
+ label: S.graph.nowBtn,
+ active: value !== null && maxTs - value < DAY_MS,
+ to: maxTs,
+ },
+ ] as const
+ ).map((a) => (
+ <button
+ key={a.key}
+ onClick={() => {
+ setPlaying(false);
+ onChange(a.to);
+ }}
+ className={`px-2.5 py-1.5 text-xs transition-colors ${
+ a.active
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
+ }`}
+ >
+ {a.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/* ============ 实体侧栏 ============ */
+
+function fmtTime(iso: string | null, precision: string): string | null {
+ if (!iso) return null;
+ const d = new Date(iso);
+ const y = d.getUTCFullYear();
+ const m = String(d.getUTCMonth() + 1).padStart(2, "0");
+ const day = String(d.getUTCDate()).padStart(2, "0");
+ if (precision === "year") return `${y}`;
+ if (precision === "month") return `${y}-${m}`;
+ return `${y}-${m}-${day}`;
+}
+
+function fmtInterval(f: EntityFact): string {
+ if (f.temporal === "eternal") return "";
+ const from = fmtTime(f.valid_from, f.valid_precision);
+ const to = fmtTime(f.valid_to, f.valid_precision);
+ if (!from && !to) return "";
+ if (from && !to) return `${from} ~ ${S.graph.ongoing}`;
+ if (from && to) return `${from} ~ ${to}`;
+ return `~ ${to}`;
+}
+
+function EntityPanel({
+ kbId,
+ entityId,
+ onClose,
+ onNavigate,
+}: {
+ kbId: string;
+ entityId: string;
+ onClose: () => void;
+ onNavigate: (entityId: string) => void;
+}) {
+ const detail = useQuery({
+ queryKey: ["entity", kbId, entityId],
+ queryFn: () => api.entityDetail(kbId, entityId),
+ });
+ const [openFact, setOpenFact] = useState<string | null>(null);
+ // Relations = 按关系分组(查关系);Timeline = 按时间摊开(读故事)
+ const [view, setView] = useState<"relations" | "timeline">("relations");
+
+ const e: GraphNode | undefined = detail.data?.entity;
+
+ // Relations = 当下有效的快照(as-of now);已闭合的历史只出现在 Timeline。
+ // 按「方向 + 谓词」分组:实体自身名不再逐行重复,谓词只出现在小节标题里
+ const { groups, historicalCount } = useMemo(() => {
+ const all = detail.data?.facts ?? [];
+ const nowIso = new Date().toISOString();
+ const current = all.filter(
+ (f) => (!f.valid_from || f.valid_from <= nowIso) && (!f.valid_to || f.valid_to > nowIso),
+ );
+ const map = new Map<
+ string,
+ { key: string; label: string; direction: string; rows: EntityFact[] }
+ >();
+ for (const f of current) {
+ const k = `${f.direction}:${f.predicate_key}`;
+ if (!map.has(k))
+ map.set(k, { key: k, label: f.predicate_label, direction: f.direction, rows: [] });
+ map.get(k)!.rows.push(f);
+ }
+ const arr = [...map.values()];
+ for (const gr of arr)
+ gr.rows.sort((a, b) => ((a.valid_from ?? "9999") < (b.valid_from ?? "9999") ? -1 : 1));
+ arr.sort((a, b) => b.rows.length - a.rows.length || a.label.localeCompare(b.label));
+ return { groups: arr, historicalCount: all.length - current.length };
+ }, [detail.data]);
+
+ return (
+ <div className="glass-strong absolute top-14 right-3 bottom-20 w-80 z-10 rounded-xl shadow-2xl flex flex-col">
+ <div className="flex items-start justify-between px-4 py-3.5 border-b border-white/10">
+ <div>
+ {e && (
+ <>
+ <div className="flex items-center gap-2">
+ <span
+ className="h-2.5 w-2.5 rounded-full shrink-0"
+ style={{ background: e.color, boxShadow: `0 0 8px ${e.color}55` }}
+ />
+ <span
+ className="text-[15px] font-semibold tracking-tight text-white"
+ style={{ fontFamily: "var(--font-display)" }}
+ >
+ {e.name}
+ </span>
+ </div>
+ <div className="mt-1 text-xs text-neutral-500">
+ {e.disambiguator ? `${e.disambiguator} · ` : ""}
+ {e.type_label} · {detail.data?.facts.length ?? 0} {S.graph.facts}
+ </div>
+ </>
+ )}
+ </div>
+ <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200 mt-0.5">
+ <X size={15} />
+ </button>
+ </div>
+
+ {/* 视图切换:Relations(分组)| Timeline(年表) */}
+ <div className="px-4 pt-2.5">
+ <div className="flex rounded-lg overflow-hidden border border-white/10 w-fit">
+ {(["relations", "timeline"] as const).map((v) => (
+ <button
+ key={v}
+ onClick={() => setView(v)}
+ className={`px-3 py-1 text-[11px] transition-colors ${
+ view === v
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
+ }`}
+ >
+ {v === "relations" ? S.graph.viewRelations : S.graph.viewTimeline}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="u-scroll flex-1 overflow-y-auto px-2 py-2">
+ {view === "relations" && historicalCount > 0 && (
+ <button
+ onClick={() => setView("timeline")}
+ className="mx-2 mb-2 mt-0.5 text-[11px] text-neutral-500 hover:text-neutral-300 underline-offset-2 hover:underline"
+ >
+ {S.graph.historicalNote(historicalCount)}
+ </button>
+ )}
+ {view === "relations" &&
+ groups.map((gr) => (
+ <div key={gr.key} className="mb-3 last:mb-1">
+ <div className="flex items-center gap-1.5 px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-500">
+ {gr.direction === "in" ? <ArrowLeft size={10} /> : <ArrowRight size={10} />}
+ {gr.label}
+ {gr.rows.length > 1 && <span className="text-neutral-600">{gr.rows.length}</span>}
+ </div>
+ <div>
+ {gr.rows.map((f) => (
+ <FactRow
+ key={f.id}
+ kbId={kbId}
+ fact={f}
+ open={openFact === f.id}
+ onToggle={() => setOpenFact(openFact === f.id ? null : f.id)}
+ onNavigate={onNavigate}
+ />
+ ))}
+ </div>
+ </div>
+ ))}
+ {view === "timeline" && (
+ <TimelineView
+ kbId={kbId}
+ facts={detail.data?.facts ?? []}
+ openFact={openFact}
+ onToggle={(id) => setOpenFact(openFact === id ? null : id)}
+ onNavigate={onNavigate}
+ />
+ )}
+ {detail.data?.facts.length === 0 && (
+ <p className="text-sm text-neutral-500 p-2">{S.graph.noFacts}</p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** 年表视图:带区间的事实按起点摊开成竖直时间线;无时间的沉到底部 undated。 */
+function TimelineView({
+ kbId,
+ facts,
+ openFact,
+ onToggle,
+ onNavigate,
+}: {
+ kbId: string;
+ facts: EntityFact[];
+ openFact: string | null;
+ onToggle: (id: string) => void;
+ onNavigate: (entityId: string) => void;
+}) {
+ const dated = facts
+ .filter((f) => f.temporal !== "eternal" && (f.valid_from || f.valid_to))
+ .sort((a, b) =>
+ (a.valid_from ?? a.valid_to ?? "") < (b.valid_from ?? b.valid_to ?? "") ? -1 : 1,
+ );
+ const undated = facts.filter((f) => !dated.includes(f));
+
+ return (
+ <div className="px-2 pt-1">
+ <div className="relative ml-1.5 border-l border-white/15 pl-3 space-y-0.5">
+ {dated.map((f) => (
+ <div key={f.id} className="relative">
+ <span className="absolute -left-[17.5px] top-2.5 h-2 w-2 rounded-full bg-neutral-600 ring-2 ring-[#0f0f10]" />
+ <TimelineRow
+ kbId={kbId}
+ fact={f}
+ open={openFact === f.id}
+ onToggle={() => onToggle(f.id)}
+ onNavigate={onNavigate}
+ />
+ </div>
+ ))}
+ {dated.length === 0 && (
+ <p className="py-2 text-xs text-neutral-500">{S.graph.timelineEmpty}</p>
+ )}
+ </div>
+ {undated.length > 0 && (
+ <div className="mt-3">
+ <div className="px-2 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600">
+ {S.graph.undated}
+ </div>
+ {undated.map((f) => (
+ <FactRow
+ key={f.id}
+ kbId={kbId}
+ fact={f}
+ open={openFact === f.id}
+ onToggle={() => onToggle(f.id)}
+ onNavigate={onNavigate}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** 年表条目:区间 + 闭合方式标记 + 开放事实的最后确认时间;点击展开证据。 */
+function TimelineRow({
+ kbId,
+ fact,
+ open,
+ onToggle,
+ onNavigate,
+}: {
+ kbId: string;
+ fact: EntityFact;
+ open: boolean;
+ onToggle: () => void;
+ onNavigate: (entityId: string) => void;
+}) {
+ const interval = fmtInterval(fact);
+ const isOpenEnded = !fact.valid_to;
+ const literal = fmtObjectValue(fact.object_value);
+ return (
+ <div
+ className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${
+ fact.stale ? "opacity-55" : ""
+ }`}
+ title={fact.stale ? S.graph.staleFactHint : undefined}
+ >
+ <button onClick={onToggle} className="w-full text-left px-2 py-1.5">
+ <div className="flex items-center gap-1.5 u-num text-[10.5px] text-neutral-500">
+ {interval || "—"}
+ {fact.corrected && (
+ <span className="text-neutral-600" title={S.graph.correctedHint}>
+ ⟲
+ </span>
+ )}
+ {isOpenEnded && fact.last_evidence_time && (
+ <span className="ml-auto text-neutral-600">
+ {S.graph.lastConfirmed(fact.last_evidence_time.slice(0, 10))}
+ </span>
+ )}
+ </div>
+ <div className="mt-0.5 flex items-center gap-1.5 text-[13px] text-neutral-200">
+ <span className="text-neutral-500 text-xs">
+ {fact.direction === "in" ? "←" : "→"} {fact.predicate_label}
+ </span>
+ {fact.other_id ? (
+ <span
+ role="link"
+ tabIndex={0}
+ onClick={(ev) => {
+ ev.stopPropagation();
+ onNavigate(fact.other_id!);
+ }}
+ onKeyDown={(ev) => {
+ if (ev.key === "Enter") {
+ ev.stopPropagation();
+ onNavigate(fact.other_id!);
+ }
+ }}
+ className="truncate hover:text-white hover:underline underline-offset-2 decoration-white/30"
+ >
+ {fact.other_name ?? "?"}
+ </span>
+ ) : (
+ <span className="truncate">{fact.other_name ?? literal ?? "?"}</span>
+ )}
+ {fact.stale && (
+ <span className="u-chip u-chip-neutral shrink-0 !text-[10px] !px-1.5">
+ {S.graph.staleFactChip}
+ </span>
+ )}
+ </div>
+ </button>
+ {open && <EvidenceList kbId={kbId} fact={fact} />}
+ </div>
+ );
+}
+
+/** 字面值宾语的显示:属性 {value,unit} / 问数映射 {summary} / 其他 JSON 兜底。 */
+function fmtObjectValue(v: Record<string, unknown> | null): string | null {
+ if (!v) return null;
+ if (v.value !== undefined) {
+ const val = typeof v.value === "boolean" ? (v.value ? "✓" : "✗") : String(v.value);
+ return typeof v.unit === "string" && v.unit ? `${val} ${v.unit}` : val;
+ }
+ if (typeof v.summary === "string") return v.summary;
+ return JSON.stringify(v);
+}
+
+function FactRow({
+ kbId,
+ fact,
+ open,
+ onToggle,
+ onNavigate,
+}: {
+ kbId: string;
+ fact: EntityFact;
+ open: boolean;
+ onToggle: () => void;
+ onNavigate: (entityId: string) => void;
+}) {
+ const interval = fmtInterval(fact);
+ // 与 Review 的低置信口径一致:只有低到需要怀疑才挂 chip,常规置信保持沉默
+ const lowConfidence = fact.confidence < 0.75;
+
+ return (
+ <div
+ className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${
+ fact.stale ? "opacity-55" : ""
+ }`}
+ title={fact.stale ? S.graph.staleFactHint : undefined}
+ >
+ <button onClick={onToggle} className="w-full text-left px-2 py-1.5 flex items-center gap-1.5">
+ <ChevronRight
+ size={11}
+ className={`shrink-0 text-neutral-600 transition-transform ${open ? "rotate-90" : ""}`}
+ />
+ {fact.other_id ? (
+ <span
+ role="link"
+ tabIndex={0}
+ onClick={(ev) => {
+ ev.stopPropagation();
+ onNavigate(fact.other_id!);
+ }}
+ onKeyDown={(ev) => {
+ if (ev.key === "Enter") {
+ ev.stopPropagation();
+ onNavigate(fact.other_id!);
+ }
+ }}
+ className="truncate text-[13px] text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
+ >
+ {fact.other_name ?? "?"}
+ </span>
+ ) : (
+ <span className="truncate text-[13px] text-neutral-200">
+ {fact.other_name ?? fmtObjectValue(fact.object_value) ?? "?"}
+ </span>
+ )}
+ {lowConfidence && (
+ <span className="u-chip u-chip-warn shrink-0 !text-[10px] !px-1.5">
+ {Math.round(fact.confidence * 100)}%
+ </span>
+ )}
+ {fact.stale && (
+ <span className="u-chip u-chip-neutral shrink-0 !text-[10px] !px-1.5">
+ {S.graph.staleFactChip}
+ </span>
+ )}
+ {interval && (
+ <span className="ml-auto shrink-0 pl-2 u-num text-[10.5px] text-neutral-500">
+ {interval}
+ </span>
+ )}
+ </button>
+ {open && <EvidenceList kbId={kbId} fact={fact} />}
+ </div>
+ );
+}
+
+/** 证据展开区(FactRow 与 TimelineRow 共用):quote + 跳原文 + 版本角标 + 置信。 */
+function EvidenceList({ kbId, fact }: { kbId: string; fact: EntityFact }) {
+ const evidence = useQuery({
+ queryKey: ["evidence", fact.id],
+ queryFn: () => api.factEvidence(kbId, fact.id),
+ });
+ return (
+ <div className="mx-2 mb-2 mt-0.5 space-y-2 border-l border-white/15 pl-2.5">
+ {evidence.data?.evidence.map((ev: Evidence) => (
+ <Link
+ key={ev.chunk_id}
+ to="/doc/$docId"
+ params={{ docId: ev.document_id }}
+ search={{ chunk: ev.chunk_id }}
+ className="block text-xs text-neutral-500 hover:text-neutral-300"
+ >
+ <div className="line-clamp-2 italic">
+ {ev.quote ? `“${ev.quote}”` : S.graph.noQuote}
+ </div>
+ <div className="mt-0.5 text-neutral-400">
+ {S.graph.sectionRef(ev.filename, ev.seq + 1)}
+ {ev.stale && (
+ <span
+ className="ml-1.5 u-num text-[10px] text-neutral-600"
+ title={S.graph.staleEvidenceHint}
+ >
+ {S.graph.fromVersion(ev.doc_version)}
+ </span>
+ )}
+ </div>
+ </Link>
+ ))}
+ {evidence.data?.evidence.length === 0 && (
+ <p className="text-xs text-neutral-500">{S.graph.noEvidence}</p>
+ )}
+ {/* 置信度只在低到值得怀疑时说话(与 Review 低置信口径一致),常规不标 */}
+ {fact.confidence < 0.75 && (
+ <p className="text-[10px] text-[var(--u-warn)]">
+ {Math.round(fact.confidence * 100)}% {S.graph.confidence}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/pages/KbSettings.tsx b/web/src/pages/KbSettings.tsx
new file mode 100644
index 00000000..f6c217e2
--- /dev/null
+++ b/web/src/pages/KbSettings.tsx
@@ -0,0 +1,506 @@
+/* 知识库设置:左栏分节(General / Members / Danger zone),为未来设置项立骨架
+ (抽取设置、保留策略、库级令牌…)。访问控制由 API 端执行(库 admin 起步)。
+ 分节互斥渲染也根治了下拉弹层被后续玻璃卡(backdrop-filter 自成 stacking
+ context)遮蔽的层级 bug。 */
+import { useEffect, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import {
+ Database,
+ History as HistoryIcon,
+ Lock,
+ Plus,
+ Settings2,
+ TriangleAlert,
+ Users,
+} from "lucide-react";
+import { api, type AuditEvent } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { DangerConfirm, Dropdown, Loading, RAIL_CLS, SearchSelect } from "../ui";
+
+const KB_ROLES = [
+ { value: "viewer", label: S.kbset.roles.viewer },
+ { value: "editor", label: S.kbset.roles.editor },
+ { value: "admin", label: S.kbset.roles.admin },
+];
+
+type Section = "general" | "members" | "data" | "activity" | "danger";
+
+export function KbSettings() {
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const { kb: currentKb } = useKb();
+ const { kb: kbParam } = useSearch({ from: "/app/kb-settings" });
+ const kbId = kbParam ?? currentKb?.id;
+
+ const kb = useQuery({
+ queryKey: ["kbOne", kbId],
+ queryFn: () => api.kbDetail(kbId!),
+ enabled: !!kbId,
+ });
+
+ const [section, setSection] = useState<Section>("general");
+ const [name, setName] = useState("");
+ const [desc, setDesc] = useState("");
+ const [visibility, setVisibility] = useState<"open" | "restricted">("open");
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (kb.data) {
+ setName(kb.data.name);
+ setDesc(kb.data.description ?? "");
+ setVisibility(kb.data.visibility);
+ }
+ }, [kb.data]);
+
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey: ["kbOne", kbId] });
+ queryClient.invalidateQueries({ queryKey: ["kbs"] });
+ };
+
+ const save = useMutation({
+ mutationFn: () =>
+ api.updateKb(kbId!, { name: name.trim(), description: desc.trim() || null, visibility }),
+ onSuccess: () => {
+ setError(null);
+ invalidate();
+ },
+ onError: (e) => setError((e as Error).message),
+ });
+
+ const removeKb = useMutation({
+ mutationFn: () => api.deleteKb(kbId!),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["kbs"] });
+ navigate({ to: "/library", search: {} });
+ },
+ onError: (e) => setError((e as Error).message),
+ });
+
+ if (!kbId || kb.isPending) return <Loading>{S.nav.loading}</Loading>;
+ if (kb.isError)
+ return <div className="p-8 text-sm text-rose-400">{(kb.error as Error).message}</div>;
+
+ const lbl = "block text-xs font-medium text-neutral-500 mb-1";
+ const rail =
+ "w-full flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] text-left transition-colors";
+
+ const isDefault = kb.data.is_default;
+ const sections: { key: Section; label: string; Icon: typeof Settings2; danger?: boolean }[] = [
+ { key: "general", label: S.kbset.general, Icon: Settings2 },
+ { key: "members", label: S.kbset.members, Icon: Users },
+ { key: "data", label: S.kbset.data, Icon: Database },
+ { key: "activity", label: S.kbset.activity, Icon: HistoryIcon },
+ // 默认库不可删除:danger 节整个不出现
+ ...(isDefault
+ ? []
+ : [{ key: "danger" as Section, label: S.kbset.danger, Icon: TriangleAlert, danger: true }]),
+ ];
+
+ return (
+ <div className="h-full flex">
+ {/* 分节导航:未来的抽取设置/保留策略/令牌等在此扩展 */}
+ <aside className={`${RAIL_CLS} p-3 space-y-0.5`}>
+ {sections.map(({ key, label, Icon, danger }) => (
+ <button
+ key={key}
+ onClick={() => setSection(key)}
+ className={`${rail} ${
+ section === key
+ ? "u-nav-active"
+ : danger
+ ? "text-neutral-500 hover:bg-white/[0.05] hover:text-[var(--u-danger)]"
+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200"
+ }`}
+ >
+ <Icon size={14} />
+ {label}
+ </button>
+ ))}
+ </aside>
+
+ <main className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">
+ <div className="max-w-xl space-y-5">
+ {/* 不缀库名:顶栏切换器已标明当前库 */}
+ <h2 className="u-title text-lg">{S.kbset.title}</h2>
+
+ {section === "general" && (
+ <div className="glass rounded-xl p-4 space-y-3">
+ <div className="grid grid-cols-2 gap-2">
+ <div>
+ <label className={lbl}>{S.settings.kbs.name}</label>
+ <input
+ className="input-dark w-full px-3 py-2 text-sm"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ </div>
+ <div>
+ <label className={lbl}>{S.settings.kbs.visibility}</label>
+ {isDefault ? (
+ /* 默认库锁 open:说明常驻可见(藏在 hover 里等于没解释),详情见 grid 下方整行 */
+ <div className="flex items-center gap-1.5 rounded-lg border border-white/10 px-2.5 py-2 text-[11px] text-neutral-500 cursor-not-allowed">
+ <Lock size={11} className="shrink-0 text-neutral-600" />
+ {S.kbset.defaultOpenLabel}
+ </div>
+ ) : (
+ <div className="flex rounded-lg overflow-hidden border border-white/10">
+ {(
+ [
+ ["open", "Open"],
+ ["restricted", S.settings.kbs.visRestricted],
+ ] as const
+ ).map(([v, label]) => (
+ <button
+ key={v}
+ onClick={() => setVisibility(v)}
+ title={label}
+ className={`flex-1 px-2 py-2 text-[11px] truncate transition-colors ${
+ visibility === v
+ ? "bg-white/[0.12] text-white"
+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ {isDefault && (
+ <p className="text-xs leading-relaxed text-neutral-500">
+ {S.kbset.defaultOpenNote}
+ </p>
+ )}
+ <div>
+ <label className={lbl}>{S.settings.kbs.description}</label>
+ <input
+ className="input-dark w-full px-3 py-2 text-sm"
+ value={desc}
+ onChange={(e) => setDesc(e.target.value)}
+ />
+ </div>
+ <div className="flex items-center gap-3">
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!name.trim() || save.isPending}
+ onClick={() => save.mutate()}
+ >
+ {S.kbset.save}
+ </button>
+ {save.isSuccess && (
+ <span className="text-xs text-neutral-400">{S.kbset.saved}</span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {section === "members" && <KbMembers kbId={kbId} />}
+ {section === "data" && <KbDataSources kbId={kbId} />}
+
+ {section === "activity" && <KbActivity kbId={kbId} />}
+
+ {section === "danger" && (
+ <div className="glass rounded-2xl px-5 py-4 flex items-center justify-between gap-4">
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-neutral-200">
+ {S.kbset.deleteRowTitle}
+ </div>
+ <div className="mt-0.5 text-xs text-neutral-500">{S.kbset.deleteRowHint}</div>
+ </div>
+ <button
+ className="u-btn px-3.5 py-1.5 text-xs font-semibold shrink-0"
+ style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
+ onClick={() => setConfirmingDelete(true)}
+ >
+ {S.kbset.deleteRowBtn}
+ </button>
+ </div>
+ )}
+
+ {error && <p className="text-sm text-rose-400">{error}</p>}
+
+ {confirmingDelete && (
+ <DangerConfirm
+ title={S.kbset.deleteKb}
+ hint={S.kbset.deleteHint(kb.data.name)}
+ requireText={kb.data.name}
+ confirmLabel={S.kbset.deleteBtn}
+ cancelLabel={S.library.cancel}
+ busy={removeKb.isPending}
+ onConfirm={() => removeKb.mutate()}
+ onCancel={() => setConfirmingDelete(false)}
+ />
+ )}
+ </div>
+ </main>
+ </div>
+ );
+}
+
+/** detail 里挑一个人类可读的名字(按 action 语义各异,逐键兜底) */
+function auditDetailName(e: AuditEvent): string {
+ const d = e.detail;
+ const cand = [d.label, d.name, d.filename, d.key, d.role];
+ const hit = cand.find((v) => typeof v === "string" && v);
+ return typeof hit === "string" ? hit : "";
+}
+
+function KbActivity({ kbId }: { kbId: string }) {
+ const audit = useQuery({
+ queryKey: ["kbAudit", kbId],
+ queryFn: () => api.kbAudit(kbId),
+ });
+ const events = audit.data?.events ?? [];
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <p className="text-xs text-neutral-500 mb-3">{S.kbset.activityHint}</p>
+ {audit.isPending ? (
+ <p className="text-xs text-neutral-600">{S.nav.loading}</p>
+ ) : events.length === 0 ? (
+ <p className="text-xs text-neutral-600">{S.kbset.activityEmpty}</p>
+ ) : (
+ <div className="space-y-0.5">
+ {events.map((e) => (
+ <div key={e.id} className="flex items-baseline gap-3 py-1.5 text-[13px]">
+ <span className="u-num shrink-0 text-[11px] text-neutral-600">
+ {e.created_at.slice(0, 16).replace("T", " ")}
+ </span>
+ <span className="min-w-0 truncate">
+ <span className="text-neutral-200">
+ {e.actor_name ?? S.kbset.deletedUser}
+ </span>{" "}
+ <span className="text-neutral-500">
+ {S.kbset.auditActions[e.action] ?? e.action}
+ </span>
+ {auditDetailName(e) && (
+ <span className="text-neutral-300"> “{auditDetailName(e)}”</span>
+ )}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** 知识库层数据源挂载:从系统已注册的源里挑选;挂载即摄取 schema。
+ 注册新连接是部署级动作:管理员从这里深链去 Deployment settings 的 Data sources。 */
+function KbDataSources({ kbId }: { kbId: string }) {
+ const queryClient = useQueryClient();
+ const navigate = useNavigate();
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ const mounted = useQuery({
+ queryKey: ["kbDataSources", kbId],
+ queryFn: () => api.kbDataSources(kbId),
+ });
+ const available = useQuery({
+ queryKey: ["kbDataSourcesAvail", kbId],
+ queryFn: () => api.kbDataSourcesAvailable(kbId),
+ });
+ const [picked, setPicked] = useState("");
+ const [notice, setNotice] = useState<string | null>(null);
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: ["kbDataSources", kbId] });
+
+ const mount = useMutation({
+ mutationFn: (dsId: string) => api.mountDataSource(kbId, dsId),
+ onSuccess: (r) => {
+ setPicked("");
+ setNotice(S.kbset.dataSchemaSynced(r.schema_tables));
+ invalidate();
+ },
+ });
+ const unmount = useMutation({
+ mutationFn: (dsId: string) => api.unmountDataSource(kbId, dsId),
+ onSettled: invalidate,
+ });
+ const sync = useMutation({
+ mutationFn: (dsId: string) => api.syncDataSourceSchema(kbId, dsId),
+ onSuccess: (r) => setNotice(S.kbset.dataSchemaSynced(r.schema_tables)),
+ });
+ const explore = useMutation({
+ mutationFn: () => api.exploreMappings(kbId),
+ onSuccess: () => setNotice(S.kbset.dataExploreQueued),
+ });
+
+ const mountedIds = new Set((mounted.data?.data_sources ?? []).map((d) => d.id));
+ const mountable = (available.data?.data_sources ?? []).filter((d) => !mountedIds.has(d.id));
+
+ return (
+ <div className="space-y-4">
+ <p className="text-xs text-neutral-500">{S.kbset.dataHint}</p>
+
+ <div className="glass rounded-xl divide-y divide-white/5">
+ {(mounted.data?.data_sources ?? []).map((d) => (
+ <div key={d.id} className="px-4 py-3 flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-neutral-200">{d.name}</div>
+ <div className="text-xs text-neutral-500 font-mono truncate">{d.summary}</div>
+ </div>
+ <button
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
+ disabled={sync.isPending}
+ onClick={() => sync.mutate(d.id)}
+ >
+ {S.kbset.dataSyncSchema}
+ </button>
+ <button
+ className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
+ disabled={unmount.isPending}
+ onClick={() => unmount.mutate(d.id)}
+ >
+ {S.kbset.dataUnmount}
+ </button>
+ </div>
+ ))}
+ {mounted.data?.data_sources.length === 0 && (
+ <p className="px-4 py-6 text-sm text-neutral-500">{S.kbset.dataNone}</p>
+ )}
+ </div>
+
+ {mountable.length > 0 && (
+ <div className="flex items-center gap-2">
+ <SearchSelect
+ className="flex-1"
+ value={picked}
+ options={mountable.map((d) => ({ value: d.id, label: d.name, hint: d.summary }))}
+ onChange={setPicked}
+ placeholder={S.kbset.dataMount + "…"}
+ />
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs shrink-0"
+ disabled={!picked || mount.isPending}
+ onClick={() => mount.mutate(picked)}
+ >
+ {S.kbset.dataMount}
+ </button>
+ </div>
+ )}
+ {/* 连接注册在部署层:管理员给直达入口,其他人指路找管理员 */}
+ {me.data?.is_admin ? (
+ <button
+ className="flex items-center gap-1.5 text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
+ onClick={() => navigate({ to: "/admin", search: { tab: "datasources" } })}
+ >
+ <Plus size={12} />
+ {S.kbset.dataNewConn}
+ </button>
+ ) : (
+ mountable.length === 0 &&
+ available.data &&
+ (mounted.data?.data_sources.length ?? 0) === 0 && (
+ <p className="text-xs text-neutral-600">{S.kbset.dataNoneAvailable}</p>
+ )
+ )}
+ {(mounted.data?.data_sources.length ?? 0) > 0 && (
+ <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
+ <p className="text-xs text-neutral-500 flex-1">{S.kbset.dataExploreHint}</p>
+ <button
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
+ disabled={explore.isPending}
+ onClick={() => explore.mutate()}
+ >
+ {S.kbset.dataExplore}
+ </button>
+ </div>
+ )}
+ {notice && <p className="text-xs text-[var(--u-ok)]">{notice}</p>}
+ {(mount.isError || sync.isError || explore.isError) && (
+ <p className="text-xs text-rose-400">
+ {((mount.error ?? sync.error ?? explore.error) as Error).message}
+ </p>
+ )}
+ </div>
+ );
+}
+
+function KbMembers({ kbId }: { kbId: string }) {
+ const queryClient = useQueryClient();
+ const members = useQuery({
+ queryKey: ["kbMembers", kbId],
+ queryFn: () => api.kbMembers(kbId),
+ });
+ const orgUsers = useQuery({ queryKey: ["orgUsers"], queryFn: api.orgUsers });
+ const [addUserId, setAddUserId] = useState("");
+ const [addRole, setAddRole] = useState("viewer");
+
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: ["kbMembers", kbId] });
+
+ const setMember = useMutation({
+ mutationFn: ({ userId, role }: { userId: string; role: string }) =>
+ api.setKbMember(kbId, userId, role),
+ onSuccess: () => {
+ setAddUserId("");
+ invalidate();
+ },
+ });
+ const remove = useMutation({
+ mutationFn: (userId: string) => api.removeKbMember(kbId, userId),
+ onSuccess: invalidate,
+ });
+
+ const memberIds = new Set(members.data?.members.map((m) => m.user_id));
+ const addable = orgUsers.data?.filter((u) => !memberIds.has(u.id)) ?? [];
+
+ if (members.isError) return null;
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <p className="text-xs text-neutral-500 mb-3">{S.kbset.membersHint}</p>
+
+ {members.data?.members.length === 0 && (
+ <p className="text-xs text-neutral-600 mb-3">{S.kbset.noMembers}</p>
+ )}
+ {members.data?.members.map((m) => (
+ <div key={m.user_id} className="flex items-center gap-3 py-1.5">
+ <div className="min-w-0 flex-1">
+ <span className="text-sm text-neutral-200">{m.display_name}</span>
+ <span className="ml-2 text-xs text-neutral-500">{m.email}</span>
+ </div>
+ <Dropdown
+ size="sm"
+ className="w-24"
+ value={m.role}
+ onChange={(role) => setMember.mutate({ userId: m.user_id, role })}
+ options={KB_ROLES}
+ />
+ <button
+ onClick={() => remove.mutate(m.user_id)}
+ className="text-xs text-neutral-500 hover:text-rose-400"
+ >
+ {S.kbset.remove}
+ </button>
+ </div>
+ ))}
+
+ {addable.length > 0 && (
+ <div className="mt-3 flex gap-2 items-center border-t border-white/5 pt-3">
+ <SearchSelect
+ className="flex-1"
+ value={addUserId}
+ onChange={setAddUserId}
+ placeholder={S.kbset.addMember}
+ options={addable.map((u) => ({
+ value: u.id,
+ label: u.display_name,
+ hint: u.email,
+ }))}
+ />
+ <Dropdown className="w-24" value={addRole} onChange={setAddRole} options={KB_ROLES} />
+ <button
+ className="u-btn u-btn-primary px-3 py-1.5 text-xs"
+ disabled={!addUserId || setMember.isPending}
+ onClick={() => setMember.mutate({ userId: addUserId, role: addRole })}
+ >
+ {S.members.add}
+ </button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/pages/Legal.tsx b/web/src/pages/Legal.tsx
new file mode 100644
index 00000000..d6cb7bea
--- /dev/null
+++ b/web/src/pages/Legal.tsx
@@ -0,0 +1,70 @@
+/* 法务页(/privacy、/terms):登录页页脚可达的公共页面。
+ 自部署语境:运营方是部署它的组织,这里的文本是随软件附带的缺省政策,
+ 口径务求诚实(存了什么、什么情况下数据会离开服务器、删除的真实语义)。 */
+import { Link } from "@tanstack/react-router";
+import { S } from "../i18n";
+
+type LegalSection = {
+ h: string;
+ body: readonly string[];
+ bullets?: readonly string[];
+};
+type LegalDocData = {
+ title: string;
+ note: string;
+ sections: readonly LegalSection[];
+};
+
+function LegalPage({ doc }: { doc: LegalDocData }) {
+ return (
+ <div className="min-h-screen px-4 py-14">
+ <div className="mx-auto w-full max-w-xl">
+ <Link
+ to="/login"
+ className="text-xs text-neutral-500 hover:text-neutral-300 transition-colors"
+ >
+ {S.legal.backToSignIn}
+ </Link>
+ <h1
+ className="mt-6 text-3xl text-white"
+ style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.04em" }}
+ >
+ {doc.title}
+ </h1>
+ <p className="mt-3 text-xs text-neutral-600">{doc.note}</p>
+ <div className="mt-9 space-y-7">
+ {doc.sections.map((s) => (
+ <section key={s.h}>
+ <h2 className="text-sm font-semibold text-neutral-200">{s.h}</h2>
+ {s.body.map((p, i) => (
+ <p key={i} className="mt-2 text-sm leading-relaxed text-neutral-400">
+ {p}
+ </p>
+ ))}
+ {s.bullets && (
+ <ul className="mt-2 space-y-1.5">
+ {s.bullets.map((b, i) => (
+ <li
+ key={i}
+ className="relative pl-4 text-sm leading-relaxed text-neutral-400"
+ >
+ <span className="absolute left-0 text-neutral-600">–</span>
+ {b}
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function Privacy() {
+ return <LegalPage doc={S.legal.privacy} />;
+}
+export function Terms() {
+ return <LegalPage doc={S.legal.terms} />;
+}
diff --git a/web/src/pages/Library.tsx b/web/src/pages/Library.tsx
new file mode 100644
index 00000000..0db6f174
--- /dev/null
+++ b/web/src/pages/Library.tsx
@@ -0,0 +1,1448 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Link, useSearch } from "@tanstack/react-router";
+import {
+ BookOpen,
+ History as HistoryIcon,
+ KeyRound,
+ RefreshCw,
+ Search,
+ Settings as SettingsIcon,
+ Upload,
+ X,
+} from "lucide-react";
+import { api, type Doc, type SourceView } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { toast } from "../toast";
+import { Chip, type ChipTone, DangerConfirm, Loading, Pager, pageSlice } from "../ui";
+import {
+ KIND_ICON,
+ SOURCE_ICONS,
+ sourceIcon,
+ SourcesRail,
+ SYNC_DOT,
+ SYNCING_KINDS,
+ type LibrarySelection,
+} from "./SourcesRail";
+
+const PAGE_SIZE = 15;
+
+const STATUS_TONE: Record<string, ChipTone> = {
+ pending: "neutral",
+ parsing: "warn",
+ indexing: "warn",
+ embedding: "warn",
+ ready: "info",
+ failed: "danger",
+};
+
+const GRAPH_TONE: Record<string, ChipTone> = {
+ queued: "neutral",
+ extracting: "warn",
+ done: "violet",
+ failed: "danger",
+};
+
+/** 调度器产出的值:interval 与 cron 互斥。 */
+interface ScheduleValue {
+ sync_interval_minutes: number | null;
+ sync_cron: string | null;
+}
+
+const pad2 = (n: number | string) => String(n).padStart(2, "0");
+
+/** 同步日程的人话展示(advanced 自定义表达式按原样显示)。 */
+function scheduleLabel(s: SourceView): string {
+ if (s.sync_cron) {
+ const daily = s.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/);
+ if (daily) return S.library.schedule.dailyAt(`${pad2(daily[2])}:${pad2(daily[1])}`);
+ const weekly = s.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* ([A-Za-z,-]+)$/);
+ if (weekly) return `${weekly[3]} ${pad2(weekly[2])}:${pad2(weekly[1])}`;
+ return s.sync_cron;
+ }
+ if (s.sync_interval_minutes) return S.library.intervalEvery(s.sync_interval_minutes);
+ return S.library.intervalManual;
+}
+
+type ScheduleMode = "manual" | "interval" | "daily" | "weekly" | "advanced";
+
+/** 已存日程 → 选择器初始状态(编辑模式回显;识别不了的 cron 落到 Advanced)。 */
+function scheduleToPickerState(initial?: ScheduleValue) {
+ const base = {
+ mode: "manual" as ScheduleMode,
+ every: 30,
+ unit: "minutes" as "minutes" | "hours",
+ time: "09:00",
+ days: new Set([0]),
+ cron: "",
+ };
+ if (!initial) return base;
+ if (initial.sync_cron) {
+ const daily = initial.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* \*$/);
+ if (daily)
+ return { ...base, mode: "daily" as ScheduleMode, time: `${pad2(daily[2])}:${pad2(daily[1])}` };
+ const weekly = initial.sync_cron.match(/^(\d{1,2}) (\d{1,2}) \* \* ([A-Za-z,]+)$/);
+ if (weekly) {
+ const idx = weekly[3]
+ .split(",")
+ .map((n) => (S.library.schedule.daysShort as readonly string[]).indexOf(n))
+ .filter((i) => i >= 0);
+ if (idx.length)
+ return {
+ ...base,
+ mode: "weekly" as ScheduleMode,
+ time: `${pad2(weekly[2])}:${pad2(weekly[1])}`,
+ days: new Set(idx),
+ };
+ }
+ return { ...base, mode: "advanced" as ScheduleMode, cron: initial.sync_cron };
+ }
+ if (initial.sync_interval_minutes) {
+ const m = initial.sync_interval_minutes;
+ return m % 60 === 0
+ ? { ...base, mode: "interval" as ScheduleMode, every: m / 60, unit: "hours" as const }
+ : { ...base, mode: "interval" as ScheduleMode, every: m, unit: "minutes" as const };
+ }
+ return base;
+}
+
+/** 可视化同步日程选择器:Manual / Interval / Daily / Weekly 构建,Advanced 才暴露 cron。 */
+function SchedulePicker({
+ onChange,
+ initial,
+}: {
+ onChange: (v: ScheduleValue) => void;
+ /** 编辑模式的既有日程;新建缺省从 Manual 起步 */
+ initial?: ScheduleValue;
+}) {
+ type Mode = ScheduleMode;
+ const [init] = useState(() => scheduleToPickerState(initial));
+ const [mode, setMode] = useState<Mode>(init.mode);
+ const [every, setEvery] = useState(init.every);
+ const [unit, setUnit] = useState<"minutes" | "hours">(init.unit);
+ const [time, setTime] = useState(init.time);
+ const [days, setDays] = useState<Set<number>>(init.days);
+ const [cron, setCron] = useState(init.cron);
+
+ const emit = (
+ m: Mode,
+ v: { every?: number; unit?: string; time?: string; days?: Set<number>; cron?: string },
+ ) => {
+ const t = v.time ?? time;
+ const [hh, mm] = t.split(":").map(Number);
+ // 时间格式未成形时(手输中途)不更新日程,保留上一个有效值
+ if ((m === "daily" || m === "weekly") && (Number.isNaN(hh) || Number.isNaN(mm))) return;
+ switch (m) {
+ case "manual":
+ return onChange({ sync_interval_minutes: null, sync_cron: null });
+ case "interval": {
+ const n = Math.max(1, v.every ?? every);
+ const u = v.unit ?? unit;
+ return onChange({
+ sync_interval_minutes: u === "hours" ? n * 60 : n,
+ sync_cron: null,
+ });
+ }
+ case "daily":
+ return onChange({ sync_interval_minutes: null, sync_cron: `${mm} ${hh} * * *` });
+ case "weekly": {
+ const ds = [...(v.days ?? days)].sort();
+ const names = ds.map((i) => S.library.schedule.daysShort[i]).join(",");
+ return onChange({
+ sync_interval_minutes: null,
+ sync_cron: ds.length ? `${mm} ${hh} * * ${names}` : null,
+ });
+ }
+ case "advanced":
+ return onChange({
+ sync_interval_minutes: null,
+ sync_cron: (v.cron ?? cron).trim() || null,
+ });
+ }
+ };
+
+ const modes: { key: Mode; label: string }[] = [
+ { key: "manual", label: S.library.schedule.manual },
+ { key: "interval", label: S.library.schedule.interval },
+ { key: "daily", label: S.library.schedule.daily },
+ { key: "weekly", label: S.library.schedule.weekly },
+ { key: "advanced", label: S.library.schedule.advanced },
+ ];
+
+ return (
+ <div>
+ <div className="flex rounded-lg overflow-hidden border border-white/10 mb-2">
+ {modes.map(({ key, label }) => (
+ <button
+ key={key}
+ onClick={() => {
+ setMode(key);
+ emit(key, {});
+ }}
+ className={`flex-1 px-2 py-1.5 text-[11px] transition-colors ${
+ mode === key
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {mode === "interval" && (
+ <div className="flex items-center gap-2 text-sm text-neutral-400">
+ {S.library.schedule.every}
+ <input
+ type="number"
+ min={1}
+ className="input-dark u-input-plain w-16 px-2 py-1.5 text-sm u-num text-center"
+ value={every}
+ onChange={(e) => {
+ const n = Number(e.target.value) || 1;
+ setEvery(n);
+ emit("interval", { every: n });
+ }}
+ />
+ {/* 两个选项不配下拉:分段切换,与上方模式条同配方 */}
+ <div className="flex rounded-lg overflow-hidden border border-white/10">
+ {(["minutes", "hours"] as const).map((u) => (
+ <button
+ key={u}
+ onClick={() => {
+ setUnit(u);
+ emit("interval", { unit: u });
+ }}
+ className={`px-3 py-1.5 text-xs transition-colors ${
+ unit === u
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
+ }`}
+ >
+ {S.library.schedule[u]}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {(mode === "daily" || mode === "weekly") && (
+ <div className="space-y-2">
+ {mode === "weekly" && (
+ <div className="flex gap-1">
+ {S.library.schedule.daysShort.map((d, i) => (
+ <button
+ key={d}
+ onClick={() => {
+ const next = new Set(days);
+ if (next.has(i)) next.delete(i);
+ else next.add(i);
+ setDays(next);
+ emit("weekly", { days: next });
+ }}
+ className={`flex-1 rounded-lg px-1 py-1.5 text-[11px] transition-colors ${
+ days.has(i)
+ ? "bg-white text-black font-medium"
+ : "bg-white/[0.05] text-neutral-500 hover:text-neutral-300"
+ }`}
+ >
+ {d}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center gap-2 text-sm text-neutral-400">
+ {S.library.schedule.at}
+ {/* 24h 纯文本输入:原生 time 控件块头大且跟随系统语言("上午 09:00") */}
+ <input
+ className={`input-dark u-input-plain w-[4.2rem] px-2 py-1.5 text-sm u-num text-center ${
+ /^([01]?\d|2[0-3]):[0-5]\d$/.test(time) ? "" : "!border-[var(--u-danger)]"
+ }`}
+ placeholder="09:00"
+ value={time}
+ onChange={(e) => {
+ const t = e.target.value;
+ setTime(t);
+ if (/^([01]?\d|2[0-3]):[0-5]\d$/.test(t)) emit(mode, { time: t });
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ {mode === "advanced" && (
+ <div>
+ {/* 表达式用 mono,placeholder 回默认字体(u-placeholder-sans) */}
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono u-placeholder-sans"
+ placeholder={S.library.schedule.cronPlaceholder}
+ value={cron}
+ onChange={(e) => {
+ setCron(e.target.value);
+ emit("advanced", { cron: e.target.value });
+ }}
+ />
+ <a
+ href={S.library.schedule.cronDocsUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="mt-1.5 inline-block text-[10.5px] text-neutral-500 underline decoration-white/20 underline-offset-2 hover:text-neutral-300 transition-colors"
+ >
+ {S.library.schedule.whatIsCron}
+ </a>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function Library() {
+ const { kb } = useKb();
+ const queryClient = useQueryClient();
+ const fileInput = useRef<HTMLInputElement>(null);
+ // 从文档查看页的来源栏跳回时带 ?src= 定位到对应文件夹
+ const { src } = useSearch({ from: "/app/library" });
+ const [dragging, setDragging] = useState(false);
+ const [selection, setSelection] = useState<LibrarySelection>(src ?? "all");
+ const [adding, setAdding] = useState(false);
+ const [editing, setEditing] = useState(false);
+ // api 来源密钥弹窗(随时可查看/轮换)
+ const [tokenReveal, setTokenReveal] = useState<{ sourceId: string } | null>(null);
+ const [cleaning, setCleaning] = useState(false);
+ const [showHistory, setShowHistory] = useState(false);
+ const [page, setPage] = useState(0);
+ const [filter, setFilter] = useState("");
+
+ // 切换文件夹回到第一页、清空过滤、退出历史视图
+ useEffect(() => {
+ setPage(0);
+ setFilter("");
+ setShowHistory(false);
+ }, [selection]);
+ // 过滤词变化回到第一页
+ useEffect(() => setPage(0), [filter]);
+
+ // 状态变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询
+ const docs = useQuery({
+ queryKey: ["documents", kb?.id],
+ queryFn: () => api.documents(kb!.id),
+ enabled: !!kb,
+ });
+ const sources = useQuery({
+ queryKey: ["sources", kb?.id],
+ queryFn: () => api.sources(kb!.id),
+ enabled: !!kb,
+ });
+
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey: ["documents", kb?.id] });
+ queryClient.invalidateQueries({ queryKey: ["sources", kb?.id] });
+ };
+
+ const upload = useMutation({
+ // 选中 folder 来源时,上传直接归入该文件夹
+ mutationFn: (files: FileList | File[]) => {
+ const folder = sources.data?.sources.find(
+ (s) => s.id === selection && s.kind === "folder",
+ );
+ return api.upload(kb!.id, Array.from(files), folder?.id);
+ },
+ onSuccess: invalidate,
+ });
+ const remove = useMutation({ mutationFn: (id: string) => api.deleteDocument(id), onSuccess: invalidate });
+ const extract = useMutation({ mutationFn: (id: string) => api.extractDocument(id), onSuccess: invalidate });
+ const reprocess = useMutation({
+ mutationFn: (id: string) => api.reprocessDocument(id),
+ onSuccess: invalidate,
+ });
+ const syncNow = useMutation({
+ mutationFn: (sourceId: string) => api.syncSource(kb!.id, sourceId),
+ onSuccess: invalidate,
+ });
+ const removeSource = useMutation({
+ mutationFn: (sourceId: string) => api.deleteSource(kb!.id, sourceId),
+ onSuccess: () => {
+ setSelection("all");
+ invalidate();
+ },
+ });
+ const cleanupMissing = useMutation({
+ mutationFn: (sourceId: string) => api.cleanupMissing(kb!.id, sourceId),
+ onSuccess: () => {
+ setCleaning(false);
+ invalidate();
+ },
+ });
+
+ // 只有手动语义的目的地可上传:All/Uploads/folder。拉取型来源(url/rss/api/custom)
+ // 由同步填充,手动塞文件会在下次同步时变成"来源里不存在"的孤儿
+ const canUpload =
+ selection === "all" ||
+ selection === "uploads" ||
+ sources.data?.sources.find((s) => s.id === selection)?.kind === "folder";
+
+ const onDrop = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+ setDragging(false);
+ if (!canUpload) return;
+ if (e.dataTransfer.files.length && kb) upload.mutate(e.dataTransfer.files);
+ },
+ [kb, upload, canUpload],
+ );
+
+ if (!kb) return <Loading>{S.nav.loading}</Loading>;
+
+ const allDocs = docs.data ?? [];
+ const sourceList = sources.data?.sources ?? [];
+ const visibleDocs =
+ selection === "all"
+ ? allDocs
+ : selection === "uploads"
+ ? allDocs.filter((d) => !d.source_id)
+ : allDocs.filter((d) => d.source_id === selection);
+ const selectedSource = sourceList.find((s) => s.id === selection);
+
+ const query = filter.trim().toLowerCase();
+ const filteredDocs = query
+ ? visibleDocs.filter((d) => d.filename.toLowerCase().includes(query))
+ : visibleDocs;
+
+ const { rows: pagedDocs, safe: safePage } = pageSlice(filteredDocs, page, PAGE_SIZE);
+
+ return (
+ <div className="h-full flex">
+ <SourcesRail
+ kbId={kb.id}
+ active={selection}
+ onSelect={setSelection}
+ onAdd={() => setAdding(true)}
+ />
+
+ {/* 文档区(scrollbar-gutter 常驻:视图切换时滚动条出没不再引起水平抖动) */}
+ <div
+ className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6 [scrollbar-gutter:stable]"
+ onDragOver={(e) => {
+ e.preventDefault();
+ if (canUpload) setDragging(true);
+ }}
+ onDragLeave={() => setDragging(false)}
+ onDrop={onDrop}
+ >
+ {/* 工作页居左:与 Review/Ontology 同规——左缘随栏起步,切页不跳 */}
+ <div className="max-w-4xl">
+ <div className="flex items-center justify-between mb-4">
+ <h1 className="u-title text-lg">
+ {selectedSource?.name ??
+ (selection === "uploads" ? S.library.uploads : S.library.title)}
+ </h1>
+ <div className="flex items-center gap-2">
+ {/* 历史视图下过滤框只藏不撤(invisible 保留占位),标题行高度不塌、不抖 */}
+ <div className={`relative ${showHistory ? "invisible" : ""}`}>
+ <Search
+ size={13}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
+ />
+ <input
+ className="input-dark w-52 pl-8 pr-7 py-1.5 text-[13px]"
+ placeholder={S.library.filterPlaceholder}
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ onKeyDown={(e) => e.key === "Escape" && setFilter("")}
+ />
+ {filter && (
+ <button
+ onClick={() => setFilter("")}
+ className="absolute right-2 top-1/2 -translate-y-1/2 text-neutral-500 hover:text-neutral-200"
+ >
+ <X size={12} />
+ </button>
+ )}
+ </div>
+ {canUpload && (
+ <button
+ onClick={() => fileInput.current?.click()}
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs flex items-center gap-1.5 shrink-0"
+ >
+ <Upload size={12} />
+ {S.library.upload}
+ </button>
+ )}
+ </div>
+ <input
+ ref={fileInput}
+ type="file"
+ multiple
+ hidden
+ accept=".pdf,.docx,.xlsx,.xls,.ods,.pptx,.md,.txt,.html,.htm,.csv,.tsv,.json,.yaml,.yml,.xml,.log"
+ onChange={(e) => e.target.files?.length && upload.mutate(e.target.files)}
+ />
+ </div>
+
+ {selectedSource && (
+ <SourceBar
+ kbId={kb.id}
+ source={selectedSource}
+ syncing={syncNow.isPending}
+ historyOpen={showHistory}
+ onToggleHistory={() => setShowHistory((v) => !v)}
+ onSync={() => syncNow.mutate(selectedSource.id)}
+ onEdit={() => setEditing(true)}
+ onCleanup={() => setCleaning(true)}
+ onToken={() => setTokenReveal({ sourceId: selectedSource.id })}
+ />
+ )}
+
+ {upload.isPending && (
+ <div className="mb-3 text-sm text-[var(--u-warn)]">{S.library.uploading}</div>
+ )}
+ {upload.isError && (
+ <div className="mb-3 text-sm text-rose-400">
+ {S.library.uploadFailed}: {String((upload.error as Error).message)}
+ </div>
+ )}
+
+ {showHistory && selectedSource ? (
+ <RunsPanel kbId={kb.id} sourceId={selectedSource.id} />
+ ) : (
+ <>
+ <div className={`glass rounded-2xl glass-hover ${dragging ? "u-highlight" : ""}`}>
+ {filteredDocs.length ? (
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="text-left text-xs text-neutral-500 border-b border-white/10">
+ <th className="px-4 py-2.5 font-medium">{S.library.colFile}</th>
+ {selection === "all" && (
+ <th className="px-4 py-2.5 font-medium">{S.library.colSource}</th>
+ )}
+ <th className="px-4 py-2.5 font-medium">{S.library.colStatus}</th>
+ <th className="px-4 py-2.5 font-medium">{S.library.colGraph}</th>
+ <th className="px-4 py-2.5 font-medium">{S.library.colChunks}</th>
+ <th className="px-4 py-2.5 font-medium">{S.library.colSize}</th>
+ <th className="px-4 py-2.5"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {pagedDocs.map((d) => (
+ <DocRow
+ key={d.id}
+ doc={d}
+ source={
+ selection === "all"
+ ? (sourceList.find((s) => s.id === d.source_id) ?? null)
+ : undefined
+ }
+ onDelete={() => remove.mutate(d.id)}
+ onExtract={() => extract.mutate(d.id)}
+ onReprocess={() => reprocess.mutate(d.id)}
+ />
+ ))}
+ </tbody>
+ </table>
+ ) : query && visibleDocs.length ? (
+ <div className="py-20 text-center text-sm text-neutral-500">
+ {S.library.filterNoMatch}
+ </div>
+ ) : (
+ <div className="py-20 text-center text-sm text-neutral-500">
+ {canUpload ? (
+ <>
+ {S.library.dropHint}
+ <div className="mt-2 text-xs text-neutral-600">{S.library.formats}</div>
+ </>
+ ) : (
+ S.library.emptyPull
+ )}
+ </div>
+ )}
+ </div>
+
+ <Pager
+ total={filteredDocs.length}
+ pageSize={PAGE_SIZE}
+ page={safePage}
+ onPage={setPage}
+ />
+ </>
+ )}
+ </div>
+ </div>
+
+ {adding && (
+ <SourceModal
+ kbId={kb.id}
+ onDone={(id, isApi) => {
+ setAdding(false);
+ if (id) setSelection(id);
+ // api 来源建好直接打开密钥弹窗(onboarding:端点 + 密钥一步拿全)
+ if (id && isApi) setTokenReveal({ sourceId: id });
+ invalidate();
+ }}
+ />
+ )}
+ {tokenReveal && (
+ <TokenModal
+ kbId={kb.id}
+ sourceId={tokenReveal.sourceId}
+ onClose={() => setTokenReveal(null)}
+ />
+ )}
+ {editing && selectedSource && (
+ <SourceEditModal
+ kbId={kb.id}
+ source={selectedSource}
+ onDone={() => {
+ setEditing(false);
+ invalidate();
+ }}
+ onDelete={() => {
+ setEditing(false);
+ removeSource.mutate(selectedSource.id);
+ }}
+ />
+ )}
+ {cleaning && selectedSource && (
+ <DangerConfirm
+ title={S.library.cleanupTitle}
+ hint={S.library.cleanupHint(selectedSource.missing_count, selectedSource.name)}
+ confirmLabel={S.library.cleanupConfirm}
+ cancelLabel={S.library.cancel}
+ busy={cleanupMissing.isPending}
+ onConfirm={() => cleanupMissing.mutate(selectedSource.id)}
+ onCancel={() => setCleaning(false)}
+ />
+ )}
+ </div>
+ );
+}
+
+/** 选中来源的状态条:同步状态 / 上次同步 / History 切换 / Sync now / 设置。 */
+function SourceBar({
+ kbId,
+ source,
+ syncing,
+ historyOpen,
+ onToggleHistory,
+ onSync,
+ onEdit,
+ onCleanup,
+ onToken,
+}: {
+ kbId: string;
+ source: SourceView;
+ syncing: boolean;
+ historyOpen: boolean;
+ onToggleHistory: () => void;
+ onSync: () => void;
+ onEdit: () => void;
+ onCleanup: () => void;
+ onToken: () => void;
+}) {
+ const isPull = SYNCING_KINDS.has(source.kind);
+ const isApi = source.kind === "api";
+ const busy = source.last_sync_status === "running" || source.last_sync_status === "queued";
+ // 历史数据的 config 可能是 jsonb null(缺省 Value::Null 落库所致)——防御性兜底
+ const cfg = source.config ?? {};
+ const configSummary =
+ cfg.feed_url ?? cfg.endpoint ?? (cfg.urls ? `${cfg.urls.length} URLs` : "");
+
+ return (
+ <div className="glass rounded-xl mb-3">
+ <div className="px-4 py-2.5 flex items-center gap-3 text-xs">
+ {/* api 与拉取型同一状态语汇:点 + 状态 + 时刻 + 产出/错误;
+ 端点是一次性集成信息,放 Token 弹窗,不占常驻条 */}
+ {(isPull || isApi) && (
+ <>
+ <span
+ className={`h-1.5 w-1.5 rounded-full shrink-0 ${SYNC_DOT[source.last_sync_status]}`}
+ />
+ <span className="text-neutral-300 whitespace-nowrap shrink-0">
+ {isApi
+ ? S.library.pushStatus[source.last_sync_status]
+ : S.library.syncStatus[source.last_sync_status]}
+ </span>
+ {source.last_sync_at && (
+ <span className="text-neutral-600 u-num whitespace-nowrap shrink-0">
+ {source.last_sync_at.slice(0, 16).replace("T", " ")}
+ </span>
+ )}
+ {source.last_sync_status === "ok" && source.last_sync_added > 0 && (
+ <span className="text-[var(--u-ok)]">
+ {S.library.lastSyncAdded(source.last_sync_added)}
+ </span>
+ )}
+ {source.last_sync_error && (
+ <span className="text-rose-400 truncate min-w-0" title={source.last_sync_error}>
+ {source.last_sync_error}
+ </span>
+ )}
+ {isPull && (
+ <>
+ <span className="text-neutral-600 truncate min-w-0">{configSummary}</span>
+ <span className="text-neutral-600 shrink-0 u-num">{scheduleLabel(source)}</span>
+ </>
+ )}
+ </>
+ )}
+ {!isPull && !isApi && (
+ <span className="text-neutral-600 truncate min-w-0">
+ {S.library.sourceKindHints[source.kind as "folder"] ?? ""}
+ </span>
+ )}
+ <div className="ml-auto flex items-center gap-2 shrink-0">
+ {/* 集成型来源(custom 拉取 / api 推送):接口文档随手可达 */}
+ {(source.kind === "custom" || source.kind === "api") && (
+ <Link
+ to="/docs/$slug"
+ params={{ slug: "ingest" }}
+ target="_blank"
+ title={S.library.ingestGuideTitle}
+ className="u-btn u-btn-ghost px-2 py-1"
+ >
+ <BookOpen size={12} />
+ </Link>
+ )}
+ {source.missing_count > 0 && (
+ <button
+ onClick={onCleanup}
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs !text-[var(--u-warn)]"
+ >
+ {S.library.cleanupMissing(source.missing_count)}
+ </button>
+ )}
+ {/* History 对拉取型与 api 推送型都开放:推送失败(格式错等)也记 run */}
+ {(isPull || source.kind === "api") && (
+ /* 激活态用反色(与弹窗类型 tab、图标选中同一语汇),一眼可辨 */
+ <button
+ onClick={onToggleHistory}
+ className={`u-btn px-2.5 py-1 text-xs flex items-center gap-1.5 ${
+ historyOpen ? "u-btn-primary" : "u-btn-ghost"
+ }`}
+ >
+ <HistoryIcon size={11} />
+ {S.library.syncHistory}
+ </button>
+ )}
+ {isPull && (
+ <button
+ onClick={onSync}
+ disabled={busy || syncing}
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
+ >
+ <RefreshCw size={11} className={busy ? "animate-spin" : ""} />
+ {S.library.syncNow}
+ </button>
+ )}
+ {source.kind === "api" && (
+ <button
+ onClick={onToken}
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs flex items-center gap-1.5"
+ >
+ <KeyRound size={11} />
+ {S.library.viewToken}
+ </button>
+ )}
+ <button
+ onClick={onEdit}
+ title={S.library.sourceSettings}
+ className="u-btn u-btn-ghost px-2 py-1"
+ >
+ <SettingsIcon size={12} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** api 来源密钥:随时可查(Editor 专用端点),内置轮换。 */
+function TokenModal({
+ kbId,
+ sourceId,
+ onClose,
+}: {
+ kbId: string;
+ sourceId: string;
+ onClose: () => void;
+}) {
+ const queryClient = useQueryClient();
+ const tokenQuery = useQuery({
+ queryKey: ["sourceToken", kbId, sourceId],
+ queryFn: () => api.sourceToken(kbId, sourceId),
+ });
+ const rotate = useMutation({
+ mutationFn: () => api.rotateSourceToken(kbId, sourceId),
+ onSuccess: (r) => {
+ queryClient.setQueryData(["sourceToken", kbId, sourceId], { ingest_token: r.ingest_token });
+ toast.success(S.toast.saved);
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+ const token = tokenQuery.data?.ingest_token ?? null;
+
+ const copy = (text: string, msg: string) =>
+ navigator.clipboard.writeText(text).then(() => toast.success(msg)).catch(() => {});
+ const endpoint = `${location.origin}/api/v1/sources/${sourceId}/ingest`;
+ return (
+ <div
+ className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
+ onMouseDown={(e) => {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ >
+ <div className="glass-strong w-[32rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl">
+ <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
+ <h2 className="u-title text-[15px] flex items-center gap-2">
+ <KeyRound size={14} className="text-neutral-400" />
+ {S.library.tokenTitle}
+ </h2>
+ <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
+ <X size={15} />
+ </button>
+ </div>
+ <div className="px-5 py-4 space-y-3">
+ {tokenQuery.isPending ? (
+ <p className="text-sm text-neutral-500">{S.nav.loading}</p>
+ ) : token ? (
+ <>
+ <button
+ onClick={() => copy(token, S.library.tokenCopied)}
+ title={S.library.copyEndpoint}
+ className="w-full text-left font-mono text-[12.5px] text-neutral-200 bg-white/[0.05] border border-white/10 hover:border-white/25 rounded-lg px-3 py-2.5 break-all transition-colors"
+ >
+ {token}
+ </button>
+ <p className="text-[11px] leading-relaxed text-neutral-500">
+ {S.library.tokenWarning}
+ </p>
+ <div>
+ <p className="mb-1 text-[11px] text-neutral-500">{S.library.tokenUsage}</p>
+ <button
+ onClick={() => copy(endpoint, S.library.endpointCopied)}
+ title={S.library.copyEndpoint}
+ className="w-full text-left font-mono text-[11.5px] text-neutral-400 hover:text-neutral-200 bg-white/[0.03] border border-white/10 rounded-lg px-3 py-2 break-all transition-colors"
+ >
+ POST {endpoint}
+ {"\n"}Authorization: Bearer &lt;token&gt;
+ </button>
+ </div>
+ </>
+ ) : (
+ <p className="text-sm text-neutral-500">{S.library.noToken}</p>
+ )}
+ </div>
+ <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
+ <button
+ className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs flex items-center gap-1.5"
+ disabled={rotate.isPending || tokenQuery.isPending}
+ onClick={() => rotate.mutate()}
+ >
+ <RefreshCw size={11} className={rotate.isPending ? "animate-spin" : ""} />
+ {token ? S.library.rotateToken : S.library.generateToken}
+ </button>
+ <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onClose}>
+ {S.library.close}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** History 视图:占据文件列表位置的同步运行记录(再点 History 切回)。 */
+function RunsPanel({ kbId, sourceId }: { kbId: string; sourceId: string }) {
+ const runs = useQuery({
+ queryKey: ["sourceRuns", kbId, sourceId],
+ queryFn: () => api.sourceRuns(kbId, sourceId),
+ });
+ const list = runs.data?.runs ?? [];
+
+ return (
+ <div className="glass rounded-2xl">
+ {runs.isLoading ? (
+ <div className="py-20 text-center text-sm text-neutral-500">{S.nav.loading}</div>
+ ) : list.length === 0 ? (
+ <div className="py-20 text-center text-sm text-neutral-500">{S.library.noRuns}</div>
+ ) : (
+ <div className="px-4 py-2">
+ {list.map((r) => (
+ <div
+ key={r.id}
+ className="flex items-center gap-3 py-2 text-xs border-b border-white/5 last:border-0"
+ >
+ <span
+ className={`h-1.5 w-1.5 rounded-full shrink-0 ${
+ r.status === "ok"
+ ? "bg-[var(--u-ok)]"
+ : r.status === "failed"
+ ? "bg-[var(--u-danger)]"
+ : "bg-[var(--u-warn)] animate-pulse"
+ }`}
+ />
+ <span className="u-num text-neutral-400 whitespace-nowrap shrink-0">
+ {r.started_at.slice(0, 16).replace("T", " ")}
+ </span>
+ <span className="text-neutral-500 whitespace-nowrap shrink-0">
+ {r.created_docs > 0 && S.library.runNew(r.created_docs)}
+ {r.created_docs > 0 && r.updated_docs > 0 && " · "}
+ {r.updated_docs > 0 && S.library.runUpdated(r.updated_docs)}
+ {r.status === "ok" && r.created_docs === 0 && r.updated_docs === 0 && (
+ <span className="text-neutral-600">{S.library.runNothing}</span>
+ )}
+ </span>
+ {r.error && (
+ <span className="text-rose-400 truncate min-w-0" title={r.error}>
+ {r.error}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** 新建来源弹窗:类型 → 名称/图标 → 类型专属配置 → 同步周期。 */
+function SourceModal({
+ kbId,
+ onDone,
+}: {
+ kbId: string;
+ /** isApi=true 时父级紧接着打开密钥弹窗 */
+ onDone: (id?: string, isApi?: boolean) => void;
+}) {
+ const [kind, setKind] = useState<"folder" | "url" | "rss" | "custom" | "api">("folder");
+ const [name, setName] = useState("");
+ const [icon, setIcon] = useState<string | null>(null);
+ const [urls, setUrls] = useState("");
+ const [feedUrl, setFeedUrl] = useState("");
+ const [endpoint, setEndpoint] = useState("");
+ const [authHeader, setAuthHeader] = useState("");
+ const [schedule, setSchedule] = useState<ScheduleValue>({
+ sync_interval_minutes: null,
+ sync_cron: null,
+ });
+ // folder = 纯容器、api = 推送型:都没有同步日程
+ const syncing = kind === "url" || kind === "rss" || kind === "custom";
+
+ const create = useMutation({
+ mutationFn: () => {
+ const config =
+ kind === "url"
+ ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
+ : kind === "rss"
+ ? { feed_url: feedUrl.trim() }
+ : kind === "custom"
+ ? {
+ endpoint: endpoint.trim(),
+ ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
+ }
+ : {};
+ return api.createSource(kbId, {
+ kind,
+ name: name.trim(),
+ config,
+ // 内置类型图标固定,只有 custom 允许自选
+ icon: kind === "custom" ? icon : null,
+ // folder/api 无同步语义:日程强制留空
+ ...(syncing ? schedule : { sync_interval_minutes: null, sync_cron: null }),
+ });
+ },
+ onSuccess: (data) => onDone(data.source.id, kind === "api"),
+ });
+
+ const valid =
+ name.trim() &&
+ (kind === "url"
+ ? urls.trim()
+ : kind === "rss"
+ ? feedUrl.trim()
+ : kind === "custom"
+ ? endpoint.trim()
+ : true);
+
+ // 注意用 div 而非 label:label 会把 :hover/click 转发给内部第一个可标记控件
+ //(button 也算),导致图标网格/日程选择器悬停时第一个按钮常亮
+ const field = (label: string, node: React.ReactNode) => (
+ <div className="mb-3">
+ <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
+ {node}
+ </div>
+ );
+
+ return (
+ <div
+ className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
+ onMouseDown={(e) => {
+ if (e.target === e.currentTarget) onDone();
+ }}
+ >
+ <div className="glass-strong w-[30rem] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-4rem)] overflow-y-auto u-scroll rounded-2xl shadow-2xl">
+ <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
+ <h2 className="u-title text-[15px]">{S.library.newSourceTitle}</h2>
+ <button onClick={() => onDone()} className="text-neutral-500 hover:text-neutral-200">
+ <X size={15} />
+ </button>
+ </div>
+
+ <div className="px-5 py-4">
+ {/* 类型 */}
+ <div className="flex gap-2 mb-2">
+ {(["folder", "url", "rss", "api", "custom"] as const).map((k) => {
+ const Icon = KIND_ICON[k];
+ return (
+ <button
+ key={k}
+ onClick={() => setKind(k)}
+ className={`u-btn flex-1 px-3 py-2 text-xs flex items-center justify-center gap-1.5 ${
+ kind === k ? "u-btn-primary" : "u-btn-ghost"
+ }`}
+ >
+ <Icon size={12} />
+ {S.library.sourceKinds[k]}
+ </button>
+ );
+ })}
+ </div>
+ {/* 类型自解释:一行说明;接口细节移入内置文档,弹窗只留链接 */}
+ <p className="mb-4 text-[11px] leading-relaxed text-neutral-500">
+ {S.library.sourceKindHints[kind]}
+ {kind === "custom" && (
+ <>
+ {" "}
+ <Link
+ to="/docs/$slug"
+ params={{ slug: "ingest" }}
+ target="_blank"
+ className="u-link"
+ >
+ {S.library.ingestGuide}
+ </Link>
+ </>
+ )}
+ </p>
+
+ {field(
+ S.library.sourceName,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ autoFocus
+ />,
+ )}
+
+ {/* 内置类型图标固定;只有 custom 开放图标选择 */}
+ {kind === "custom" &&
+ field(
+ S.library.iconLabel,
+ <div className="grid grid-cols-10 gap-1">
+ {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
+ <button
+ key={key}
+ onClick={() => setIcon(icon === key ? null : key)}
+ title={key}
+ className={`h-8 grid place-items-center rounded-lg transition-colors ${
+ icon === key
+ ? "bg-white text-black"
+ : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
+ }`}
+ >
+ <Icon size={14} />
+ </button>
+ ))}
+ </div>,
+ )}
+
+ {kind === "custom" && (
+ <>
+ {field(
+ S.library.endpointField,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono"
+ placeholder="https://your-service/utopia-feed"
+ value={endpoint}
+ onChange={(e) => setEndpoint(e.target.value)}
+ />,
+ )}
+ {field(
+ S.library.authHeaderField,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono"
+ type="password"
+ placeholder="Bearer sk-…"
+ value={authHeader}
+ onChange={(e) => setAuthHeader(e.target.value)}
+ />,
+ )}
+ </>
+ )}
+
+ {kind === "url" &&
+ field(
+ S.library.urlsField,
+ <textarea
+ className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
+ value={urls}
+ onChange={(e) => setUrls(e.target.value)}
+ />,
+ )}
+ {kind === "rss" &&
+ field(
+ S.library.feedUrl,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono"
+ value={feedUrl}
+ onChange={(e) => setFeedUrl(e.target.value)}
+ />,
+ )}
+
+ {syncing && field(S.library.interval, <SchedulePicker onChange={setSchedule} />)}
+
+ {create.isError && (
+ <p className="text-xs text-rose-400 mb-2">{(create.error as Error).message}</p>
+ )}
+ </div>
+
+ <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
+ <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={() => onDone()}>
+ {S.library.cancel}
+ </button>
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!valid || create.isPending}
+ onClick={() => create.mutate()}
+ >
+ {S.library.createSource}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** 来源设置弹窗:改名/图标(仅 custom)/摄取配置/日程;类型不可改;底部 danger zone。 */
+function SourceEditModal({
+ kbId,
+ source,
+ onDone,
+ onDelete,
+}: {
+ kbId: string;
+ source: SourceView;
+ onDone: () => void;
+ onDelete: () => void;
+}) {
+ const kind = source.kind;
+ const cfg = source.config ?? {};
+ const [name, setName] = useState(source.name);
+ const [icon, setIcon] = useState<string | null>(source.icon);
+ const [urls, setUrls] = useState((cfg.urls ?? []).join("\n"));
+ const [feedUrl, setFeedUrl] = useState(cfg.feed_url ?? "");
+ const [endpoint, setEndpoint] = useState(cfg.endpoint ?? "");
+ const [authHeader, setAuthHeader] = useState("");
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+ const [schedule, setSchedule] = useState<ScheduleValue>({
+ sync_interval_minutes: source.sync_interval_minutes,
+ sync_cron: source.sync_cron,
+ });
+ const syncing = SYNCING_KINDS.has(kind);
+ const KindIcon = KIND_ICON[kind as keyof typeof KIND_ICON] ?? Upload;
+
+ // 摄取配置是否有改动——有则展示"旧文档去留"说明
+ const ingestChanged =
+ (kind === "url" && urls.trim() !== (cfg.urls ?? []).join("\n").trim()) ||
+ (kind === "rss" && feedUrl.trim() !== (cfg.feed_url ?? "")) ||
+ (kind === "custom" && endpoint.trim() !== (cfg.endpoint ?? ""));
+
+ const save = useMutation({
+ mutationFn: () => {
+ const config =
+ kind === "url"
+ ? { urls: urls.split("\n").map((u) => u.trim()).filter(Boolean) }
+ : kind === "rss"
+ ? { feed_url: feedUrl.trim() }
+ : kind === "custom"
+ ? {
+ endpoint: endpoint.trim(),
+ // 留空 = 后端保留库里原值(凭据只进不出)
+ ...(authHeader.trim() ? { auth_header: authHeader.trim() } : {}),
+ }
+ : undefined;
+ return api.updateSource(kbId, source.id, {
+ name: name.trim(),
+ ...(kind === "custom" && icon ? { icon } : {}),
+ ...(config ? { config } : {}),
+ ...(syncing ? { schedule } : {}),
+ });
+ },
+ onSuccess: () => onDone(),
+ });
+
+ const valid =
+ name.trim() &&
+ (kind === "url"
+ ? urls.trim()
+ : kind === "rss"
+ ? feedUrl.trim()
+ : kind === "custom"
+ ? endpoint.trim()
+ : true);
+
+ // div 而非 label:label 会把 :hover/click 转发给第一个可标记控件
+ const field = (label: string, node: React.ReactNode) => (
+ <div className="mb-3">
+ <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div>
+ {node}
+ </div>
+ );
+
+ return (
+ <div
+ className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
+ onMouseDown={(e) => {
+ if (e.target === e.currentTarget) onDone();
+ }}
+ >
+ <div className="glass-strong w-[30rem] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-4rem)] overflow-y-auto u-scroll rounded-2xl shadow-2xl">
+ <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-white/10">
+ <h2 className="u-title text-[15px]">{S.library.editSourceTitle}</h2>
+ <button onClick={onDone} className="text-neutral-500 hover:text-neutral-200">
+ <X size={15} />
+ </button>
+ </div>
+
+ <div className="px-5 py-4">
+ {/* 类型只读:换类型 = 换身份,应新建来源 */}
+ <div className="mb-4 flex items-center gap-2 text-xs text-neutral-400">
+ <KindIcon size={13} className="text-neutral-500" />
+ {S.library.sourceKinds[kind as keyof typeof S.library.sourceKinds] ?? kind}
+ </div>
+
+ {field(
+ S.library.sourceName,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />,
+ )}
+
+ {kind === "custom" &&
+ field(
+ S.library.iconLabel,
+ <div className="grid grid-cols-10 gap-1">
+ {Object.entries(SOURCE_ICONS).map(([key, Icon]) => (
+ <button
+ key={key}
+ onClick={() => setIcon(icon === key ? null : key)}
+ title={key}
+ className={`h-8 grid place-items-center rounded-lg transition-colors ${
+ icon === key
+ ? "bg-white text-black"
+ : "text-neutral-400 hover:bg-white/[0.07] hover:text-neutral-200"
+ }`}
+ >
+ <Icon size={14} />
+ </button>
+ ))}
+ </div>,
+ )}
+
+ {kind === "url" &&
+ field(
+ S.library.urlsField,
+ <textarea
+ className="input-dark w-full px-3 py-2 text-sm font-mono h-20 resize-y"
+ value={urls}
+ onChange={(e) => setUrls(e.target.value)}
+ />,
+ )}
+ {kind === "rss" &&
+ field(
+ S.library.feedUrl,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono"
+ value={feedUrl}
+ onChange={(e) => setFeedUrl(e.target.value)}
+ />,
+ )}
+ {kind === "custom" && (
+ <>
+ {field(
+ S.library.endpointField,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono"
+ value={endpoint}
+ onChange={(e) => setEndpoint(e.target.value)}
+ />,
+ )}
+ {field(
+ S.library.authHeaderEditField,
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono"
+ type="password"
+ placeholder={S.library.authKeepHint}
+ value={authHeader}
+ onChange={(e) => setAuthHeader(e.target.value)}
+ />,
+ )}
+ </>
+ )}
+
+ {ingestChanged && (
+ <p className="mb-3 text-[11px] leading-relaxed text-neutral-500">
+ {S.library.editKeepNote}
+ </p>
+ )}
+
+ {syncing &&
+ field(
+ S.library.interval,
+ <SchedulePicker
+ initial={{
+ sync_interval_minutes: source.sync_interval_minutes,
+ sync_cron: source.sync_cron,
+ }}
+ onChange={setSchedule}
+ />,
+ )}
+
+ {save.isError && (
+ <p className="text-xs text-rose-400 mb-2">{(save.error as Error).message}</p>
+ )}
+
+ {/* Danger zone:删除来源(文档保留,落回 Uploads) */}
+ <div className="mt-4 pt-3 border-t border-white/10">
+ <div className="mb-1 text-[11px] font-medium text-neutral-500">
+ {S.library.dangerZone}
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-[11px] text-neutral-600">{S.library.deleteSourceHint}</span>
+ <button
+ onClick={() => setConfirmingDelete(true)}
+ className="u-btn px-3.5 py-1.5 text-xs font-semibold shrink-0"
+ style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
+ >
+ {S.library.deleteSource}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex justify-end gap-2 px-5 py-3 border-t border-white/10">
+ <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={onDone}>
+ {S.library.cancel}
+ </button>
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!valid || save.isPending}
+ onClick={() => save.mutate()}
+ >
+ {S.library.saveChanges}
+ </button>
+ </div>
+ </div>
+
+ {confirmingDelete && (
+ <DangerConfirm
+ title={S.library.deleteSourceTitle}
+ hint={S.library.deleteSourceBody(source.name)}
+ requireText={source.name}
+ confirmLabel={S.library.deleteSource}
+ cancelLabel={S.library.cancel}
+ onConfirm={onDelete}
+ onCancel={() => setConfirmingDelete(false)}
+ />
+ )}
+ </div>
+ );
+}
+
+function DocRow({
+ doc,
+ source,
+ onDelete,
+ onExtract,
+ onReprocess,
+}: {
+ doc: Doc;
+ /** undefined = 不渲染来源列;null = Uploads(source_id 为空) */
+ source?: SourceView | null;
+ onDelete: () => void;
+ onExtract: () => void;
+ onReprocess: () => void;
+}) {
+ const statusText =
+ S.library.status[doc.status as keyof typeof S.library.status] ?? doc.status;
+ const graphText =
+ S.library.graphStatus[doc.graph_status as keyof typeof S.library.graphStatus] ??
+ doc.graph_status;
+ const SrcIcon = source ? sourceIcon(source) : Upload;
+ return (
+ <tr className="border-b border-white/5 hover:bg-white/[0.03]">
+ <td className="px-4 py-2.5 max-w-xs truncate" title={doc.filename}>
+ <Link
+ to="/doc/$docId"
+ params={{ docId: doc.id }}
+ search={{}}
+ className="text-neutral-200 hover:text-[var(--u-accent)]"
+ >
+ {doc.filename}
+ </Link>
+ </td>
+ {source !== undefined && (
+ <td className="px-4 py-2.5">
+ <span className="flex items-center gap-1.5 text-xs text-neutral-400">
+ <SrcIcon size={12} className="shrink-0 text-neutral-500" />
+ <span className="truncate max-w-28">{source?.name ?? S.library.uploads}</span>
+ </span>
+ </td>
+ )}
+ <td className="px-4 py-2.5">
+ <Chip tone={STATUS_TONE[doc.status] ?? "neutral"} title={doc.error ?? ""}>
+ {statusText}
+ </Chip>
+ {/* 解析管道失败:重跑 解析→索引→嵌入(解析器升级/瞬时故障重试) */}
+ {doc.status === "failed" && (
+ <button onClick={onReprocess} className="u-link ml-1.5 text-xs">
+ {S.library.reprocess}
+ </button>
+ )}
+ {doc.missing_since && (
+ <span className="ml-1.5 inline-block" title={doc.missing_since.slice(0, 16).replace("T", " ")}>
+ <Chip tone="neutral">{S.library.notInSource}</Chip>
+ </span>
+ )}
+ </td>
+ <td className="px-4 py-2.5">
+ {doc.graph_status === "none" ? (
+ <span className="text-xs text-neutral-600">{graphText}</span>
+ ) : (
+ <Chip tone={GRAPH_TONE[doc.graph_status] ?? "neutral"}>{graphText}</Chip>
+ )}
+ {/* done 也可重抽:本体(描述/新类)调整后强制全量重抽正是常规操作 */}
+ {doc.status === "ready" && ["none", "failed", "done"].includes(doc.graph_status) && (
+ <button onClick={onExtract} className="u-link ml-1.5 text-xs">
+ {doc.graph_status === "done" ? S.library.reExtract : S.library.extract}
+ </button>
+ )}
+ </td>
+ <td className="px-4 py-2.5 text-neutral-400">{doc.chunk_count || "—"}</td>
+ <td className="px-4 py-2.5 text-neutral-400">{formatSize(doc.size_bytes)}</td>
+ <td className="px-4 py-2.5 text-right">
+ <button onClick={onDelete} className="text-xs text-neutral-500 hover:text-rose-400">
+ {S.library.delete}
+ </button>
+ </td>
+ </tr>
+ );
+}
+
+function formatSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+}
diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsx
new file mode 100644
index 00000000..fc2a31a7
--- /dev/null
+++ b/web/src/pages/Login.tsx
@@ -0,0 +1,159 @@
+import { useState } from "react";
+import { useMutation } from "@tanstack/react-query";
+import { Link, useNavigate } from "@tanstack/react-router";
+
+/* lucide 已移除品牌图标,GitHub mark 内联(官方 mark 路径,fill=currentColor) */
+function GithubMark({ size = 16 }: { size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
+ <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
+ </svg>
+ );
+}
+import { api, ApiError } from "../api";
+import { S } from "../i18n";
+import { Wordmark } from "../ui";
+import { LoginScene } from "./LoginScene";
+import { usePageTitle } from "../useTitle";
+
+export function Login() {
+ usePageTitle(S.app.name, S.login.signIn);
+ const navigate = useNavigate();
+ const [mode, setMode] = useState<"login" | "register">("login");
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [displayName, setDisplayName] = useState("");
+ const [leaving, setLeaving] = useState(false);
+
+ const mutation = useMutation({
+ mutationFn: async () => {
+ if (mode === "login") return api.login(email, password);
+ return api.register(email, password, displayName);
+ },
+ onSuccess: () => {
+ // 谢幕:卡片上浮淡出、巨构放大穿越,再进入图谱首页
+ setLeaving(true);
+ window.setTimeout(() => navigate({ to: "/graph" }), 650);
+ },
+ });
+
+ const error =
+ mutation.error instanceof ApiError
+ ? mutation.error.message
+ : mutation.error
+ ? S.login.networkError
+ : null;
+
+ const input = "input-dark w-full px-3 py-2 text-sm";
+
+ return (
+ <div className="min-h-screen flex items-center justify-center px-4">
+ {/* 巨构变换背景:星球 → 环形都市 → 城市平原 → 波动巨碑 */}
+ <LoginScene leaving={leaving} />
+ <div className={`relative z-10 w-full max-w-sm ${leaving ? "u-depart" : ""}`}>
+ <div className="mb-8 text-center u-rise">
+ <h1 className="text-5xl font-normal">
+ <Wordmark />
+ </h1>
+ <p className="mt-2 text-sm text-neutral-400">{S.app.tagline}</p>
+ </div>
+
+ <div className="u-card-opaque rounded-2xl p-6 u-rise" style={{ animationDelay: "90ms" }}>
+ <div className="flex gap-1 mb-5 bg-white/5 rounded-lg p-1">
+ {(["login", "register"] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ onClick={() => setMode(m)}
+ className={`flex-1 rounded-md py-1.5 text-sm font-medium transition-colors ${
+ mode === m
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:text-neutral-300"
+ }`}
+ >
+ {m === "login" ? S.login.signIn : S.login.signUp}
+ </button>
+ ))}
+ </div>
+
+ <form
+ className="space-y-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ mutation.mutate();
+ }}
+ >
+ {mode === "register" && (
+ <input
+ className={input}
+ placeholder={S.login.displayName}
+ value={displayName}
+ onChange={(e) => setDisplayName(e.target.value)}
+ required
+ />
+ )}
+ <input
+ type="email"
+ className={input}
+ placeholder={S.login.email}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ required
+ />
+ <input
+ type="password"
+ className={input}
+ placeholder={S.login.password}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ required
+ minLength={8}
+ />
+ {error && <p className="text-sm text-rose-400">{error}</p>}
+ <button
+ type="submit"
+ disabled={mutation.isPending || leaving}
+ className="btn-primary w-full py-2 text-sm"
+ >
+ {mutation.isPending || leaving
+ ? S.login.submitting
+ : mode === "login"
+ ? S.login.signIn
+ : S.login.createAccount}
+ </button>
+ </form>
+ </div>
+
+ {/* 页脚:惯用同意句式内嵌条款/隐私链接 + GitHub 入口 */}
+ <div className="mt-6 text-center u-rise" style={{ animationDelay: "180ms" }}>
+ <p className="u-balance text-[11px] leading-relaxed text-neutral-600">
+ {S.login.agreePrefix}
+ <Link
+ to="/terms"
+ className="whitespace-nowrap text-neutral-500 underline decoration-white/20 underline-offset-2 hover:text-neutral-300 transition-colors"
+ >
+ {S.legal.termsTitle}
+ </Link>
+ {S.login.agreeAnd}
+ <Link
+ to="/privacy"
+ className="whitespace-nowrap text-neutral-500 underline decoration-white/20 underline-offset-2 hover:text-neutral-300 transition-colors"
+ >
+ {S.legal.privacyTitle}
+ </Link>
+ {S.login.agreeSuffix}
+ </p>
+ <a
+ href={S.login.githubUrl}
+ target="_blank"
+ rel="noreferrer"
+ title="GitHub"
+ className="mt-3 inline-flex text-neutral-600 hover:text-neutral-300 transition-colors"
+ >
+ <GithubMark size={16} />
+ </a>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/LoginScene.tsx b/web/src/pages/LoginScene.tsx
new file mode 100644
index 00000000..48e17cb7
--- /dev/null
+++ b/web/src/pages/LoginScene.tsx
@@ -0,0 +1,398 @@
+/* 登录页背景:巨构变换(Canvas 2D,零依赖)。
+ 四种巨型形态——星球(球面)→ 环形都市(环面)→ 城市平原(起伏网格)→
+ 波动巨碑(竖直巨墙)。结构持续缓慢自转(运动本身很便宜);形态切换不做
+ 逐点插值变形(那才是卡顿来源),而是整体淡出 → 换形态 → 淡入,浮现时
+ 带一点由小到大的生长感。透视投影、结构大于视口(巨物应当出画)。
+ 性能:形态几何只在切换时重算进 TypedArray;点按亮度分桶、每桶一次 fill;
+ DPR 封顶 1.5。纯中性白灰;prefers-reduced-motion 时静止单帧。 */
+import { useEffect, useRef } from "react";
+
+const U = 48; // 经向点数
+const V = 26; // 纬向点数
+const N = U * V;
+const HOLD_MS = 7000; // 完全可见的停留
+const FADE_MS = 1400; // 淡出 / 淡入各自时长
+const ROT_SPEED = 0.000024; // 弧度/毫秒(约 260s 一周,巨物应当迟缓)
+const BUCKETS = 12; // 点亮度分桶数
+
+type Vec3 = [number, number, number];
+
+/** 形态族:每个函数把 (u,v)∈[0,1) 映射到 ~[-1,1]³ */
+const FORMS: ((u: number, v: number) => Vec3)[] = [
+ // 星球:球面
+ (u, v) => {
+ const lon = u * Math.PI * 2;
+ const lat = (v - 0.5) * Math.PI * 0.92;
+ return [Math.cos(lat) * Math.cos(lon), Math.sin(lat) * 0.95, Math.cos(lat) * Math.sin(lon)];
+ },
+ // 环形都市:环面
+ (u, v) => {
+ const a = u * Math.PI * 2;
+ const b = v * Math.PI * 2;
+ const R = 0.74;
+ const r = 0.32;
+ return [
+ (R + r * Math.cos(b)) * Math.cos(a),
+ r * Math.sin(b) * 1.05,
+ (R + r * Math.cos(b)) * Math.sin(a),
+ ];
+ },
+ // 城市平原:起伏网格
+ (u, v) => {
+ const x = (u - 0.5) * 2.5;
+ const z = (v - 0.5) * 2.5;
+ const y = Math.sin(x * 2.3) * 0.14 + Math.cos(z * 2.1 + x * 1.2) * 0.12 - 0.15;
+ return [x, y, z];
+ },
+ // 波动巨碑:竖直巨墙
+ (u, v) => {
+ const x = (u - 0.5) * 2.3;
+ const y = (v - 0.5) * 1.5;
+ const z = Math.sin(x * 2.8 + y * 1.6) * 0.22;
+ return [x, y, z];
+ },
+];
+
+function smoothstep(t: number): number {
+ return t * t * (3 - 2 * t);
+}
+
+export function LoginScene({ leaving }: { leaving?: boolean }) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+
+ const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+ // 点阵参数坐标
+ const pu = new Float32Array(N);
+ const pv = new Float32Array(N);
+ for (let j = 0; j < V; j++)
+ for (let i = 0; i < U; i++) {
+ const k = j * U + i;
+ pu[k] = i / U;
+ pv[k] = j / (V - 1);
+ }
+ // 网格邻接边,扁平存储
+ const edgeIdx: number[] = [];
+ for (let j = 0; j < V; j++)
+ for (let i = 0; i < U; i++) {
+ const a = j * U + i;
+ if (i < U - 1) edgeIdx.push(a, a + 1);
+ if (j < V - 1) edgeIdx.push(a, a + U);
+ }
+ const edges = new Int32Array(edgeIdx);
+ // u 首尾回绕边:只在 u 方向闭合的形态(球面/环面)上绘制——
+ // 摊平形态(平原/巨碑)画它会横穿整个画面
+ const wrapIdx: number[] = [];
+ for (let j = 0; j < V; j++) wrapIdx.push(j * U + U - 1, j * U);
+ const wrapEdges = new Int32Array(wrapIdx);
+ const U_CLOSED = [true, true, false, false]; // 与 FORMS 一一对应
+
+ // 当前形态几何:只在切换时重算,帧内零分配
+ const fx = new Float32Array(N), fy = new Float32Array(N), fz = new Float32Array(N);
+ let cachedForm = -1;
+ const fillForm = (idx: number) => {
+ const map = FORMS[idx];
+ for (let k = 0; k < N; k++) {
+ const P = map(pu[k], pv[k]);
+ fx[k] = P[0];
+ fy[k] = P[1];
+ fz[k] = P[2];
+ }
+ cachedForm = idx;
+ };
+
+ const px = new Float32Array(N);
+ const py = new Float32Array(N);
+ const pa = new Float32Array(N); // 深度→亮度 0..1
+
+ // 亮度分桶:预生成样式串,帧内无字符串拼接
+ const bucketStyle: string[] = [];
+ for (let b = 0; b < BUCKETS; b++)
+ bucketStyle.push(`rgba(255,255,255,${(0.1 + (b / (BUCKETS - 1)) * 0.34).toFixed(3)})`);
+ const buckets: number[][] = Array.from({ length: BUCKETS }, () => []);
+
+ // 原地闪烁:弱化为氛围层(主秀是下面的光脉冲)
+ const TWINKLES = 40;
+ const twIdx = new Int32Array(TWINKLES);
+ const twPhase = new Float32Array(TWINKLES);
+ const twSpeed = new Float32Array(TWINKLES);
+ for (let n = 0; n < TWINKLES; n++) {
+ twIdx[n] = (n * 1013 + 389) % N; // 确定性伪随机散布
+ twPhase[n] = ((n * 7919) % 628) / 100; // 0..2π
+ twSpeed[n] = 0.0008 + ((n * 271) % 100) / 100 * 0.0016; // 弧度/毫秒
+ }
+
+ // 光脉冲:从一个顶点沿边亮向另一个顶点,拖渐隐尾迹(信号在巨构上传导)
+ const PULSES = 12;
+ const TRAIL_MAX = 5; // 尾迹保留的节点数
+ const TRAIL_LEN = 3.2; // 尾迹可见长度(边数)
+ type Pulse = {
+ trail: number[]; // 已过节点,旧→新
+ next: number; // 正在亮向的节点
+ t: number; // 当前边上的进度 0..1
+ speed: number; // 边/毫秒
+ edgesLeft: number;
+ fade: number; // 出生/消亡包络
+ dying: boolean;
+ delay: number; // 重生倒计时(毫秒)
+ };
+ const nbuf: number[] = [];
+ const neighborsOf = (k: number) => {
+ nbuf.length = 0;
+ const i = k % U;
+ const j = (k / U) | 0;
+ if (i > 0) nbuf.push(k - 1);
+ if (i < U - 1) nbuf.push(k + 1);
+ if (j > 0) nbuf.push(k - U);
+ if (j < V - 1) nbuf.push(k + U);
+ };
+ const spawnPulse = (p: Pulse, first: boolean) => {
+ const k = (Math.random() * N) | 0;
+ neighborsOf(k);
+ p.trail = [k];
+ p.next = nbuf[(Math.random() * nbuf.length) | 0];
+ p.t = 0;
+ p.speed = (1.6 + Math.random() * 1.8) / 1000;
+ p.edgesLeft = 5 + ((Math.random() * 8) | 0);
+ p.fade = 0;
+ p.dying = false;
+ p.delay = first ? Math.random() * 4000 : 600 + Math.random() * 3500;
+ };
+ const pulses: Pulse[] = [];
+ for (let n = 0; n < PULSES; n++) {
+ const p = {} as Pulse;
+ spawnPulse(p, true);
+ pulses.push(p);
+ }
+
+ let raf = 0;
+ let w = 0;
+ let h = 0;
+ const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
+ const resize = () => {
+ w = canvas.clientWidth;
+ h = canvas.clientHeight;
+ canvas.width = Math.max(1, Math.round(w * dpr));
+ canvas.height = Math.max(1, Math.round(h * dpr));
+ };
+ resize();
+ const ro = new ResizeObserver(resize);
+ ro.observe(canvas);
+
+ let lastNow = -1;
+ const draw = (now: number) => {
+ const dt = lastNow < 0 ? 16 : Math.min(50, now - lastNow);
+ lastNow = now;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+
+ // 推进光脉冲(与场景可见性无关,淡出期间也在走)
+ for (const p of pulses) {
+ if (p.delay > 0) {
+ p.delay -= dt;
+ continue;
+ }
+ if (p.dying) {
+ p.fade -= dt / 350;
+ if (p.fade <= 0) spawnPulse(p, false);
+ continue;
+ }
+ p.fade = Math.min(1, p.fade + dt / 350);
+ p.t += p.speed * dt;
+ while (p.t >= 1) {
+ p.t -= 1;
+ const prev = p.trail[p.trail.length - 1];
+ const cur = p.next;
+ p.trail.push(cur);
+ if (p.trail.length > TRAIL_MAX) p.trail.shift();
+ if (--p.edgesLeft <= 0) {
+ p.dying = true;
+ break;
+ }
+ // 选下一条边:偏好直行(信号感),不走回头路
+ const straight = cur + (cur - prev);
+ neighborsOf(cur);
+ if (nbuf.includes(straight) && Math.random() < 0.72) {
+ p.next = straight;
+ } else {
+ let pick = prev;
+ let seen = 0;
+ for (const cand of nbuf) {
+ if (cand === prev) continue;
+ seen++;
+ if (Math.random() < 1 / seen) pick = cand;
+ }
+ p.next = pick;
+ }
+ }
+ }
+
+ // 时间轴:淡入 → 停留 → 淡出,边界处(不可见时)切换形态
+ const cycle = HOLD_MS + FADE_MS * 2;
+ const tt = now % (FORMS.length * cycle);
+ const slot = Math.floor(tt / cycle);
+ const tc = tt - slot * cycle;
+ if (slot !== cachedForm) fillForm(slot);
+ let vis: number;
+ if (tc < FADE_MS) vis = smoothstep(tc / FADE_MS);
+ else if (tc < FADE_MS + HOLD_MS) vis = 1;
+ else vis = 1 - smoothstep((tc - FADE_MS - HOLD_MS) / FADE_MS);
+ if (vis <= 0.004) {
+ if (!reduced) raf = requestAnimationFrame(draw);
+ return;
+ }
+
+ const ry = now * ROT_SPEED;
+ const sinY = Math.sin(ry);
+ const cosY = Math.cos(ry);
+ const sinX = Math.sin(0.4);
+ const cosX = Math.cos(0.4);
+
+ // 巨物尺度:大于视口;浮现时带一点生长感
+ const scale = Math.max(w, h) * 0.62 * (0.96 + 0.04 * vis);
+ const cx = w * 0.5;
+ const cy = h * 0.66;
+
+ for (let k = 0; k < N; k++) {
+ let x = fx[k];
+ let y = fy[k];
+ let z = fz[k];
+ const x1 = x * cosY + z * sinY;
+ const z1 = -x * sinY + z * cosY;
+ const y1 = y * cosX - z1 * sinX;
+ const z2 = y * sinX + z1 * cosX;
+ x = x1;
+ y = y1;
+ z = z2;
+ const persp = 2.6 / (2.6 - z * 0.9);
+ px[k] = cx + x * scale * persp;
+ py[k] = cy - y * scale * persp;
+ pa[k] = Math.min(1, Math.max(0, (z + 1.15) / 2.1)); // 近处亮
+ }
+
+ // 整体可见度只动 globalAlpha 这一个旋钮
+ ctx.globalAlpha = vis;
+
+ // 边:极淡的白,一次 stroke
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = "rgba(255,255,255,0.045)";
+ ctx.beginPath();
+ for (let e = 0; e < edges.length; e += 2) {
+ const a = edges[e];
+ const b = edges[e + 1];
+ ctx.moveTo(px[a], py[a]);
+ ctx.lineTo(px[b], py[b]);
+ }
+ if (U_CLOSED[slot]) {
+ for (let e = 0; e < wrapEdges.length; e += 2) {
+ const a = wrapEdges[e];
+ const b = wrapEdges[e + 1];
+ ctx.moveTo(px[a], py[a]);
+ ctx.lineTo(px[b], py[b]);
+ }
+ }
+ ctx.stroke();
+
+ // 点:按亮度分桶,每桶一次 fill(矩形,1~2px 下与圆不可分辨)
+ for (let b = 0; b < BUCKETS; b++) buckets[b].length = 0;
+ for (let k = 0; k < N; k++) {
+ const b = Math.min(BUCKETS - 1, (pa[k] * BUCKETS) | 0);
+ buckets[b].push(k);
+ }
+ for (let b = 0; b < BUCKETS; b++) {
+ const list = buckets[b];
+ if (!list.length) continue;
+ ctx.fillStyle = bucketStyle[b];
+ ctx.beginPath();
+ for (let n = 0; n < list.length; n++) {
+ const k = list[n];
+ const r = 0.8 + pa[k] * 1.1;
+ ctx.rect(px[k] - r, py[k] - r, r * 2, r * 2);
+ }
+ ctx.fill();
+ }
+
+ // 氛围闪烁:尖峰脉冲(sin⁶),弱化版
+ ctx.fillStyle = "rgba(255,255,255,0.92)";
+ for (let n = 0; n < TWINKLES; n++) {
+ const s = Math.sin(now * twSpeed[n] + twPhase[n]);
+ if (s <= 0) continue;
+ const glint = s * s * s * s * s * s;
+ if (glint < 0.02) continue;
+ const k = twIdx[n];
+ ctx.globalAlpha = vis * glint * (0.35 + pa[k] * 0.65) * 0.5;
+ const r = 0.9 + glint * 1.3;
+ ctx.beginPath();
+ ctx.arc(px[k], py[k], r, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ // 光脉冲:头部亮点 + 沿走过的边渐隐的尾迹
+ ctx.strokeStyle = "#ffffff";
+ ctx.fillStyle = "#ffffff";
+ ctx.lineWidth = 1.2;
+ for (const p of pulses) {
+ if (p.delay > 0 || p.fade <= 0) continue;
+ const tail = p.trail;
+ const cur = tail[tail.length - 1];
+ const hx = px[cur] + (px[p.next] - px[cur]) * p.t;
+ const hy = py[cur] + (py[p.next] - py[cur]) * p.t;
+ const base = vis * p.fade * (0.35 + pa[cur] * 0.65);
+
+ // 尾迹:先画 cur→头部 的半段,再逐段回溯,按距头部的边数渐隐
+ let x2 = hx;
+ let y2 = hy;
+ let dist = 0; // 段中点距头部的边数
+ for (let s = tail.length - 1; s >= 0; s--) {
+ const k = tail[s];
+ const segLen = s === tail.length - 1 ? p.t : 1;
+ const a = Math.max(0, 1 - (dist + segLen / 2) / TRAIL_LEN);
+ if (a <= 0.01) break;
+ ctx.globalAlpha = base * a * 0.55;
+ ctx.beginPath();
+ ctx.moveTo(px[k], py[k]);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+ x2 = px[k];
+ y2 = py[k];
+ dist += segLen;
+ }
+
+ // 头部:光晕 + 亮核
+ ctx.globalAlpha = base * 0.16;
+ ctx.beginPath();
+ ctx.arc(hx, hy, 3.8, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.globalAlpha = base * 0.95;
+ ctx.beginPath();
+ ctx.arc(hx, hy, 1.5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.globalAlpha = 1;
+
+ if (!reduced) raf = requestAnimationFrame(draw);
+ };
+
+ raf = requestAnimationFrame(draw);
+ return () => {
+ cancelAnimationFrame(raf);
+ ro.disconnect();
+ };
+ }, []);
+
+ return (
+ <canvas
+ ref={canvasRef}
+ className={`pointer-events-none fixed inset-0 h-full w-full ${
+ leaving ? "u-scene-depart" : ""
+ }`}
+ aria-hidden
+ />
+ );
+}
diff --git a/web/src/pages/Members.tsx b/web/src/pages/Members.tsx
new file mode 100644
index 00000000..40057c91
--- /dev/null
+++ b/web/src/pages/Members.tsx
@@ -0,0 +1,221 @@
+import { useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { S } from "../i18n";
+import { Dropdown, Pager, pageSlice, SearchSelect } from "../ui";
+
+const ROLES = ["owner", "admin", "editor", "viewer"] as const;
+const ROLE_OPTIONS = ROLES.map((r) => ({ value: r, label: S.members.roles[r] }));
+const MEMBER_PAGE = 10;
+
+export function Members({ workspaceId }: { workspaceId: string }) {
+ const queryClient = useQueryClient();
+ const [addUserId, setAddUserId] = useState("");
+ const [addRole, setAddRole] = useState("viewer");
+ const [memberPage, setMemberPage] = useState(0);
+ const [filter, setFilter] = useState("");
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ const [error, setError] = useState<string | null>(null);
+
+ const members = useQuery({
+ queryKey: ["members", workspaceId],
+ queryFn: () => api.members(workspaceId),
+ });
+ const orgUsers = useQuery({ queryKey: ["orgUsers"], queryFn: api.orgUsers });
+
+ const refresh = () => {
+ setError(null);
+ queryClient.invalidateQueries({ queryKey: ["members", workspaceId] });
+ };
+ const onError = (e: unknown) => setError((e as Error).message);
+
+ const setRole = useMutation({
+ mutationFn: ({ userId, role }: { userId: string; role: string }) =>
+ api.setMemberRole(workspaceId, userId, role),
+ onSuccess: refresh,
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: (userId: string) => api.removeMember(workspaceId, userId),
+ onSuccess: refresh,
+ onError,
+ });
+
+ const memberIds = new Set(members.data?.map((m) => m.user_id));
+ const addable = orgUsers.data?.filter((u) => !memberIds.has(u.id)) ?? [];
+ const q = filter.trim().toLowerCase();
+ const memberList = (members.data ?? []).filter(
+ (m) =>
+ !q || m.display_name.toLowerCase().includes(q) || m.email.toLowerCase().includes(q),
+ );
+ const { rows: pagedMembers, safe: safeMemberPage } = pageSlice(memberList, memberPage, MEMBER_PAGE);
+
+ return (
+ <div className="glass rounded-xl p-5">
+ <div className="flex items-center gap-3 mb-3">
+ <h3 className="text-sm font-bold text-neutral-200">{S.members.title}</h3>
+ <input
+ className="input-dark ml-auto w-56 px-2.5 py-1 text-xs"
+ placeholder={S.settings.searchUsers}
+ value={filter}
+ onChange={(e) => {
+ setFilter(e.target.value);
+ setMemberPage(0);
+ }}
+ />
+ </div>
+
+ {error && <p className="mb-3 text-sm text-rose-400">{error}</p>}
+
+ <table className="w-full text-sm">
+ <tbody>
+ {pagedMembers.map((m) => (
+ <tr key={m.user_id} className="border-b border-white/5">
+ <td className="py-2 pr-3">
+ <div className="text-neutral-200">
+ {m.display_name}
+ {m.is_admin && (
+ <span className="ml-1.5 rounded bg-[rgba(74,163,255,0.12)] px-1.5 py-0.5 text-[10px] text-[var(--u-accent)]">
+ {S.members.systemAdmin}
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-neutral-500">{m.email}</div>
+ </td>
+ <td className="py-2 pr-3 text-right">
+ <Dropdown
+ size="sm"
+ className="w-24 ml-auto"
+ value={m.role}
+ onChange={(role) => setRole.mutate({ userId: m.user_id, role })}
+ options={ROLE_OPTIONS}
+ />
+ </td>
+ <td className="py-2 text-right">
+ <button
+ onClick={() => remove.mutate(m.user_id)}
+ className="text-xs text-neutral-500 hover:text-rose-400"
+ >
+ {S.members.remove}
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ <div className="mb-4">
+ <Pager
+ total={memberList.length}
+ pageSize={MEMBER_PAGE}
+ page={safeMemberPage}
+ onPage={setMemberPage}
+ />
+ </div>
+
+ {addable.length > 0 ? (
+ <div className="flex gap-2 items-center">
+ <SearchSelect
+ className="flex-1"
+ value={addUserId}
+ onChange={setAddUserId}
+ placeholder={S.members.pickUser}
+ options={addable.map((u) => ({
+ value: u.id,
+ label: u.display_name,
+ hint: u.email,
+ }))}
+ />
+ <Dropdown
+ className="w-28"
+ value={addRole}
+ onChange={setAddRole}
+ options={ROLE_OPTIONS}
+ />
+ <button
+ onClick={() => addUserId && setRole.mutate({ userId: addUserId, role: addRole })}
+ disabled={!addUserId}
+ className="u-btn u-btn-primary px-3 py-1.5 text-sm"
+ >
+ {S.members.add}
+ </button>
+ </div>
+ ) : (
+ <p className="text-xs text-neutral-500">{S.members.allAdded}</p>
+ )}
+
+ {me.data?.is_admin && <CreateUser onCreated={refresh} />}
+ </div>
+ );
+}
+
+/** 管理员代开账号(注册关闭后的唯一入口)。 */
+function CreateUser({ onCreated }: { onCreated: () => void }) {
+ const queryClient = useQueryClient();
+ const [email, setEmail] = useState("");
+ const [name, setName] = useState("");
+ const [password, setPassword] = useState("");
+ const [role, setRole] = useState("editor");
+ const [error, setError] = useState<string | null>(null);
+
+ const create = useMutation({
+ mutationFn: () =>
+ api.adminCreateUser({ email: email.trim(), display_name: name.trim(), password, role }),
+ onSuccess: () => {
+ setEmail("");
+ setName("");
+ setPassword("");
+ setError(null);
+ queryClient.invalidateQueries({ queryKey: ["orgUsers"] });
+ onCreated();
+ },
+ onError: (e) => setError((e as Error).message),
+ });
+
+ const valid = email.includes("@") && name.trim() && password.length >= 8;
+
+ return (
+ <div className="mt-5 border-t border-white/10 pt-4">
+ <h4 className="text-xs font-bold text-neutral-400 mb-2">{S.settings.newUser}</h4>
+ <div className="grid grid-cols-2 gap-2 mb-2">
+ <input
+ className="input-dark px-3 py-2 text-sm"
+ placeholder={S.login.email}
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ />
+ <input
+ className="input-dark px-3 py-2 text-sm"
+ placeholder={S.login.displayName}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <input
+ className="input-dark px-3 py-2 text-sm"
+ type="password"
+ placeholder={S.settings.initialPassword}
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ />
+ <Dropdown
+ value={role}
+ onChange={setRole}
+ options={[
+ { value: "admin", label: S.members.roles.admin },
+ { value: "editor", label: S.members.roles.editor },
+ { value: "viewer", label: S.members.roles.viewer },
+ ]}
+ />
+ </div>
+ <div className="flex items-center gap-3">
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!valid || create.isPending}
+ onClick={() => create.mutate()}
+ >
+ {S.settings.createUserBtn}
+ </button>
+ {error && <p className="text-xs text-rose-400">{error}</p>}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/MyKbs.tsx b/web/src/pages/MyKbs.tsx
new file mode 100644
index 00000000..4b690456
--- /dev/null
+++ b/web/src/pages/MyKbs.tsx
@@ -0,0 +1,110 @@
+/* 账户层"我的知识库":可访问的库 + 我的角色 + 加入信息 + 概览统计。
+ 只读全景——建库是管理动作,入口在 System settings › Knowledge bases。 */
+import { useQuery } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
+import { Lock } from "lucide-react";
+import { api, type MyKb } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { Chip, Loading } from "../ui";
+
+const ymd = (iso: string) => iso.slice(0, 10);
+
+function joinInfo(row: MyKb): string {
+ if (row.my_role === "owner") return S.account.deploymentAdmin;
+ if (row.joined_at) {
+ return row.added_by_name
+ ? S.account.addedBy(row.added_by_name, ymd(row.joined_at))
+ : S.account.joinedOn(ymd(row.joined_at));
+ }
+ return S.account.openToEveryone;
+}
+
+export function MyKbs() {
+ const navigate = useNavigate();
+ const { workspace, setKb } = useKb();
+
+ const mine = useQuery({
+ queryKey: ["myKbs", workspace?.id],
+ queryFn: () => api.myKbs(workspace!.id),
+ enabled: !!workspace,
+ });
+
+ if (!workspace || mine.isPending) return <Loading>{S.nav.loading}</Loading>;
+
+ const rows = mine.data?.kbs ?? [];
+ const openKb = (id: string) => {
+ setKb(id);
+ navigate({ to: "/graph" });
+ };
+
+ return (
+ <div className="max-w-2xl p-8">
+ <div className="mb-6">
+ <h1 className="u-title text-lg">{S.account.kbsTitle}</h1>
+ </div>
+
+ <div className="space-y-3">
+ {rows.map((row) => {
+ const canManage = row.my_role === "admin" || row.my_role === "owner";
+ return (
+ <div key={row.kb.id} className="glass glass-hover rounded-2xl px-5 py-4">
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="text-[15px] font-medium text-neutral-100 truncate">
+ {row.kb.name}
+ </span>
+ {row.kb.visibility === "restricted" ? (
+ <span className="flex items-center gap-1 text-[10.5px] text-neutral-500">
+ <Lock size={10} />
+ {S.account.kbRestricted}
+ </span>
+ ) : (
+ <span className="text-[10.5px] text-neutral-600">{S.account.kbOpen}</span>
+ )}
+ </div>
+ {row.kb.description && (
+ <p className="mt-0.5 text-xs text-neutral-500 truncate">
+ {row.kb.description}
+ </p>
+ )}
+ <p className="mt-1.5 text-[11px] text-neutral-600">
+ <span className="u-num">{S.account.kbStats(row.doc_count, row.member_count)}</span>
+ <span className="mx-1.5 text-neutral-700">·</span>
+ {joinInfo(row)}
+ </p>
+ </div>
+ <div className="shrink-0 flex items-center gap-2">
+ {row.my_role && (
+ <Chip tone={canManage ? "info" : "neutral"}>
+ {S.account.roleNames[row.my_role] ?? row.my_role}
+ </Chip>
+ )}
+ <button
+ onClick={() => openKb(row.kb.id)}
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs"
+ >
+ {S.account.openKb}
+ </button>
+ {canManage && (
+ <button
+ onClick={() => {
+ setKb(row.kb.id);
+ navigate({ to: "/kb-settings", search: { kb: row.kb.id } });
+ }}
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs"
+ >
+ {S.account.kbSettingsBtn}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ </div>
+ );
+}
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
new file mode 100644
index 00000000..c6d2c353
--- /dev/null
+++ b/web/src/pages/Ontology.tsx
@@ -0,0 +1,1222 @@
+// 本体编辑器:master-detail 双栏(与 Library 的 SourcesRail 同构)。
+// 左栏 = filter + Classes/Properties 两小节 + 底部 Unmatched 入口;
+// 右侧 = 选中项的表单 / 未匹配信号面板 / 概览。
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Link } from "@tanstack/react-router";
+import { ChevronRight, Inbox, Plus, Search } from "lucide-react";
+import {
+ api,
+ type EntityTypeView,
+ type OntologyMiss,
+ type OntologyProposals,
+ type RelationTypeView,
+} from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { toast } from "../toast";
+import {
+ Button,
+ Chip,
+ ColorPicker,
+ Dropdown,
+ Input,
+ Loading,
+ Pager,
+ PageTitle,
+ RAIL_CLS,
+ SearchSelect,
+ cn,
+ pageSlice,
+} from "../ui";
+
+/** 左栏行高(py-1.5 + 13px 文字 + space-y 间隙)与底部预留(新建行 + 分页器) */
+const RAIL_ROW_H = 34;
+const RAIL_RESERVED = 80;
+/** 兜底页行数(首帧未量到高度时用) */
+const RAIL_PAGE = 14;
+/** 过滤模式两节混排时每节的行数 */
+const RAIL_PAGE_MIXED = 6;
+
+/** 右侧详情区当前展示什么 */
+type Sel =
+ | { kind: "class"; id: string }
+ | { kind: "relation"; id: string }
+ | { kind: "new-class"; parentId: string | null }
+ | { kind: "new-relation" }
+ | { kind: "misses" }
+ | null;
+
+export function Ontology() {
+ const { kb } = useKb();
+ const queryClient = useQueryClient();
+ const [sel, setSel] = useState<Sel>(null);
+ const [railTab, setRailTab] = useState<"classes" | "properties">("classes");
+ const [filter, setFilter] = useState("");
+ const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
+ // 每页行数按列表区实际高度动态算:窗口多高铺多满,不滚动也不留大空
+ const listRef = useRef<HTMLDivElement>(null);
+ const [railRows, setRailRows] = useState(RAIL_PAGE);
+ useEffect(() => {
+ const el = listRef.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => {
+ setRailRows(Math.max(5, Math.floor((el.clientHeight - RAIL_RESERVED) / RAIL_ROW_H)));
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ const data = useQuery({
+ queryKey: ["ontology", kb?.id],
+ queryFn: () => api.ontology(kb!.id),
+ enabled: !!kb,
+ });
+
+ const refresh = () => queryClient.invalidateQueries({ queryKey: ["ontology", kb?.id] });
+ // 错误统一走全局 toast,不再用页面内嵌错误行
+ const onError = (e: unknown) => toast.error((e as Error).message);
+
+ if (!kb) return <Loading>{S.nav.loading}</Loading>;
+ if (data.isPending) return <Loading>{S.nav.loading}</Loading>;
+ if (data.isError) return <Loading>{(data.error as Error).message}</Loading>;
+
+ const { entity_types, relation_types, misses } = data.data;
+ // 属性不进 Properties 列表:它们挂在类下,在类详情区编辑
+ const relations = relation_types.filter((r) => r.kind !== "attribute");
+ const selectedClass =
+ sel?.kind === "class" ? (entity_types.find((t) => t.id === sel.id) ?? null) : null;
+ const selectedProp =
+ sel?.kind === "relation" ? (relation_types.find((r) => r.id === sel.id) ?? null) : null;
+
+ return (
+ <div className="h-full flex">
+ {/* 左栏:filter + 两小节 + Unmatched */}
+ <aside className={`${RAIL_CLS} flex flex-col`}>
+ <div className="px-3 pt-3 pb-2.5">
+ <div className="relative">
+ <Search
+ size={12}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-600"
+ />
+ <input
+ className="input-dark w-full pl-7 pr-2 py-1.5 text-xs"
+ placeholder={S.ontology.filter}
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ />
+ </div>
+ </div>
+ {/* 分段切换:与登录页模式切换/日程选择器同一语汇(bg-white/5 容器 + 激活反白);
+ 过滤时列表例外:两节混排同时给出命中 */}
+ <div className="mx-3 mb-1 flex gap-1 rounded-lg bg-white/5 p-1">
+ {(
+ [
+ ["classes", S.ontology.tabClasses],
+ ["properties", S.ontology.tabProperties],
+ ] as const
+ ).map(([k, label]) => (
+ <button
+ key={k}
+ onClick={() => setRailTab(k)}
+ className={cn(
+ "flex-1 rounded-md py-1 text-[12px] font-medium text-center transition-colors",
+ railTab === k
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:text-neutral-300",
+ )}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <div ref={listRef} className="flex-1 min-h-0 overflow-hidden px-2 pt-1.5 pb-2 flex flex-col">
+ {/* 新建行置顶:随当前段建类/建关系 */}
+ {!filter.trim() && (
+ <button
+ onClick={() =>
+ railTab === "classes"
+ ? setSel({ kind: "new-class", parentId: null })
+ : setSel({ kind: "new-relation" })
+ }
+ className="w-full flex items-center gap-1.5 rounded-lg px-2 py-2 mb-0.5 text-[13px] text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-200 transition-colors"
+ >
+ <Plus size={13} />
+ {railTab === "classes" ? S.ontology.newClass : S.ontology.newProperty}
+ </button>
+ )}
+ {filter.trim() ? (
+ <>
+ <div className="px-2 pt-2 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600">
+ {S.ontology.tabClasses}
+ </div>
+ <ClassTree
+ types={entity_types}
+ filter={filter}
+ collapsed={collapsed}
+ onToggle={() => {}}
+ selectedId={selectedClass?.id ?? null}
+ onSelect={(id) => setSel({ kind: "class", id })}
+ pageSize={RAIL_PAGE_MIXED}
+ />
+ <div className="px-2 pt-3 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600">
+ {S.ontology.tabProperties}
+ </div>
+ <PropertyList
+ relations={relations}
+ filter={filter}
+ selectedId={selectedProp?.id ?? null}
+ onSelect={(id) => setSel({ kind: "relation", id })}
+ pageSize={RAIL_PAGE_MIXED}
+ />
+ </>
+ ) : railTab === "classes" ? (
+ <ClassTree
+ types={entity_types}
+ filter={filter}
+ collapsed={collapsed}
+ onToggle={(id) => {
+ const next = new Set(collapsed);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ setCollapsed(next);
+ }}
+ selectedId={selectedClass?.id ?? null}
+ onSelect={(id) => setSel({ kind: "class", id })}
+ pageSize={railRows}
+ />
+ ) : (
+ <PropertyList
+ relations={relations}
+ filter={filter}
+ selectedId={selectedProp?.id ?? null}
+ onSelect={(id) => setSel({ kind: "relation", id })}
+ pageSize={railRows}
+ />
+ )}
+ </div>
+ {/* 底部常驻:抽取未匹配信号(有存量时带数量徽标) */}
+ <button
+ onClick={() => setSel({ kind: "misses" })}
+ className={cn(
+ "shrink-0 border-t border-white/10 px-4 py-2.5 flex items-center gap-2 text-[13px] transition-colors",
+ sel?.kind === "misses"
+ ? "u-nav-active"
+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
+ )}
+ >
+ <Inbox size={14} className="text-neutral-500" />
+ <span>{S.ontology.missesShort}</span>
+ {misses.length > 0 && (
+ <span className="ml-auto u-num text-[10.5px] text-neutral-500 bg-white/[0.08] rounded-full px-1.5 py-px">
+ {misses.length}
+ </span>
+ )}
+ </button>
+ </aside>
+
+ {/* 右侧:详情。选中类时表单 + 实例列表双栏铺开,提高宽屏利用率 */}
+ <div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">
+ {/* 放宽到 6xl 供三列铺开;misses/关系/概览各自带 max-w-xl 内衬不受影响 */}
+ <div className="max-w-6xl">
+ {sel?.kind === "misses" ? (
+ <div className="max-w-xl">
+ <MissesPanel kbId={kb.id} misses={misses} onChanged={refresh} onError={onError} />
+ </div>
+ ) : sel?.kind === "new-class" || selectedClass ? (
+ /* lg 两列(表单 | 属性+实例堆叠);xl 三列并排(包装器 xl:contents 解散入栅格) */
+ <div className="grid gap-4 items-start lg:grid-cols-[minmax(0,24rem)_minmax(0,1fr)] xl:grid-cols-[minmax(0,22rem)_minmax(0,1fr)_minmax(0,1fr)]">
+ <div className="glass rounded-xl p-4">
+ <ClassForm
+ key={
+ selectedClass?.id ?? `new-${sel?.kind === "new-class" ? sel.parentId : "root"}`
+ }
+ kbId={kb.id}
+ existing={selectedClass}
+ parentId={
+ sel?.kind === "new-class" ? sel.parentId : (selectedClass?.parent_id ?? null)
+ }
+ allTypes={entity_types}
+ onNewSub={
+ selectedClass
+ ? () => setSel({ kind: "new-class", parentId: selectedClass.id })
+ : undefined
+ }
+ onDone={(createdId) => {
+ // 新建成功即选中它:立刻能看到、能继续编辑
+ if (sel?.kind === "new-class")
+ setSel(createdId ? { kind: "class", id: createdId } : null);
+ refresh();
+ }}
+ onError={onError}
+ />
+ </div>
+ {/* lg 右列堆叠属性+实例;xl 解散为两个独立栅格列 */}
+ {selectedClass && (
+ <div className="grid gap-4 items-start xl:contents">
+ <AttributesCard
+ kbId={kb.id}
+ type={selectedClass}
+ attributes={relation_types.filter(
+ (r) => r.kind === "attribute" && r.domain_type_id === selectedClass.id,
+ )}
+ onChanged={refresh}
+ onError={onError}
+ />
+ <InstancesCard kbId={kb.id} type={selectedClass} />
+ </div>
+ )}
+ </div>
+ ) : sel?.kind === "new-relation" || selectedProp ? (
+ <div className="glass rounded-xl p-4 max-w-xl">
+ <PropertyForm
+ key={selectedProp?.id ?? "new"}
+ kbId={kb.id}
+ existing={selectedProp}
+ onDone={(createdId) => {
+ if (sel?.kind === "new-relation")
+ setSel(createdId ? { kind: "relation", id: createdId } : null);
+ refresh();
+ }}
+ onError={onError}
+ />
+ </div>
+ ) : (
+ /* 概览:未选中任何条目 */
+ <div className="glass rounded-xl p-6 max-w-xl">
+ <PageTitle className="mb-1">{S.ontology.title}</PageTitle>
+ <p className="text-xs text-neutral-500 u-num">
+ {S.ontology.overviewStats(entity_types.length, relations.length)}
+ </p>
+ <p className="mt-3 text-sm text-neutral-400">{S.ontology.overviewHint}</p>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/* ---------- 实例列表:选中类的实体(服务端分页,点击进图谱) ---------- */
+
+function InstancesCard({ kbId, type }: { kbId: string; type: EntityTypeView }) {
+ const PER = 12;
+ const [page, setPage] = useState(0);
+ useEffect(() => setPage(0), [type.id]);
+ const q = useQuery({
+ queryKey: ["type-entities", kbId, type.id, page],
+ queryFn: () => api.typeEntities(kbId, type.id, page, PER),
+ });
+ const total = q.data?.total ?? 0;
+ const rows = q.data?.entities ?? [];
+ if (!q.isPending && total === 0) return null; // 没有实例时不占版面
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="mb-1.5 flex items-baseline gap-2">
+ <h3 className="text-sm font-bold text-neutral-200">{S.ontology.instances}</h3>
+ <span className="u-num text-xs text-neutral-500">{total}</span>
+ </div>
+ <div className="divide-y divide-white/[0.06]">
+ {rows.map((e) => (
+ <Link
+ key={e.id}
+ to="/graph"
+ search={{ entity: e.id }}
+ className="flex items-center gap-2 py-1.5 text-sm text-neutral-300 hover:text-white"
+ >
+ <span
+ className={`h-2 w-2 shrink-0 ${type.shape === "square" ? "" : "rounded-full"}`}
+ style={{ background: type.color }}
+ />
+ <span className="truncate">{e.name}</span>
+ <span className="ml-auto shrink-0 u-num text-[10.5px] text-neutral-600">
+ {S.ontology.instanceFacts(e.fact_count)}
+ </span>
+ </Link>
+ ))}
+ </div>
+ <Pager total={total} pageSize={PER} page={page} onPage={setPage} />
+ </div>
+ );
+}
+
+/* ---------- 属性卡片:选中类的字面值字段(行内增改删) ---------- */
+
+function AttributesCard({
+ kbId,
+ type,
+ attributes,
+ onChanged,
+ onError,
+}: {
+ kbId: string;
+ type: EntityTypeView;
+ attributes: RelationTypeView[];
+ onChanged: () => void;
+ onError: (e: unknown) => void;
+}) {
+ // 行内编辑:一次只展开一行(属性 id 或 "new")
+ const [editing, setEditing] = useState<string | null>(null);
+ useEffect(() => setEditing(null), [type.id]);
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="mb-1 flex items-baseline gap-2">
+ <h3 className="text-sm font-bold text-neutral-200">{S.ontology.attributes}</h3>
+ {attributes.length > 0 && (
+ <span className="u-num text-xs text-neutral-500">{attributes.length}</span>
+ )}
+ </div>
+ <p className="text-xs text-neutral-500 mb-2">{S.ontology.attributesHint}</p>
+ <div className="divide-y divide-white/[0.06]">
+ {attributes.map((a) =>
+ editing === a.id ? (
+ <AttributeForm
+ key={a.id}
+ kbId={kbId}
+ typeId={type.id}
+ existing={a}
+ onDone={() => {
+ setEditing(null);
+ onChanged();
+ }}
+ onCancel={() => setEditing(null)}
+ onError={onError}
+ />
+ ) : (
+ <button
+ key={a.id}
+ onClick={() => setEditing(a.id)}
+ className="w-full flex items-center gap-2 py-1.5 text-sm text-left text-neutral-300 hover:text-white"
+ >
+ <span className="truncate">{a.label}</span>
+ <Chip tone="neutral">{S.ontology.datatypeNames[a.datatype ?? "text"]}</Chip>
+ {a.unit && <span className="text-xs text-neutral-500 shrink-0">{a.unit}</span>}
+ {a.functional && <Chip tone="info">1:1</Chip>}
+ <span className="ml-auto shrink-0 u-num text-[10.5px] text-neutral-600">
+ {S.ontology.usage(a.usage)}
+ </span>
+ </button>
+ ),
+ )}
+ </div>
+ {editing === "new" ? (
+ <div className="pt-2">
+ <AttributeForm
+ kbId={kbId}
+ typeId={type.id}
+ existing={null}
+ onDone={() => {
+ setEditing(null);
+ onChanged();
+ }}
+ onCancel={() => setEditing(null)}
+ onError={onError}
+ />
+ </div>
+ ) : (
+ <button
+ onClick={() => setEditing("new")}
+ className="mt-1.5 flex items-center gap-1.5 text-[13px] text-neutral-500 hover:text-neutral-200 transition-colors"
+ >
+ <Plus size={13} />
+ {S.ontology.newAttribute}
+ </button>
+ )}
+ </div>
+ );
+}
+
+function AttributeForm({
+ kbId,
+ typeId,
+ existing,
+ onDone,
+ onCancel,
+ onError,
+}: {
+ kbId: string;
+ typeId: string;
+ existing: RelationTypeView | null;
+ onDone: () => void;
+ onCancel: () => void;
+ onError: (e: unknown) => void;
+}) {
+ const [key, setKey] = useState(existing?.key ?? "");
+ const [label, setLabel] = useState(existing?.label ?? "");
+ const [datatype, setDatatype] = useState(existing?.datatype ?? "text");
+ const [unit, setUnit] = useState(existing?.unit ?? "");
+ // 单值 = functional:新值经时态引擎闭合旧值(属性历史的来源)。多数属性如此,默认开
+ const [single, setSingle] = useState(existing?.functional ?? true);
+ const [description, setDescription] = useState(existing?.description ?? "");
+
+ const save = useMutation({
+ mutationFn: async (): Promise<unknown> =>
+ existing
+ ? api.updateRelationType(kbId, existing.id, {
+ label,
+ temporal: existing.temporal,
+ functional: single,
+ inverse_functional: false,
+ description,
+ datatype,
+ unit,
+ })
+ : api.createRelationType(kbId, {
+ key,
+ label,
+ kind: "attribute",
+ domain_type_id: typeId,
+ temporal: "state",
+ functional: single,
+ inverse_functional: false,
+ description,
+ datatype,
+ unit,
+ }),
+ onSuccess: () => {
+ toast.success(existing ? S.toast.saved : S.toast.created);
+ onDone();
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteRelationType(kbId, existing!.id),
+ onSuccess: () => {
+ toast.success(S.toast.deleted);
+ onDone();
+ },
+ onError,
+ });
+
+ const lbl = "block text-xs font-medium text-neutral-500 mb-1";
+ return (
+ <div className="py-2.5 space-y-2.5">
+ {!existing && (
+ <div className="flex gap-2">
+ <div className="flex-1">
+ <label className={lbl}>{S.ontology.key}</label>
+ <Input
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ className="w-full"
+ placeholder="salary"
+ />
+ </div>
+ <div className="flex-1">
+ <label className={lbl}>{S.ontology.label}</label>
+ <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ </div>
+ </div>
+ )}
+ {existing && (
+ <div>
+ <label className={lbl}>{S.ontology.label}</label>
+ <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ </div>
+ )}
+ <div className="flex gap-2">
+ <div className="flex-1">
+ <label className={lbl}>{S.ontology.attrDatatype}</label>
+ <Dropdown
+ value={datatype}
+ onChange={(v) => setDatatype(v as typeof datatype)}
+ className="w-full"
+ options={(["text", "number", "date", "bool"] as const).map((d) => ({
+ value: d,
+ label: S.ontology.datatypeNames[d],
+ }))}
+ />
+ </div>
+ <div className="flex-1">
+ <label className={lbl}>
+ {S.ontology.attrUnit}{" "}
+ <span className="text-neutral-600">({S.ontology.attrUnitHint})</span>
+ </label>
+ <Input value={unit} onChange={(e) => setUnit(e.target.value)} className="w-full" />
+ </div>
+ </div>
+ <label className="flex items-center gap-2 text-[13px] text-neutral-300">
+ <input type="checkbox" checked={single} onChange={(e) => setSingle(e.target.checked)} />
+ {S.ontology.attrSingle}
+ </label>
+ <div>
+ <label className={lbl}>{S.ontology.description}</label>
+ <textarea
+ className="input-dark w-full px-3 py-2 text-sm min-h-[3.5rem] resize-y"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </div>
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ onClick={() => save.mutate()}
+ disabled={save.isPending || !label.trim() || (!existing && !key.trim())}
+ >
+ {S.ontology.save}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onCancel}>
+ {S.ontology.cancel}
+ </Button>
+ {existing && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="ml-auto"
+ disabled={existing.usage > 0}
+ title={existing.usage > 0 ? S.ontology.deleteBlocked : undefined}
+ onClick={() => remove.mutate()}
+ >
+ {S.ontology.delete}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/* ---------- 左栏小节头 ---------- */
+
+/* ---------- 类层级树(可折叠;filter 时拍平) ---------- */
+
+function ClassTree({
+ types,
+ filter,
+ collapsed,
+ onToggle,
+ selectedId,
+ onSelect,
+ pageSize,
+}: {
+ types: EntityTypeView[];
+ filter: string;
+ collapsed: Set<string>;
+ onToggle: (id: string) => void;
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ pageSize: number;
+}) {
+ const rows = useMemo(() => {
+ const q = filter.trim().toLowerCase();
+ if (q) {
+ // filter 模式:拍平命中项(label/key 都参与匹配)
+ return types
+ .filter((t) => t.label.toLowerCase().includes(q) || t.key.toLowerCase().includes(q))
+ .map((t) => ({ t, depth: 0, hasChildren: false }));
+ }
+ const children = new Map<string | null, EntityTypeView[]>();
+ for (const t of types) {
+ const p = t.parent_id ?? null;
+ if (!children.has(p)) children.set(p, []);
+ children.get(p)!.push(t);
+ }
+ const out: { t: EntityTypeView; depth: number; hasChildren: boolean }[] = [];
+ const walk = (parent: string | null, depth: number) => {
+ for (const t of children.get(parent) ?? []) {
+ const kids = children.get(t.id) ?? [];
+ out.push({ t, depth, hasChildren: kids.length > 0 });
+ if (!collapsed.has(t.id)) walk(t.id, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+ }, [types, filter, collapsed]);
+
+ // 半屏分页:过滤词变化回第一页
+ const [page, setPage] = useState(0);
+ useEffect(() => setPage(0), [filter]);
+ const { rows: paged, safe } = pageSlice(rows, page, pageSize);
+
+ return (
+ <div className="space-y-0.5">
+ {paged.map(({ t, depth, hasChildren }) => (
+ <button
+ key={t.id}
+ onClick={() => onSelect(t.id)}
+ style={{ paddingLeft: `${6 + depth * 14}px` }}
+ className={cn(
+ "w-full text-left rounded-lg py-1.5 pr-2 text-[13px] flex items-center gap-1.5",
+ selectedId === t.id
+ ? "u-nav-active"
+ : "hover:bg-white/[0.05] text-neutral-400 hover:text-neutral-200",
+ )}
+ >
+ {/* 折叠柄:有子类才渲染,点击不选中 */}
+ {hasChildren ? (
+ <span
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggle(t.id);
+ }}
+ className="shrink-0 text-neutral-600 hover:text-neutral-300"
+ >
+ <ChevronRight
+ size={12}
+ className={cn("transition-transform", !collapsed.has(t.id) && "rotate-90")}
+ />
+ </span>
+ ) : (
+ <span className="w-3 shrink-0" />
+ )}
+ {/* 方形是直角:与圆形拉开区分度(图谱节点同理) */}
+ <span
+ className={`h-2.5 w-2.5 shrink-0 ${t.shape === "square" ? "" : "rounded-full"}`}
+ style={{ background: t.color }}
+ />
+ {/* 不在列表里放逐项用量读数:数量级上来后统计和渲染都是负担,用量看表单 */}
+ <span className="truncate">{t.label}</span>
+ </button>
+ ))}
+ <Pager total={rows.length} pageSize={pageSize} page={safe} onPage={setPage} />
+ </div>
+ );
+}
+
+/* ---------- 关系列表 ---------- */
+
+function PropertyList({
+ relations,
+ filter,
+ selectedId,
+ onSelect,
+ pageSize,
+}: {
+ relations: RelationTypeView[];
+ filter: string;
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ pageSize: number;
+}) {
+ const q = filter.trim().toLowerCase();
+ const rows = q
+ ? relations.filter(
+ (r) => r.label.toLowerCase().includes(q) || r.key.toLowerCase().includes(q),
+ )
+ : relations;
+ // 半屏分页:过滤词变化回第一页
+ const [page, setPage] = useState(0);
+ useEffect(() => setPage(0), [filter]);
+ const { rows: paged, safe } = pageSlice(rows, page, pageSize);
+ return (
+ <div className="space-y-0.5">
+ {paged.map((r) => (
+ <button
+ key={r.id}
+ onClick={() => onSelect(r.id)}
+ style={{ paddingLeft: "6px" }}
+ className={cn(
+ "w-full text-left rounded-lg py-1.5 pr-2 text-[13px] flex items-center gap-1.5",
+ selectedId === r.id
+ ? "u-nav-active"
+ : "hover:bg-white/[0.05] text-neutral-400 hover:text-neutral-200",
+ )}
+ >
+ {/* 前导只留折叠柄槽:文字起点对齐类行"标识点"的左端 */}
+ <span className="w-3 shrink-0" />
+ <span className="truncate">{r.label}</span>
+ {r.functional && <Chip tone="info">1:1</Chip>}
+ </button>
+ ))}
+ <Pager total={rows.length} pageSize={pageSize} page={safe} onPage={setPage} />
+ </div>
+ );
+}
+
+/* ---------- 类表单 ---------- */
+
+/** 父类下拉的候选:树序 + 缩进(层级可见),排除自己与全部后代(防成环)。 */
+function parentOptions(
+ allTypes: EntityTypeView[],
+ selfId: string | undefined,
+): { value: string; label: string; indent: number }[] {
+ const excluded = new Set<string>();
+ if (selfId) {
+ excluded.add(selfId);
+ // 收后代:反复扫描直到收敛(类的数量级很小,O(n²) 无所谓)
+ let grew = true;
+ while (grew) {
+ grew = false;
+ for (const t of allTypes) {
+ if (t.parent_id && excluded.has(t.parent_id) && !excluded.has(t.id)) {
+ excluded.add(t.id);
+ grew = true;
+ }
+ }
+ }
+ }
+ const children = new Map<string | null, EntityTypeView[]>();
+ for (const t of allTypes) {
+ const p = t.parent_id ?? null;
+ if (!children.has(p)) children.set(p, []);
+ children.get(p)!.push(t);
+ }
+ const out: { value: string; label: string; indent: number }[] = [];
+ const walk = (parent: string | null, depth: number) => {
+ for (const t of children.get(parent) ?? []) {
+ if (excluded.has(t.id)) continue;
+ out.push({ value: t.id, label: t.label, indent: depth });
+ walk(t.id, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+}
+
+function ClassForm({
+ kbId,
+ existing,
+ parentId,
+ allTypes,
+ onNewSub,
+ onDone,
+ onError,
+}: {
+ kbId: string;
+ existing: EntityTypeView | null;
+ parentId: string | null;
+ allTypes: EntityTypeView[];
+ /** 编辑已有类时提供:以当前类为父级新建子类 */
+ onNewSub?: () => void;
+ /** 创建成功时携带新 id,编辑成功时为 undefined */
+ onDone: (createdId?: string) => void;
+ onError: (e: unknown) => void;
+}) {
+ const [key, setKey] = useState(existing?.key ?? "");
+ const [label, setLabel] = useState(existing?.label ?? "");
+ const [color, setColor] = useState(existing?.color ?? "#8ea5bd");
+ const [shape, setShape] = useState<"circle" | "square">(existing?.shape ?? "circle");
+ const [parent, setParent] = useState<string>(parentId ?? "");
+ const [description, setDescription] = useState(existing?.description ?? "");
+
+ useEffect(() => setParent(parentId ?? ""), [parentId]);
+
+ const save = useMutation({
+ mutationFn: async (): Promise<unknown> =>
+ existing
+ ? api.updateEntityType(kbId, existing.id, {
+ label,
+ color,
+ shape,
+ parent_id: parent || null,
+ description,
+ })
+ : api.createEntityType(kbId, {
+ key,
+ label,
+ color,
+ shape,
+ parent_id: parent || null,
+ description,
+ }),
+ onSuccess: (res) => {
+ toast.success(existing ? S.toast.saved : S.toast.created);
+ onDone(existing ? undefined : (res as { id?: string })?.id);
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteEntityType(kbId, existing!.id),
+ onSuccess: () => {
+ toast.success(S.toast.deleted);
+ onDone();
+ },
+ onError,
+ });
+
+ const lbl = "block text-xs font-medium text-neutral-500 mb-1";
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <span
+ className={`h-3 w-3 ${shape === "square" ? "" : "rounded-full"}`}
+ style={{ background: color }}
+ />
+ <span className="font-bold text-neutral-100">{existing?.label ?? S.ontology.newClass}</span>
+ {/* key 是纯技术标识:已存在时干脆不展示,只在创建时输入 */}
+ {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}
+ {existing && (
+ <span className="ml-auto text-xs text-neutral-500">{S.ontology.usage(existing.usage)}</span>
+ )}
+ </div>
+ {!existing && (
+ <div>
+ <label className={lbl}>
+ {S.ontology.key}{" "}
+ <span className="text-neutral-600">({S.ontology.keyHint})</span>
+ </label>
+ <Input
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ className="w-full"
+ placeholder="contract"
+ />
+ </div>
+ )}
+ <div>
+ <label className={lbl}>{S.ontology.label}</label>
+ <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ </div>
+ <div>
+ <label className={lbl}>{S.ontology.shapeColor}</label>
+ <div className="flex items-center gap-2">
+ <ColorPicker value={color} onChange={setColor} shape={shape} />
+ {/* 形状:与图谱节点渲染一一对应(circle=四层圆 / square=四层方) */}
+ <div className="flex rounded-lg overflow-hidden border border-white/10">
+ {(["circle", "square"] as const).map((sh) => (
+ <button
+ key={sh}
+ onClick={() => setShape(sh)}
+ title={sh}
+ className={`h-8 w-10 grid place-items-center transition-colors ${
+ shape === sh
+ ? "bg-white/[0.12] text-white"
+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
+ }`}
+ >
+ <span
+ className={`h-3 w-3 border-[1.5px] border-current ${
+ sh === "circle" ? "rounded-full" : ""
+ }`}
+ />
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ <div>
+ <label className={lbl}>{S.ontology.parent}</label>
+ <SearchSelect
+ value={parent}
+ onChange={setParent}
+ className="w-full"
+ options={[
+ { value: "", label: S.ontology.noParent },
+ ...parentOptions(allTypes, existing?.id),
+ ]}
+ />
+ </div>
+ <div>
+ <label className={lbl}>{S.ontology.description}</label>
+ {/* 语义指引:整段注入抽取 prompt,直接影响抽取归类质量 */}
+ <textarea
+ className="input-dark w-full px-3 py-2 text-sm min-h-[4.5rem] resize-y"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ <p className="mt-1 text-[10.5px] text-neutral-600">{S.ontology.descriptionHint}</p>
+ </div>
+ <div className="flex gap-2 pt-1">
+ <Button size="sm" onClick={() => save.mutate()} disabled={save.isPending || !label.trim()}>
+ {S.ontology.save}
+ </Button>
+ {onNewSub && (
+ <Button size="sm" variant="ghost" onClick={onNewSub}>
+ {S.ontology.newSubClass}
+ </Button>
+ )}
+ {existing && !existing.builtin && (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={existing.usage > 0}
+ title={existing.usage > 0 ? S.ontology.deleteBlocked : undefined}
+ onClick={() => remove.mutate()}
+ >
+ {S.ontology.delete}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/* ---------- 关系表单 ---------- */
+
+function PropertyForm({
+ kbId,
+ existing,
+ onDone,
+ onError,
+}: {
+ kbId: string;
+ existing: RelationTypeView | null;
+ onDone: (createdId?: string) => void;
+ onError: (e: unknown) => void;
+}) {
+ const [key, setKey] = useState(existing?.key ?? "");
+ const [label, setLabel] = useState(existing?.label ?? "");
+ const [temporal, setTemporal] = useState(existing?.temporal ?? "state");
+ const [functional, setFunctional] = useState(existing?.functional ?? false);
+ const [inverseFunctional, setInverseFunctional] = useState(
+ existing?.inverse_functional ?? false,
+ );
+ const [description, setDescription] = useState(existing?.description ?? "");
+
+ const save = useMutation({
+ mutationFn: async (): Promise<unknown> =>
+ existing
+ ? api.updateRelationType(kbId, existing.id, {
+ label,
+ temporal,
+ functional,
+ inverse_functional: inverseFunctional,
+ description,
+ })
+ : api.createRelationType(kbId, {
+ key,
+ label,
+ temporal,
+ functional,
+ inverse_functional: inverseFunctional,
+ description,
+ }),
+ onSuccess: (res) => {
+ toast.success(existing ? S.toast.saved : S.toast.created);
+ onDone(existing ? undefined : (res as { id?: string })?.id);
+ },
+ onError,
+ });
+ const remove = useMutation({
+ mutationFn: () => api.deleteRelationType(kbId, existing!.id),
+ onSuccess: () => {
+ toast.success(S.toast.deleted);
+ onDone();
+ },
+ onError,
+ });
+
+ const lbl = "block text-xs font-medium text-neutral-500 mb-1";
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center gap-2">
+ <span className="font-bold text-neutral-100">
+ {existing?.label ?? S.ontology.newProperty}
+ </span>
+ {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}
+ {existing && (
+ <span className="ml-auto text-xs text-neutral-500">{S.ontology.usage(existing.usage)}</span>
+ )}
+ </div>
+ {!existing && (
+ <div>
+ <label className={lbl}>
+ {S.ontology.key}{" "}
+ <span className="text-neutral-600">({S.ontology.keyHint})</span>
+ </label>
+ <Input
+ value={key}
+ onChange={(e) => setKey(e.target.value)}
+ className="w-full"
+ placeholder="signed_with"
+ />
+ </div>
+ )}
+ <div>
+ <label className={lbl}>{S.ontology.label}</label>
+ <Input value={label} onChange={(e) => setLabel(e.target.value)} className="w-full" />
+ </div>
+ <div>
+ <label className={lbl}>{S.ontology.temporal}</label>
+ <Dropdown
+ value={temporal}
+ onChange={setTemporal}
+ className="w-full"
+ options={[
+ { value: "state", label: S.ontology.temporalState },
+ { value: "event", label: S.ontology.temporalEvent },
+ { value: "eternal", label: S.ontology.temporalEternal },
+ ]}
+ />
+ </div>
+ <label className="flex items-center gap-2 text-sm text-neutral-300">
+ <input
+ type="checkbox"
+ checked={functional}
+ onChange={(e) => setFunctional(e.target.checked)}
+ />
+ {S.ontology.functional}
+ </label>
+ <label className="flex items-center gap-2 text-sm text-neutral-300">
+ <input
+ type="checkbox"
+ checked={inverseFunctional}
+ onChange={(e) => setInverseFunctional(e.target.checked)}
+ />
+ {S.ontology.inverseFunctional}
+ </label>
+ <div>
+ <label className={lbl}>{S.ontology.description}</label>
+ <textarea
+ className="input-dark w-full px-3 py-2 text-sm min-h-[4.5rem] resize-y"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ <p className="mt-1 text-[10.5px] text-neutral-600">{S.ontology.descriptionHint}</p>
+ </div>
+ <div className="flex gap-2 pt-1">
+ <Button size="sm" onClick={() => save.mutate()} disabled={save.isPending || !label.trim()}>
+ {S.ontology.save}
+ </Button>
+ {existing && !existing.builtin && (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={existing.usage > 0}
+ title={existing.usage > 0 ? S.ontology.deleteBlocked : undefined}
+ onClick={() => remove.mutate()}
+ >
+ {S.ontology.delete}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/* ---------- 未匹配信号 + AI 建议 ---------- */
+
+function MissesPanel({
+ kbId,
+ misses,
+ onChanged,
+ onError,
+}: {
+ kbId: string;
+ misses: OntologyMiss[];
+ onChanged: () => void;
+ onError: (e: unknown) => void;
+}) {
+ const [proposals, setProposals] = useState<OntologyProposals | null>(null);
+
+ const suggest = useMutation({
+ mutationFn: () => api.suggestOntology(kbId),
+ onSuccess: setProposals,
+ onError,
+ });
+ const dismiss = useMutation({
+ mutationFn: ({ kind, key }: { kind: string; key: string }) =>
+ api.dismissMiss(kbId, kind, key),
+ onSuccess: onChanged,
+ onError,
+ });
+ const approveEntity = useMutation({
+ mutationFn: (p: { key: string; label: string }) =>
+ api.createEntityType(kbId, { key: p.key, label: p.label }),
+ onSuccess: (_data, p) => {
+ // 已采纳:从提案列表移除,并顺带清掉对应的未匹配统计 chip(本体已覆盖)
+ toast.success(S.toast.added);
+ setProposals(
+ (prev) =>
+ prev && { ...prev, entity_types: prev.entity_types.filter((x) => x.key !== p.key) },
+ );
+ api.dismissMiss(kbId, "entity_type", p.key).catch(() => {});
+ onChanged();
+ },
+ onError,
+ });
+ const approveRelation = useMutation({
+ mutationFn: (p: { key: string; label: string; temporal?: string; functional?: boolean }) =>
+ api.createRelationType(kbId, {
+ key: p.key,
+ label: p.label,
+ temporal: p.temporal ?? "state",
+ functional: p.functional ?? false,
+ }),
+ onSuccess: (_data, p) => {
+ toast.success(S.toast.added);
+ setProposals(
+ (prev) =>
+ prev && { ...prev, relation_types: prev.relation_types.filter((x) => x.key !== p.key) },
+ );
+ api.dismissMiss(kbId, "relation_type", p.key).catch(() => {});
+ onChanged();
+ },
+ onError,
+ });
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="flex items-center gap-3 mb-1">
+ <h3 className="text-sm font-bold text-neutral-200">{S.ontology.misses}</h3>
+ {misses.length > 0 && (
+ <Button size="sm" variant="ghost" onClick={() => suggest.mutate()} disabled={suggest.isPending}>
+ {suggest.isPending ? S.ontology.suggesting : S.ontology.suggest}
+ </Button>
+ )}
+ </div>
+ <p className="text-xs text-neutral-500 mb-3">{S.ontology.missesHint}</p>
+
+ {misses.length === 0 ? (
+ <p className="text-sm text-neutral-500">{S.ontology.noMisses}</p>
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {misses.map((m) => (
+ <span
+ key={`${m.kind}:${m.key}`}
+ className="glass rounded-full px-2.5 py-1 text-xs flex items-center gap-1.5"
+ title={m.example ?? ""}
+ >
+ <Chip tone={m.kind === "entity_type" ? "info" : "violet"}>
+ {m.kind === "entity_type" ? "C" : "P"}
+ </Chip>
+ <span className="font-mono text-neutral-300">{m.key}</span>
+ <span className="text-neutral-500">×{m.count}</span>
+ <button
+ onClick={() => dismiss.mutate({ kind: m.kind, key: m.key })}
+ className="text-neutral-600 hover:text-neutral-300"
+ >
+ ✕
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+
+ {proposals && (
+ <div className="mt-4 border-t border-white/10 pt-3">
+ <h4 className="text-xs font-bold text-neutral-400 mb-2">{S.ontology.proposals}</h4>
+ <div className="space-y-1.5">
+ {proposals.entity_types.map((p) => (
+ <div key={p.key} className="flex items-center gap-2 text-sm">
+ <Chip tone="info">C</Chip>
+ <span className="font-mono text-neutral-300">{p.key}</span>
+ <span className="text-neutral-200">{p.label}</span>
+ {p.reason && <span className="text-xs text-neutral-500 truncate">{p.reason}</span>}
+ <Button
+ size="sm"
+ className="ml-auto"
+ onClick={() => approveEntity.mutate(p)}
+ disabled={approveEntity.isPending}
+ >
+ {S.ontology.approve}
+ </Button>
+ </div>
+ ))}
+ {proposals.relation_types.map((p) => (
+ <div key={p.key} className="flex items-center gap-2 text-sm">
+ <Chip tone="violet">P</Chip>
+ <span className="font-mono text-neutral-300">{p.key}</span>
+ <span className="text-neutral-200">{p.label}</span>
+ {p.temporal && <Chip tone="neutral">{p.temporal}</Chip>}
+ {p.reason && <span className="text-xs text-neutral-500 truncate">{p.reason}</span>}
+ <Button
+ size="sm"
+ className="ml-auto"
+ onClick={() => approveRelation.mutate(p)}
+ disabled={approveRelation.isPending}
+ >
+ {S.ontology.approve}
+ </Button>
+ </div>
+ ))}
+ {proposals.entity_types.length === 0 && proposals.relation_types.length === 0 && (
+ <p className="text-sm text-neutral-500">—</p>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/pages/Review.tsx b/web/src/pages/Review.tsx
new file mode 100644
index 00000000..92f76cba
--- /dev/null
+++ b/web/src/pages/Review.tsx
@@ -0,0 +1,715 @@
+import { useEffect, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ api,
+ type ConflictItem,
+ type FactReviewItem,
+ type MergeLog,
+ type ReviewHistoryEvent,
+ type ReviewItem,
+ type ReviewSide,
+} from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { Chip, type ChipTone, Pager, RAIL_CLS, pageSlice, cn } from "../ui";
+
+const DUP_PAGE = 6;
+const FACT_PAGE = 10;
+const MERGE_PAGE = 10;
+const CONFLICT_PAGE = 8;
+
+const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
+
+function dateRange(from: string | null, to: string | null): string | null {
+ if (!from && !to) return null;
+ return `${ym(from) ?? "…"} → ${ym(to) ?? S.review.ongoing}`;
+}
+
+function SideCard({ side }: { side: ReviewSide }) {
+ return (
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <span
+ className="h-2.5 w-2.5 rounded-full shrink-0"
+ style={{ backgroundColor: side.color }}
+ />
+ <span className="text-sm font-medium text-white truncate">{side.name}</span>
+ {side.disambiguator && (
+ <span className="text-xs text-neutral-500 truncate">· {side.disambiguator}</span>
+ )}
+ </div>
+ <div className="text-xs text-neutral-500 mb-2">
+ {side.type_label} · {S.review.factsCount(side.degree)}
+ </div>
+ {side.top_facts.length > 0 ? (
+ <ul className="space-y-1">
+ {side.top_facts.map((f, i) => (
+ <li key={i} className="text-xs text-neutral-400 truncate">
+ {f}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-xs text-neutral-600">{S.review.noFacts}</p>
+ )}
+ </div>
+ );
+}
+
+function DuplicateCard({
+ item,
+ busy,
+ onDecide,
+}: {
+ item: ReviewItem;
+ busy: boolean;
+ onDecide: (action: "merge" | "keep") => void;
+}) {
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="flex gap-4">
+ <SideCard side={item.left} />
+ <div className="self-center text-neutral-600 text-sm shrink-0">≟</div>
+ <SideCard side={item.right} />
+ </div>
+ <div className="mt-3 pt-3 flex items-center gap-3 border-t border-[var(--u-line)]">
+ <span
+ className={`u-chip ${item.stage === "human" ? "u-chip-warn" : "u-chip-neutral"}`}
+ >
+ {item.stage === "human" ? S.review.stageHuman : S.review.stageAdjudicating}
+ </span>
+ <span className="text-xs text-neutral-500">
+ {S.review.similarity(Math.round(item.score * 100))}
+ </span>
+ {item.reason && (
+ <span className="text-xs text-neutral-600 truncate min-w-0">{item.reason}</span>
+ )}
+ <div className="ml-auto flex gap-2 shrink-0">
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ disabled={busy}
+ onClick={() => onDecide("keep")}
+ >
+ {S.review.keep}
+ </button>
+ <button
+ className="u-btn u-btn-primary px-3 py-1.5 text-xs"
+ disabled={busy}
+ onClick={() => onDecide("merge")}
+ >
+ {S.review.merge}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function FactRow({
+ fact,
+ busy,
+ onConfirm,
+ onReject,
+}: {
+ fact: FactReviewItem;
+ busy: boolean;
+ onConfirm: () => void;
+ onReject: () => void;
+}) {
+ const range = dateRange(fact.valid_from, fact.valid_to);
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-medium text-white">{fact.subject_name}</span>
+ <span className="text-xs text-neutral-500">— {fact.predicate_label} →</span>
+ <span className="text-sm font-medium text-white">{fact.object_name ?? "?"}</span>
+ {range && <span className="text-xs text-neutral-500">({range})</span>}
+ <span className="u-chip u-chip-warn ml-auto">
+ {S.review.confidence(Math.round(fact.confidence * 100))}
+ </span>
+ </div>
+ {fact.quote && (
+ <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">“{fact.quote}”</p>
+ )}
+ <div className="mt-3 flex gap-2 justify-end">
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
+ disabled={busy}
+ onClick={onReject}
+ >
+ {S.review.reject}
+ </button>
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ disabled={busy}
+ onClick={onConfirm}
+ >
+ {S.review.confirm}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** 时态冲突行:旧事实 vs 新事实,三个动作(Close old / Keep both / Reject new)。 */
+function ConflictRow({
+ conflict,
+ busy,
+ onResolve,
+}: {
+ conflict: ConflictItem;
+ busy: boolean;
+ onResolve: (action: "close" | "keep" | "reject_new", closeAt?: string) => void;
+}) {
+ const [closeAt, setCloseAt] = useState("");
+ const c = conflict;
+ const needsDate = !c.new_valid_from;
+ // close_at 输入按天精度转 RFC3339
+ const closeAtIso = /^\d{4}-\d{2}-\d{2}$/.test(closeAt.trim())
+ ? `${closeAt.trim()}T00:00:00Z`
+ : undefined;
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-medium text-white">{c.old_subject}</span>
+ <span className="text-xs text-neutral-500">— {c.predicate_label} →</span>
+ <span className="text-sm font-medium text-white">{c.old_object ?? "?"}</span>
+ {c.old_valid_from && (
+ <span className="u-num text-xs text-neutral-500">
+ ({S.review.conflictSince(c.old_valid_from.slice(0, 10))})
+ </span>
+ )}
+ <span className="text-xs text-neutral-600">{S.review.conflictVs}</span>
+ <span className="text-sm font-medium text-white">{c.new_subject}</span>
+ <span className="text-xs text-neutral-500">— {c.predicate_label} →</span>
+ <span className="text-sm font-medium text-white">{c.new_object ?? "?"}</span>
+ {c.new_valid_from && (
+ <span className="u-num text-xs text-neutral-500">
+ ({S.review.conflictSince(c.new_valid_from.slice(0, 10))})
+ </span>
+ )}
+ <span className="u-chip u-chip-warn ml-auto">
+ {S.review.conflictReason[c.reason] ?? c.reason}
+ </span>
+ </div>
+ <div className="mt-3 flex items-center gap-2 justify-end">
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
+ disabled={busy}
+ onClick={() => onResolve("reject_new")}
+ >
+ {S.review.rejectNew}
+ </button>
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ disabled={busy}
+ onClick={() => onResolve("keep")}
+ >
+ {S.review.keepBoth}
+ </button>
+ {needsDate && (
+ <input
+ className="input-dark u-num w-28 px-2 py-1.5 text-xs text-center"
+ placeholder={S.review.closeAtPlaceholder}
+ value={closeAt}
+ onChange={(e) => setCloseAt(e.target.value)}
+ />
+ )}
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ disabled={busy || (needsDate && !closeAtIso)}
+ onClick={() => onResolve("close", closeAtIso)}
+ >
+ {c.new_valid_from
+ ? S.review.closeOldAt(c.new_valid_from.slice(0, 10))
+ : S.review.closeOld}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** "文档新版没再提"的事实行:Reject(抽取错误)或 Close at date(这事结束了)。 */
+function UnconfirmedRow({
+ fact,
+ busy,
+ onReject,
+ onClose,
+}: {
+ fact: FactReviewItem;
+ busy: boolean;
+ onReject: () => void;
+ onClose: (validTo: string) => void;
+}) {
+ const [closeAt, setCloseAt] = useState("");
+ const closeAtIso = /^\d{4}-\d{2}-\d{2}$/.test(closeAt.trim())
+ ? `${closeAt.trim()}T00:00:00Z`
+ : undefined;
+ const range = dateRange(fact.valid_from, fact.valid_to);
+
+ return (
+ <div className="glass rounded-xl p-4">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-medium text-white">{fact.subject_name}</span>
+ <span className="text-xs text-neutral-500">— {fact.predicate_label} →</span>
+ <span className="text-sm font-medium text-white">{fact.object_name ?? "?"}</span>
+ {range && <span className="u-num text-xs text-neutral-500">({range})</span>}
+ </div>
+ {fact.quote && (
+ <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">“{fact.quote}”</p>
+ )}
+ <div className="mt-3 flex items-center gap-2 justify-end">
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
+ disabled={busy}
+ onClick={onReject}
+ >
+ {S.review.reject}
+ </button>
+ <input
+ className="input-dark u-num w-28 px-2 py-1.5 text-xs text-center"
+ placeholder={S.review.closeAtPlaceholder}
+ value={closeAt}
+ onChange={(e) => setCloseAt(e.target.value)}
+ />
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ disabled={busy || !closeAtIso}
+ onClick={() => closeAtIso && onClose(closeAtIso)}
+ >
+ {closeAt.trim() ? S.review.closeFactAt(closeAt.trim()) : S.review.closeFact}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function MergeRow({
+ merge,
+ busy,
+ onRevert,
+}: {
+ merge: MergeLog;
+ busy: boolean;
+ onRevert: () => void;
+}) {
+ return (
+ <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-neutral-300 truncate">
+ <span className="text-neutral-500">{merge.source_name}</span>
+ <span className="text-neutral-600"> → </span>
+ <span className="text-white">{merge.target_name}</span>
+ </div>
+ <div className="text-xs text-neutral-500 truncate">
+ {merge.merged_by_name ? S.review.mergedBy(merge.merged_by_name) : S.review.mergedByAi}
+ {" · "}
+ {merge.created_at.slice(0, 10)}
+ {merge.reason ? ` · ${merge.reason}` : ""}
+ </div>
+ </div>
+ {merge.reverted_at ? (
+ <span className="u-chip u-chip-neutral shrink-0">{S.review.reverted}</span>
+ ) : (
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs shrink-0"
+ disabled={busy}
+ onClick={onRevert}
+ >
+ {S.review.revert}
+ </button>
+ )}
+ </div>
+ );
+}
+
+/* ---------- 决策台账行 ---------- */
+
+const DECISION_TONE: Record<string, ChipTone> = {
+ "review.merge": "violet",
+ "merge.manual": "violet",
+ "review.keep": "neutral",
+ "fact.confirm": "success",
+ "fact.reject": "danger",
+ "conflict.reject_new": "danger",
+ "fact.close": "info",
+ "conflict.close_old": "info",
+ "conflict.keep_both": "neutral",
+ "merge.revert": "warn",
+};
+
+function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
+ // detail 是决策时的自包含快照——不 join 活数据,事实删了台账也完整
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const d = e.detail as any;
+ let text: string;
+ if (e.action.startsWith("review.")) text = `${d.left} ≟ ${d.right}`;
+ else if (e.action.startsWith("fact."))
+ text = `${d.subject} — ${d.predicate} → ${d.object ?? "?"}`;
+ else if (e.action.startsWith("conflict."))
+ text = `${d.old_subject} — ${d.predicate} → ${d.old_object ?? "?"} · vs · ${
+ d.new_object ?? d.new_subject
+ }`;
+ else text = `${d.source} → ${d.target}`;
+
+ return (
+ <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
+ <Chip tone={DECISION_TONE[e.action] ?? "neutral"}>
+ {S.review.decisionActions[e.action] ?? e.action}
+ </Chip>
+ <span className="text-sm text-neutral-300 truncate min-w-0">{text}</span>
+ {typeof d.confidence === "number" && (
+ <span className="u-num text-xs text-neutral-600 shrink-0">
+ {Math.round(d.confidence * 100)}%
+ </span>
+ )}
+ {typeof d.valid_to === "string" && (
+ <span className="u-num text-xs text-neutral-600 shrink-0">
+ → {d.valid_to.slice(0, 10)}
+ </span>
+ )}
+ <span className="ml-auto shrink-0 text-xs text-neutral-500">
+ {e.actor_name ?? S.review.aiActor}
+ {" · "}
+ <span className="u-num">{e.created_at.slice(0, 10)}</span>
+ </span>
+ </div>
+ );
+}
+
+/* ---------- 页面:左栏分类 + 单类内容区 ---------- */
+
+type Sel = "duplicates" | "conflicts" | "unconfirmed" | "lowconf" | "decisions" | "merges";
+
+const QUEUE_ORDER: Sel[] = ["duplicates", "conflicts", "unconfirmed", "lowconf"];
+const PAGE_SIZE: Record<Sel, number> = {
+ duplicates: DUP_PAGE,
+ conflicts: CONFLICT_PAGE,
+ unconfirmed: FACT_PAGE,
+ lowconf: FACT_PAGE,
+ merges: MERGE_PAGE,
+ decisions: 20,
+};
+
+function RailHeader({ label }: { label: string }) {
+ return (
+ <div className="px-4 pt-4 pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-500">
+ {label}
+ </div>
+ );
+}
+
+function RailItem({
+ active,
+ label,
+ count,
+ onClick,
+}: {
+ active: boolean;
+ label: string;
+ count: number | null;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ onClick={onClick}
+ className={cn(
+ "w-full flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] transition-colors",
+ active ? "u-nav-active" : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
+ )}
+ >
+ <span className="truncate">{label}</span>
+ {count !== null && (
+ <span
+ className={cn(
+ "ml-auto shrink-0 u-num text-[10.5px]",
+ count > 0 ? "text-neutral-400" : "text-neutral-700",
+ )}
+ >
+ {count}
+ </span>
+ )}
+ </button>
+ );
+}
+
+export function Review() {
+ const { kb } = useKb();
+ const queryClient = useQueryClient();
+ const [sel, setSel] = useState<Sel | null>(null);
+ const [page, setPage] = useState(0);
+
+ // 队列变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询
+ const review = useQuery({
+ queryKey: ["review", kb?.id],
+ queryFn: () => api.review(kb!.id),
+ enabled: !!kb,
+ });
+ // 决策台账:服务端分页,仅选中时拉取
+ const history = useQuery({
+ queryKey: ["reviewHistory", kb?.id, page],
+ queryFn: () => api.reviewHistory(kb!.id, page),
+ enabled: !!kb && sel === "decisions",
+ });
+
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey: ["review", kb?.id] });
+ queryClient.invalidateQueries({ queryKey: ["reviewHistory", kb?.id] });
+ queryClient.invalidateQueries({ queryKey: ["graph"] });
+ };
+
+ const decide = useMutation({
+ mutationFn: ({ id, action }: { id: string; action: "merge" | "keep" }) =>
+ api.decideReview(kb!.id, id, action),
+ onSettled: invalidate,
+ });
+ const factAction = useMutation({
+ mutationFn: ({ id, action }: { id: string; action: "confirm" | "reject" }) =>
+ action === "confirm" ? api.confirmFact(kb!.id, id) : api.rejectFact(kb!.id, id),
+ onSettled: invalidate,
+ });
+ const revert = useMutation({
+ mutationFn: (mergeId: string) => api.revertMerge(kb!.id, mergeId),
+ onSettled: invalidate,
+ });
+ const conflictAction = useMutation({
+ mutationFn: ({
+ id,
+ action,
+ closeAt,
+ }: {
+ id: string;
+ action: "close" | "keep" | "reject_new";
+ closeAt?: string;
+ }) => api.resolveConflict(kb!.id, id, { action, close_at: closeAt }),
+ onSettled: invalidate,
+ });
+
+ const closeFactAction = useMutation({
+ mutationFn: ({ id, validTo }: { id: string; validTo: string }) =>
+ api.closeFact(kb!.id, id, validTo),
+ onSettled: invalidate,
+ });
+
+ const data = review.data;
+ const counts: Record<Sel, number> = {
+ duplicates: data?.reviews.length ?? 0,
+ conflicts: data?.conflicts?.length ?? 0,
+ unconfirmed: data?.unconfirmed?.length ?? 0,
+ lowconf: data?.facts.length ?? 0,
+ merges: data?.merges.length ?? 0,
+ decisions: history.data?.total ?? 0,
+ };
+ const queueEmpty = QUEUE_ORDER.every((k) => counts[k] === 0);
+
+ // 首批数据到达:定位到第一个非空队列(全空落在 duplicates 显示"干净"文案)
+ useEffect(() => {
+ if (sel === null && data) setSel(QUEUE_ORDER.find((k) => counts[k] > 0) ?? "duplicates");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [data]);
+
+ const select = (s: Sel) => {
+ setSel(s);
+ setPage(0);
+ };
+
+ const active = sel ?? "duplicates";
+ const isQueueSel = QUEUE_ORDER.includes(active);
+
+ const SECTION: Record<Sel, { title: string; hint: string | null }> = {
+ duplicates: { title: S.review.duplicates, hint: S.review.duplicatesHint },
+ conflicts: { title: S.review.conflicts, hint: S.review.conflictsHint },
+ unconfirmed: { title: S.review.unconfirmed, hint: S.review.unconfirmedHint },
+ lowconf: { title: S.review.lowConfidence, hint: S.review.lowConfidenceHint },
+ decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
+ merges: { title: S.review.mergeHistory, hint: null },
+ };
+
+ return (
+ <div className="h-full flex">
+ {/* 左栏:队列分类 + 历史,各带实时计数(SSE 推动刷新) */}
+ <aside className={`${RAIL_CLS} flex flex-col`}>
+ <RailHeader label={S.review.tabQueue} />
+ <div className="px-2 space-y-0.5">
+ <RailItem
+ active={active === "duplicates"}
+ label={S.review.railDuplicates}
+ count={counts.duplicates}
+ onClick={() => select("duplicates")}
+ />
+ <RailItem
+ active={active === "conflicts"}
+ label={S.review.railConflicts}
+ count={counts.conflicts}
+ onClick={() => select("conflicts")}
+ />
+ <RailItem
+ active={active === "unconfirmed"}
+ label={S.review.railUnconfirmed}
+ count={counts.unconfirmed}
+ onClick={() => select("unconfirmed")}
+ />
+ <RailItem
+ active={active === "lowconf"}
+ label={S.review.railLowConfidence}
+ count={counts.lowconf}
+ onClick={() => select("lowconf")}
+ />
+ </div>
+ <RailHeader label={S.review.tabHistory} />
+ <div className="px-2 space-y-0.5">
+ <RailItem
+ active={active === "decisions"}
+ label={S.review.railDecisions}
+ count={null}
+ onClick={() => select("decisions")}
+ />
+ <RailItem
+ active={active === "merges"}
+ label={S.review.railMerges}
+ count={counts.merges}
+ onClick={() => select("merges")}
+ />
+ </div>
+ </aside>
+
+ {/* 右侧:一次只显示选中的一类,单一分页 */}
+ <div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">
+ <div className="max-w-4xl">
+ {review.isPending && <p className="text-sm text-neutral-500">{S.nav.loading}</p>}
+ {review.isError && (
+ <p className="text-sm text-rose-400">{(review.error as Error).message}</p>
+ )}
+
+ {data && (
+ <section>
+ {/* 页级标题:与 Library/KB Settings 同级(text-lg),不是卡片头 */}
+ <h2 className="u-title text-lg mb-1">{SECTION[active].title}</h2>
+ {SECTION[active].hint && (
+ <p className="text-xs text-neutral-500 mb-3">{SECTION[active].hint}</p>
+ )}
+
+ {/* 空态:整个待办全清 vs 单类清空 */}
+ {isQueueSel && counts[active] === 0 && (
+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
+ {queueEmpty ? S.review.empty : S.review.categoryEmpty}
+ </div>
+ )}
+
+ {active === "duplicates" && counts.duplicates > 0 && (
+ <div className="space-y-3">
+ {pageSlice(data.reviews, page, DUP_PAGE).rows.map((item) => (
+ <DuplicateCard
+ key={item.id}
+ item={item}
+ busy={decide.isPending && decide.variables?.id === item.id}
+ onDecide={(action) => decide.mutate({ id: item.id, action })}
+ />
+ ))}
+ </div>
+ )}
+
+ {active === "conflicts" && counts.conflicts > 0 && (
+ <div className="space-y-3">
+ {pageSlice(data.conflicts, page, CONFLICT_PAGE).rows.map((c) => (
+ <ConflictRow
+ key={c.id}
+ conflict={c}
+ busy={conflictAction.isPending && conflictAction.variables?.id === c.id}
+ onResolve={(action, closeAt) =>
+ conflictAction.mutate({ id: c.id, action, closeAt })
+ }
+ />
+ ))}
+ </div>
+ )}
+
+ {active === "unconfirmed" && counts.unconfirmed > 0 && (
+ <div className="space-y-3">
+ {pageSlice(data.unconfirmed, page, FACT_PAGE).rows.map((fact) => (
+ <UnconfirmedRow
+ key={fact.id}
+ fact={fact}
+ busy={
+ (factAction.isPending && factAction.variables?.id === fact.id) ||
+ (closeFactAction.isPending && closeFactAction.variables?.id === fact.id)
+ }
+ onReject={() => factAction.mutate({ id: fact.id, action: "reject" })}
+ onClose={(validTo) => closeFactAction.mutate({ id: fact.id, validTo })}
+ />
+ ))}
+ </div>
+ )}
+
+ {active === "lowconf" && counts.lowconf > 0 && (
+ <div className="space-y-3">
+ {pageSlice(data.facts, page, FACT_PAGE).rows.map((fact) => (
+ <FactRow
+ key={fact.id}
+ fact={fact}
+ busy={factAction.isPending && factAction.variables?.id === fact.id}
+ onConfirm={() => factAction.mutate({ id: fact.id, action: "confirm" })}
+ onReject={() => factAction.mutate({ id: fact.id, action: "reject" })}
+ />
+ ))}
+ </div>
+ )}
+
+ {active === "merges" &&
+ (counts.merges === 0 ? (
+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
+ {S.review.historyEmpty}
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {pageSlice(data.merges, page, MERGE_PAGE).rows.map((m) => (
+ <MergeRow
+ key={m.id}
+ merge={m}
+ busy={revert.isPending && revert.variables === m.id}
+ onRevert={() => revert.mutate(m.id)}
+ />
+ ))}
+ </div>
+ ))}
+
+ {active === "decisions" &&
+ (history.isPending ? (
+ <p className="text-sm text-neutral-500">{S.nav.loading}</p>
+ ) : (history.data?.total ?? 0) === 0 ? (
+ <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
+ {S.review.decisionsEmpty}
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {(history.data?.events ?? []).map((e) => (
+ <DecisionRow key={e.id} e={e} />
+ ))}
+ </div>
+ ))}
+
+ {/* 单一分页:queue/merges 走客户端切片,decisions 服务端分页 */}
+ {active !== "decisions" && (
+ <Pager
+ total={counts[active]}
+ pageSize={PAGE_SIZE[active]}
+ page={page}
+ onPage={setPage}
+ />
+ )}
+ {active === "decisions" && (
+ <Pager
+ total={history.data?.total ?? 0}
+ pageSize={PAGE_SIZE.decisions}
+ page={page}
+ onPage={setPage}
+ />
+ )}
+ </section>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/Search.tsx b/web/src/pages/Search.tsx
new file mode 100644
index 00000000..af61b5f2
--- /dev/null
+++ b/web/src/pages/Search.tsx
@@ -0,0 +1,86 @@
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Link } from "@tanstack/react-router";
+import { api } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { Pager, pageSlice } from "../ui";
+
+const RESULT_PAGE = 10;
+
+export function Search() {
+ const { kb } = useKb();
+ const [input, setInput] = useState("");
+ const [query, setQuery] = useState("");
+ const [page, setPage] = useState(0);
+
+ const results = useQuery({
+ queryKey: ["search", kb?.id, query],
+ queryFn: () => api.search(kb!.id, query),
+ enabled: !!kb && query.length > 0,
+ });
+
+ return (
+ <div className="h-full overflow-y-auto p-6">
+ <div className="max-w-2xl mx-auto">
+ <div className="flex gap-2 mb-6">
+ <input
+ className="input-dark flex-1 px-4 py-2.5 text-sm"
+ placeholder={S.search.placeholder}
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ setQuery(input.trim());
+ setPage(0);
+ }
+ }}
+ />
+ <button
+ onClick={() => {
+ setQuery(input.trim());
+ setPage(0);
+ }}
+ disabled={!input.trim()}
+ className="u-btn u-btn-primary px-5 py-2 text-sm"
+ >
+ {S.search.button}
+ </button>
+ </div>
+
+ {results.isFetching && <p className="text-sm text-neutral-500">{S.search.searching}</p>}
+ {results.isError && (
+ <p className="text-sm text-rose-400">{(results.error as Error).message}</p>
+ )}
+ {results.data && results.data.results.length === 0 && (
+ <p className="text-sm text-neutral-500">{S.search.noResults}</p>
+ )}
+
+ <div className="space-y-3">
+ {pageSlice(results.data?.results ?? [], page, RESULT_PAGE).rows.map((r) => (
+ <Link
+ key={r.id}
+ to="/doc/$docId"
+ params={{ docId: r.document_id }}
+ search={{ chunk: r.id }}
+ className="block glass rounded-xl p-4 glass-hover"
+ >
+ <div className="mb-1.5 text-xs text-neutral-500">
+ {S.search.chunkOf(r.filename, r.seq + 1)}
+ </div>
+ <p className="text-sm text-neutral-300 leading-relaxed line-clamp-4 whitespace-pre-wrap">
+ {r.text}
+ </p>
+ </Link>
+ ))}
+ </div>
+ <Pager
+ total={results.data?.results.length ?? 0}
+ pageSize={RESULT_PAGE}
+ page={page}
+ onPage={setPage}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/ServerDown.tsx b/web/src/pages/ServerDown.tsx
new file mode 100644
index 00000000..d3c87cca
--- /dev/null
+++ b/web/src/pages/ServerDown.tsx
@@ -0,0 +1,66 @@
+/* 惩戒页(Punishment pages):500 服务器失联 / 404 迷失之城。
+ 复用登录页场景做背景——报错也保持门面体面(自托管场景里这页常是运维第一现场)。 */
+import { Home, RefreshCw } from "lucide-react";
+import { Link } from "@tanstack/react-router";
+import { S } from "../i18n";
+import { Wordmark } from "../ui";
+import { usePageTitle } from "../useTitle";
+import { LoginScene } from "./LoginScene";
+
+function PunishmentPage({
+ message,
+ children,
+}: {
+ message: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="min-h-screen flex items-center justify-center px-4">
+ <LoginScene />
+ <div className="relative z-10 text-center u-rise">
+ <h1 className="text-5xl font-normal">
+ <Wordmark />
+ </h1>
+ <p className="u-balance mt-4 text-sm text-neutral-400">{message}</p>
+ <div className="mt-5 flex items-center justify-center gap-4">
+ {children}
+ <a
+ href={`${S.login.githubUrl}/issues`}
+ target="_blank"
+ rel="noreferrer"
+ className="u-link text-xs"
+ >
+ {S.nav.reportIssue}
+ </a>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function ServerDown() {
+ usePageTitle(S.app.name, "Punishment 500");
+ return (
+ <PunishmentPage message={S.nav.serverUnreachable}>
+ <button
+ onClick={() => window.location.reload()}
+ className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs flex items-center gap-1.5"
+ >
+ <RefreshCw size={12} />
+ {S.nav.refresh}
+ </button>
+ </PunishmentPage>
+ );
+}
+
+export function NotFound() {
+ usePageTitle(S.app.name, "Punishment 404");
+ return (
+ <PunishmentPage message={S.nav.notFound}>
+ <Link to="/" className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs flex items-center gap-1.5">
+ <Home size={12} />
+ {S.nav.returnHome}
+ </Link>
+ </PunishmentPage>
+ );
+}
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
new file mode 100644
index 00000000..2991faf2
--- /dev/null
+++ b/web/src/pages/Settings.tsx
@@ -0,0 +1,595 @@
+import { useEffect, useState } from "react";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useNavigate, useSearch } from "@tanstack/react-router";
+import { Lock, Plus, X } from "lucide-react";
+import { api } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { Members } from "./Members";
+
+/** 部署级配置:注册开关 + worker 并发。 */
+function DeploymentAdmin() {
+ const queryClient = useQueryClient();
+ const dep = useQuery({ queryKey: ["deployment"], queryFn: api.adminDeployment });
+ const [workers, setWorkers] = useState<number | null>(null);
+ const shown = workers ?? dep.data?.worker_concurrency ?? 4;
+ const save = useMutation({
+ mutationFn: (v: { open: boolean; workers?: number }) =>
+ api.saveAdminDeployment(v.open, v.workers),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["deployment"] }),
+ });
+ const open = dep.data?.open_registration ?? true;
+
+ return (
+ <div className="glass rounded-xl p-4 space-y-4">
+ <label className="flex items-start gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ className="mt-0.5"
+ checked={open}
+ disabled={dep.isPending || save.isPending}
+ onChange={(e) => save.mutate({ open: e.target.checked })}
+ />
+ <span>
+ <span className="block text-sm text-neutral-200">{S.settings.deployment.openReg}</span>
+ <span className="block text-xs text-neutral-500 mt-0.5">
+ {S.settings.deployment.openRegHint}
+ </span>
+ </span>
+ </label>
+
+ <div className="flex items-start justify-between gap-4 border-t border-white/10 pt-4">
+ <div className="min-w-0">
+ <span className="block text-sm text-neutral-200">{S.settings.deployment.workers}</span>
+ <span className="block text-xs text-neutral-500 mt-0.5">
+ {S.settings.deployment.workersHint}
+ </span>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ <input
+ type="number"
+ min={1}
+ max={32}
+ className="input-dark u-input-plain w-16 px-2 py-1.5 text-sm u-num text-center"
+ value={shown}
+ disabled={dep.isPending}
+ onChange={(e) => setWorkers(Math.max(1, Math.min(32, Number(e.target.value) || 1)))}
+ />
+ <button
+ className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
+ disabled={save.isPending || workers === null || workers === dep.data?.worker_concurrency}
+ onClick={() => save.mutate({ open, workers: shown })}
+ >
+ {S.settings.deployment.workersApply}
+ </button>
+ </div>
+ </div>
+ {save.isError && (
+ <p className="text-xs text-rose-400">{(save.error as Error).message}</p>
+ )}
+ </div>
+ );
+}
+
+/** 知识库管理(部署层):全部库总览 + 新建(建库是管理动作,切换器只切换)。 */
+function KbsAdmin() {
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+ const { workspace, setKb } = useKb();
+ const [creating, setCreating] = useState(false);
+ const list = useQuery({
+ queryKey: ["myKbs", workspace?.id],
+ queryFn: () => api.myKbs(workspace!.id),
+ enabled: !!workspace,
+ });
+ const rows = list.data?.kbs ?? [];
+
+ return (
+ <div className="space-y-4">
+ <p className="text-xs text-neutral-500">{S.settings.kbs.hint}</p>
+
+ <div className="glass rounded-xl divide-y divide-white/5">
+ {rows.map(({ kb, doc_count, member_count }) => (
+ <div key={kb.id} className="px-4 py-3 flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-neutral-200 truncate">{kb.name}</span>
+ {kb.is_default && (
+ <span className="u-chip u-chip-neutral !text-[10px]">
+ {S.settings.kbs.defaultChip}
+ </span>
+ )}
+ {kb.visibility === "restricted" && (
+ <span className="flex items-center gap-1 text-[10.5px] text-neutral-500">
+ <Lock size={10} />
+ {S.settings.kbs.visRestricted}
+ </span>
+ )}
+ </div>
+ <div className="mt-0.5 text-xs text-neutral-500">
+ <span className="u-num">{S.account.kbStats(doc_count, member_count)}</span>
+ </div>
+ </div>
+ <button
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
+ onClick={() => {
+ setKb(kb.id);
+ navigate({ to: "/kb-settings", search: { kb: kb.id } });
+ }}
+ >
+ {S.settings.kbs.openSettings}
+ </button>
+ </div>
+ ))}
+ {!list.isPending && rows.length === 0 && (
+ <p className="px-4 py-6 text-sm text-neutral-500">—</p>
+ )}
+ </div>
+
+ <button
+ onClick={() => setCreating(true)}
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs flex items-center gap-1.5"
+ >
+ <Plus size={12} />
+ {S.settings.kbs.newKb}
+ </button>
+
+ {creating && workspace && (
+ <NewKbModal
+ workspaceId={workspace.id}
+ onDone={(id) => {
+ setCreating(false);
+ queryClient.invalidateQueries({ queryKey: ["myKbs", workspace.id] });
+ queryClient.invalidateQueries({ queryKey: ["kbs", workspace.id] });
+ // 建完直达库设置:下一步几乎总是邀人/配置
+ if (id) {
+ setKb(id);
+ navigate({ to: "/kb-settings", search: { kb: id } });
+ }
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+/** 新建知识库弹窗(管理员):缺省 restricted,不污染全员切换器。 */
+function NewKbModal({
+ workspaceId,
+ onDone,
+}: {
+ workspaceId: string;
+ onDone: (id?: string) => void;
+}) {
+ const [name, setName] = useState("");
+ const [desc, setDesc] = useState("");
+ const [restricted, setRestricted] = useState(true);
+
+ const create = useMutation({
+ mutationFn: () =>
+ api.createKb(workspaceId, {
+ name: name.trim(),
+ description: desc.trim() || null,
+ visibility: restricted ? "restricted" : "open",
+ }),
+ onSuccess: (kb) => onDone(kb.id),
+ });
+
+ return (
+ <div
+ className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
+ onMouseDown={(e) => {
+ if (e.target === e.currentTarget) onDone();
+ }}
+ >
+ <div className="glass-strong w-[24rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl p-5">
+ <div className="flex items-center justify-between mb-4">
+ <h2 className="u-title text-[15px]">{S.settings.kbs.newKb}</h2>
+ <button onClick={() => onDone()} className="text-neutral-500 hover:text-neutral-200">
+ <X size={15} />
+ </button>
+ </div>
+ <input
+ autoFocus
+ className="input-dark w-full px-3 py-2 text-sm mb-2"
+ placeholder={S.settings.kbs.name}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <input
+ className="input-dark w-full px-3 py-2 text-sm mb-3"
+ placeholder={S.settings.kbs.description}
+ value={desc}
+ onChange={(e) => setDesc(e.target.value)}
+ />
+ <label className="flex items-center gap-2 text-xs text-neutral-400 mb-4">
+ <input
+ type="checkbox"
+ checked={restricted}
+ onChange={(e) => setRestricted(e.target.checked)}
+ />
+ {S.settings.kbs.visRestricted}
+ </label>
+ {create.isError && (
+ <p className="text-xs text-rose-400 mb-2">{(create.error as Error).message}</p>
+ )}
+ <div className="flex justify-end gap-2">
+ <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={() => onDone()}>
+ {S.library.cancel}
+ </button>
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!name.trim() || create.isPending}
+ onClick={() => create.mutate()}
+ >
+ {S.settings.kbs.create}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/** 系统层数据源注册(问数):凭据只进不出,列表只显示 host:port/db 摘要。 */
+function DataSourcesAdmin() {
+ const queryClient = useQueryClient();
+ const list = useQuery({ queryKey: ["dataSources"], queryFn: api.adminDataSources });
+ const [name, setName] = useState("");
+ const [conn, setConn] = useState("");
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: ["dataSources"] });
+
+ const create = useMutation({
+ mutationFn: () => api.adminCreateDataSource({ name: name.trim(), conn_string: conn.trim() }),
+ onSuccess: () => {
+ setName("");
+ setConn("");
+ invalidate();
+ },
+ });
+ const remove = useMutation({
+ mutationFn: (id: string) => api.adminDeleteDataSource(id),
+ onSettled: invalidate,
+ });
+ const test = useMutation({
+ mutationFn: (id: string) => api.adminTestDataSource(id),
+ onSettled: invalidate,
+ });
+
+ return (
+ <div className="space-y-4">
+ <p className="text-xs text-neutral-500">{S.settings.datasources.hint}</p>
+
+ <div className="glass rounded-xl divide-y divide-white/5">
+ {(list.data?.data_sources ?? []).map((d) => (
+ <div key={d.id} className="px-4 py-3 flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-neutral-200">{d.name}</div>
+ <div className="text-xs text-neutral-500 font-mono truncate">{d.summary}</div>
+ </div>
+ <span
+ className={`u-chip shrink-0 ${
+ d.last_test_ok === true
+ ? "u-chip-success"
+ : d.last_test_ok === false
+ ? "u-chip-danger"
+ : "u-chip-neutral"
+ }`}
+ >
+ {d.last_test_ok === true
+ ? S.settings.datasources.testOk
+ : d.last_test_ok === false
+ ? S.settings.datasources.testFail
+ : S.settings.datasources.neverTested}
+ </span>
+ <button
+ className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
+ disabled={test.isPending}
+ onClick={() => test.mutate(d.id)}
+ >
+ {S.settings.datasources.test}
+ </button>
+ <button
+ className="text-xs text-neutral-500 hover:text-[var(--u-danger)] shrink-0"
+ disabled={remove.isPending}
+ onClick={() => remove.mutate(d.id)}
+ >
+ {S.settings.datasources.remove}
+ </button>
+ </div>
+ ))}
+ {list.data?.data_sources.length === 0 && (
+ <p className="px-4 py-6 text-sm text-neutral-500">—</p>
+ )}
+ </div>
+
+ <div className="glass rounded-xl p-4 space-y-2">
+ <input
+ className="input-dark w-full px-3 py-2 text-sm"
+ placeholder={S.settings.datasources.name}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <input
+ className="input-dark w-full px-3 py-2 text-sm font-mono u-placeholder-sans"
+ placeholder={S.settings.datasources.connString}
+ value={conn}
+ onChange={(e) => setConn(e.target.value)}
+ />
+ <div className="flex items-center gap-3">
+ <button
+ className="u-btn u-btn-primary px-3.5 py-1.5 text-xs"
+ disabled={!name.trim() || !conn.trim() || create.isPending}
+ onClick={() => create.mutate()}
+ >
+ {S.settings.datasources.add}
+ </button>
+ {create.isError && (
+ <span className="text-xs text-rose-400">{(create.error as Error).message}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const PRESETS: Record<
+ string,
+ { chat: string; embed: string; chatModel: string; embedModel: string }
+> = {
+ DeepSeek: {
+ chat: "https://api.deepseek.com/v1",
+ chatModel: "deepseek-chat",
+ embed: "",
+ embedModel: "",
+ },
+ SiliconFlow: {
+ chat: "https://api.siliconflow.cn/v1",
+ chatModel: "deepseek-ai/DeepSeek-V3",
+ embed: "https://api.siliconflow.cn/v1",
+ embedModel: "BAAI/bge-m3",
+ },
+ "Qwen (DashScope)": {
+ chat: "https://dashscope.aliyuncs.com/compatible-mode/v1",
+ chatModel: "qwen-plus",
+ embed: "https://dashscope.aliyuncs.com/compatible-mode/v1",
+ embedModel: "text-embedding-v3",
+ },
+ Ollama: {
+ chat: "http://localhost:11434/v1",
+ chatModel: "qwen2.5:7b",
+ embed: "http://localhost:11434/v1",
+ embedModel: "bge-m3",
+ },
+ OpenAI: {
+ chat: "https://api.openai.com/v1",
+ chatModel: "gpt-4o-mini",
+ embed: "https://api.openai.com/v1",
+ embedModel: "text-embedding-3-small",
+ },
+};
+
+export function Settings() {
+ const { workspace } = useKb();
+ const { tab: tabParam } = useSearch({ from: "/account/admin" });
+ const [tab, setTab] = useState<"models" | "members" | "kbs" | "datasources" | "deployment">(
+ tabParam ?? "models",
+ );
+ const queryClient = useQueryClient();
+ const settings = useQuery({
+ queryKey: ["settings", workspace?.id],
+ queryFn: () => api.settings(workspace!.id),
+ enabled: !!workspace,
+ });
+
+ const [form, setForm] = useState({
+ chat_base_url: "",
+ chat_api_key: "",
+ chat_model: "",
+ embed_base_url: "",
+ embed_api_key: "",
+ embed_model: "",
+ });
+
+ useEffect(() => {
+ if (settings.data) {
+ setForm((f) => ({
+ ...f,
+ chat_base_url: settings.data.chat_base_url ?? "",
+ chat_model: settings.data.chat_model ?? "",
+ embed_base_url: settings.data.embed_base_url ?? "",
+ embed_model: settings.data.embed_model ?? "",
+ }));
+ }
+ }, [settings.data]);
+
+ const save = useMutation({
+ mutationFn: () => api.saveSettings(workspace!.id, form),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["settings", workspace?.id] }),
+ });
+
+ const test = useMutation({ mutationFn: () => api.testSettings(workspace!.id) });
+
+ if (!workspace) return <div className="p-8 text-sm text-neutral-500">{S.nav.loading}</div>;
+
+ const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
+ setForm({ ...form, [k]: e.target.value });
+
+ const input =
+ "input-dark w-full px-3 py-2 text-sm";
+ const label = "block text-xs font-medium text-neutral-400 mb-1";
+
+ return (
+ <div className="h-full overflow-y-auto p-6">
+ <div className="max-w-xl">
+ <h2 className="text-lg font-bold text-neutral-100 mb-3">{S.settings.title}</h2>
+ <div className="flex gap-1 mb-5 bg-white/5 rounded-lg p-1 w-fit">
+ {(
+ [
+ ["models", S.settings.tabModels],
+ ["members", S.settings.tabMembers],
+ ["kbs", S.settings.tabKbs],
+ ["datasources", S.settings.datasources.tab],
+ ["deployment", S.settings.tabDeployment],
+ ] as const
+ ).map(([key, tabLabel]) => (
+ <button
+ key={key}
+ onClick={() => setTab(key)}
+ className={`rounded-md px-4 py-1.5 text-sm font-medium transition-colors ${
+ tab === key
+ ? "bg-white/10 text-neutral-100"
+ : "text-neutral-500 hover:text-neutral-300"
+ }`}
+ >
+ {tabLabel}
+ </button>
+ ))}
+ </div>
+
+ {tab === "members" && <Members workspaceId={workspace.id} />}
+ {tab === "kbs" && <KbsAdmin />}
+ {tab === "datasources" && <DataSourcesAdmin />}
+ {tab === "deployment" && <DeploymentAdmin />}
+
+ {tab === "models" && (
+ <>
+ <p className="text-sm text-neutral-400 mb-4">{S.settings.modelsIntro}</p>
+
+ <div className="mb-5 flex flex-wrap gap-2">
+ {Object.entries(PRESETS).map(([name, p]) => (
+ <button
+ key={name}
+ onClick={() =>
+ setForm({
+ ...form,
+ chat_base_url: p.chat,
+ chat_model: p.chatModel,
+ embed_base_url: p.embed,
+ embed_model: p.embedModel,
+ })
+ }
+ className="rounded-full border border-white/15 bg-white/5 px-3 py-1 text-xs text-neutral-300 hover:border-[rgba(var(--u-accent-deep),0.5)] hover:text-[var(--u-accent)]"
+ >
+ {name}
+ </button>
+ ))}
+ </div>
+
+ <div className="glass rounded-xl p-5 space-y-4">
+ <h3 className="text-sm font-bold text-neutral-200">{S.settings.chatModel}</h3>
+ <div>
+ <label className={label}>{S.settings.baseUrl}</label>
+ <input
+ className={input}
+ placeholder="https://api.deepseek.com/v1"
+ value={form.chat_base_url}
+ onChange={set("chat_base_url")}
+ />
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <label className={label}>{S.settings.model}</label>
+ <input
+ className={input}
+ placeholder="deepseek-chat"
+ value={form.chat_model}
+ onChange={set("chat_model")}
+ />
+ </div>
+ <div>
+ <label className={label}>
+ {S.settings.apiKey}{" "}
+ {settings.data?.has_chat_key && (
+ <span className="text-[var(--u-accent)]">{S.settings.keyConfigured}</span>
+ )}
+ </label>
+ <input
+ className={input}
+ type="password"
+ placeholder="sk-…"
+ value={form.chat_api_key}
+ onChange={set("chat_api_key")}
+ />
+ </div>
+ </div>
+
+ <h3 className="text-sm font-bold text-neutral-200 pt-2">{S.settings.embedModel}</h3>
+ <div>
+ <label className={label}>{S.settings.baseUrl}</label>
+ <input
+ className={input}
+ placeholder="http://localhost:11434/v1"
+ value={form.embed_base_url}
+ onChange={set("embed_base_url")}
+ />
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <label className={label}>{S.settings.model}</label>
+ <input
+ className={input}
+ placeholder="bge-m3"
+ value={form.embed_model}
+ onChange={set("embed_model")}
+ />
+ </div>
+ <div>
+ <label className={label}>
+ {S.settings.apiKey}{" "}
+ {settings.data?.has_embed_key && (
+ <span className="text-[var(--u-accent)]">{S.settings.keyConfigured}</span>
+ )}
+ </label>
+ <input
+ className={input}
+ type="password"
+ value={form.embed_api_key}
+ onChange={set("embed_api_key")}
+ />
+ </div>
+ </div>
+
+ <div className="flex gap-2 pt-2">
+ <button
+ onClick={() => save.mutate()}
+ disabled={save.isPending}
+ className="u-btn u-btn-primary px-4 py-2 text-sm"
+ >
+ {save.isPending ? S.settings.saving : S.settings.save}
+ </button>
+ <button
+ onClick={() => test.mutate()}
+ disabled={test.isPending}
+ className="u-btn u-btn-ghost px-4 py-2 text-sm"
+ >
+ {test.isPending ? S.settings.testing : S.settings.test}
+ </button>
+ </div>
+
+ {save.isSuccess && <p className="text-sm text-[var(--u-accent)]">{S.settings.saved}</p>}
+ {save.isError && (
+ <p className="text-sm text-rose-400">{(save.error as Error).message}</p>
+ )}
+ {test.data && (
+ <div className="text-sm space-y-1 pt-1">
+ <p className={test.data.chat.ok ? "text-[var(--u-accent)]" : "text-rose-400"}>
+ {S.settings.chatLabel}:{" "}
+ {test.data.chat.ok
+ ? S.settings.ok(test.data.chat.reply ?? "OK")
+ : test.data.chat.error}
+ </p>
+ <p className={test.data.embed.ok ? "text-[var(--u-accent)]" : "text-neutral-400"}>
+ {S.settings.embedLabel}:{" "}
+ {test.data.embed.ok
+ ? S.settings.okDim(test.data.embed.dim ?? 0)
+ : test.data.embed.error}
+ </p>
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/pages/Shell.tsx b/web/src/pages/Shell.tsx
new file mode 100644
index 00000000..7e3513c0
--- /dev/null
+++ b/web/src/pages/Shell.tsx
@@ -0,0 +1,138 @@
+import { useQuery } from "@tanstack/react-query";
+import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
+import {
+ BookMarked,
+ Library as LibraryIcon,
+ ListChecks,
+ MessagesSquare,
+ Search as SearchIcon,
+ Settings as SettingsIcon,
+ Shapes,
+ Waypoints,
+} from "lucide-react";
+import { api, ApiError } from "../api";
+import { S } from "../i18n";
+import { useKb } from "../kb";
+import { Dropdown, GithubMark, Wordmark } from "../ui";
+import { UserMenu } from "./UserMenu";
+import { ServerDown } from "./ServerDown";
+import { useKbEvents } from "../useKbEvents";
+import { usePageTitle } from "../useTitle";
+
+const TABS = [
+ // 图谱是门面,排第一;两种查询方式(Search/Ask)随后
+ { to: "/graph", label: S.nav.graph, Icon: Waypoints },
+ { to: "/search", label: S.nav.search, Icon: SearchIcon },
+ { to: "/chat", label: S.nav.ask, Icon: MessagesSquare },
+ { to: "/library", label: S.nav.library, Icon: LibraryIcon },
+ { to: "/review", label: S.review.title, Icon: ListChecks },
+ { to: "/ontology", label: S.ontology.title, Icon: Shapes },
+ // 库设置与其它 tab 同为"当前知识库作用域",并列于内容导航
+ { to: "/kb-settings", label: S.nav.settings, Icon: SettingsIcon },
+] as const;
+
+export function Shell() {
+ const navigate = useNavigate();
+
+ const me = useQuery({ queryKey: ["me"], queryFn: api.me });
+ const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });
+ const { kb, kbs, setKb } = useKb();
+ // 标题跟随当前 tab:`Graph · Utopia`;文档查看页归入 Library
+ const pathname = useRouterState({ select: (s) => s.location.pathname });
+ const tabLabel =
+ TABS.find((t) => pathname.startsWith(t.to))?.label ??
+ (pathname.startsWith("/doc/") ? S.nav.library : undefined);
+ usePageTitle(S.app.name, tabLabel);
+ // 全局唯一的 KB 事件流连接:文档/审核状态实时刷新(替轮询)
+ useKbEvents(kb?.id);
+
+ if (me.isPending) {
+ return (
+ <div className="min-h-screen flex items-center justify-center text-neutral-500 text-sm">
+ {S.nav.loading}
+ </div>
+ );
+ }
+
+ if (me.isError) {
+ if (me.error instanceof ApiError && me.error.status === 401) {
+ navigate({ to: "/login" });
+ return null;
+ }
+ return <ServerDown />;
+ }
+
+ return (
+ <div className="h-screen flex flex-col overflow-hidden u-arrive">
+ {/* 顶栏:品牌 + 工作区 + 用户(Vercel 式) */}
+ {/* z-40:backdrop-filter 使顶栏与 tab 条各自成 stacking context,
+ 不提权则后者按 DOM 序盖住顶栏内的弹出面板 */}
+ <header className="glass-strong relative z-40 border-x-0 border-t-0 h-14 shrink-0 flex items-center gap-4 px-5">
+ {/* 字标:逐字母淡入,hover 浮出 ↗,点击去官网 */}
+ <Wordmark className="text-[17px]" />
+ {/* 面包屑唯一一级:知识库。Workspace 已从概念层折叠为部署级隐形管道
+ (settings/members 仍经它走 API,如 organizations 之于单租户)。 */}
+ <span className="text-neutral-700">/</span>
+ {/* 纯切换器:建库是管理动作,入口在 System settings › Knowledge bases */}
+ <Dropdown
+ className="w-40"
+ size="sm"
+ icon={<BookMarked size={12} />}
+ menuLabel={S.nav.kbLabel}
+ value={kb?.id ?? ""}
+ onChange={setKb}
+ options={kbs.map((k) => ({ value: k.id, label: k.name }))}
+ />
+ <div className="ml-auto flex items-center gap-1.5">
+ {/* 项目入口:Docs + [GitHub·版本] 胶囊(版本取自后端 health,与部署一致)。
+ 版本并入 GitHub 胶囊:两个等高元素,视觉平衡 */}
+ <Link
+ to="/docs"
+ className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
+ >
+ {S.nav.docs}
+ </Link>
+ <a
+ href={S.login.githubUrl}
+ target="_blank"
+ rel="noreferrer"
+ title="GitHub"
+ className="flex items-center gap-1.5 rounded-full border border-white/10 px-2.5 py-1 text-neutral-500 hover:text-neutral-200 hover:border-white/25 transition-colors"
+ >
+ <GithubMark size={13} />
+ {health.data && (
+ <span className="u-num text-[11px]">v{health.data.version}</span>
+ )}
+ </a>
+ {/* 用户菜单:个人信息 / 系统管理(仅管理员)/ 登出 */}
+ <div className="ml-1.5">
+ <UserMenu user={me.data} />
+ </div>
+ </div>
+ </header>
+
+ {/* Tab 导航条:图标 + 文字,激活态下划线(Vercel 式) */}
+ <nav className="glass-strong border-x-0 border-t-0 shrink-0 flex items-stretch gap-1 px-4">
+ {TABS.map(({ to, label, Icon }) => (
+ <Link
+ key={to}
+ to={to}
+ className="flex items-center gap-2 px-3.5 py-2.5 text-[13.5px] font-medium text-neutral-400 border-b-2 border-transparent hover:text-neutral-200"
+ activeProps={{
+ className:
+ "flex items-center gap-2 px-3.5 py-2.5 text-[13.5px] font-medium text-white border-b-2 border-white",
+ }}
+ >
+ <Icon size={15} strokeWidth={1.8} />
+ {label}
+ </Link>
+ ))}
+ </nav>
+
+ <main className="flex-1 min-h-0">
+ <Outlet />
+ </main>
+ </div>
+ );
+}
+
diff --git a/web/src/pages/SourcesRail.tsx b/web/src/pages/SourcesRail.tsx
new file mode 100644
index 00000000..9d30c48b
--- /dev/null
+++ b/web/src/pages/SourcesRail.tsx
@@ -0,0 +1,198 @@
+/* 来源栏("来源即文件夹"):Library 与 DocViewer 共用的左侧导航。 */
+import { useQuery } from "@tanstack/react-query";
+import {
+ Archive,
+ BookOpen,
+ Brain,
+ Briefcase,
+ Building2,
+ Cloud,
+ Database,
+ FileText,
+ FlaskConical,
+ FolderOpen,
+ Globe,
+ HardDrive,
+ Inbox,
+ Library as LibraryIcon,
+ Newspaper,
+ Notebook,
+ Plus,
+ Puzzle,
+ Rocket,
+ Rss,
+ Server,
+ Upload,
+ Users,
+ Webhook,
+ type LucideIcon,
+} from "lucide-react";
+import { api, type SourceView } from "../api";
+import { S } from "../i18n";
+import { RAIL_CLS } from "../ui";
+
+/** 左栏选择:全部 / 手动上传 / 某个来源 id */
+export type LibrarySelection = "all" | "uploads" | string;
+
+/** 可选的来源图标(lucide 图标名 → 组件)。 */
+export const SOURCE_ICONS: Record<string, LucideIcon> = {
+ "folder-open": FolderOpen,
+ globe: Globe,
+ rss: Rss,
+ webhook: Webhook,
+ "book-open": BookOpen,
+ newspaper: Newspaper,
+ "file-text": FileText,
+ database: Database,
+ cloud: Cloud,
+ "hard-drive": HardDrive,
+ inbox: Inbox,
+ archive: Archive,
+ briefcase: Briefcase,
+ "building-2": Building2,
+ "flask-conical": FlaskConical,
+ notebook: Notebook,
+ rocket: Rocket,
+ server: Server,
+ users: Users,
+};
+
+export const KIND_ICON = {
+ folder: FolderOpen,
+ url: Globe,
+ rss: Rss,
+ api: Webhook,
+ custom: Puzzle,
+ memory: Brain,
+ upload: Upload,
+} as const;
+
+/** 有拉取/同步语义的来源类型(folder/api 无同步概念) */
+export const SYNCING_KINDS = new Set(["url", "rss", "custom"]);
+
+export const SYNC_DOT: Record<SourceView["last_sync_status"], string> = {
+ never: "bg-neutral-600",
+ queued: "bg-[var(--u-warn)]",
+ running: "bg-[var(--u-warn)] animate-pulse",
+ ok: "bg-[var(--u-ok)]",
+ failed: "bg-[var(--u-danger)]",
+};
+
+export function sourceIcon(s: SourceView): LucideIcon {
+ // 内置类型图标固定,只有 custom 尊重用户自选图标
+ if (s.kind === "custom" && s.icon && SOURCE_ICONS[s.icon]) return SOURCE_ICONS[s.icon];
+ return KIND_ICON[s.kind] || Globe;
+}
+
+function RailItem({
+ active,
+ onClick,
+ icon,
+ label,
+ count,
+ dot,
+}: {
+ active: boolean;
+ onClick: () => void;
+ icon: React.ReactNode;
+ label: string;
+ count: number;
+ dot?: string;
+}) {
+ return (
+ <button
+ onClick={onClick}
+ className={`w-full flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] transition-colors ${
+ active ? "u-nav-active" : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200"
+ }`}
+ >
+ <span className="shrink-0 text-neutral-500">{icon}</span>
+ <span className="truncate">{label}</span>
+ {dot && <span className={`h-1.5 w-1.5 rounded-full shrink-0 ${dot}`} />}
+ <span className="ml-auto shrink-0 u-num text-[10.5px] text-neutral-600">{count}</span>
+ </button>
+ );
+}
+
+export function SourcesRail({
+ kbId,
+ active,
+ onSelect,
+ onAdd,
+}: {
+ kbId: string;
+ active: LibrarySelection | null;
+ onSelect: (sel: LibrarySelection) => void;
+ /** 缺省时隐藏 "+"(如文档查看页) */
+ onAdd?: () => void;
+}) {
+ const docs = useQuery({
+ queryKey: ["documents", kbId],
+ queryFn: () => api.documents(kbId),
+ });
+ const sources = useQuery({
+ queryKey: ["sources", kbId],
+ queryFn: () => api.sources(kbId),
+ });
+
+ const allDocs = docs.data ?? [];
+ const sourceList = sources.data?.sources ?? [];
+ const uploadsCount = allDocs.filter((d) => !d.source_id).length;
+
+ return (
+ <aside className={`${RAIL_CLS} flex flex-col`}>
+ {/* 全部文档置顶为一级入口;SOURCES 小节(含 +)居其下 */}
+ <div className="px-2 pt-3">
+ <RailItem
+ active={active === "all"}
+ onClick={() => onSelect("all")}
+ icon={<LibraryIcon size={14} />}
+ label={S.library.allDocs}
+ count={allDocs.length}
+ />
+ </div>
+ <div className="flex items-center justify-between px-4 pt-3 pb-1.5">
+ <span className="text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-500">
+ {S.library.sources}
+ </span>
+ {onAdd && (
+ <button
+ onClick={onAdd}
+ title={S.library.addSource}
+ className="text-neutral-500 hover:text-neutral-200"
+ >
+ <Plus size={14} />
+ </button>
+ )}
+ </div>
+ <div className="u-scroll flex-1 overflow-y-auto px-2 pb-3 space-y-0.5">
+ {/* Uploads:常驻默认来源(上传的默认去处,不可删除) */}
+ <RailItem
+ active={active === "uploads"}
+ onClick={() => onSelect("uploads")}
+ icon={<Upload size={14} />}
+ label={S.library.uploads}
+ count={uploadsCount}
+ />
+ {sourceList.map((s) => {
+ const Icon = sourceIcon(s);
+ return (
+ <RailItem
+ key={s.id}
+ active={active === s.id}
+ onClick={() => onSelect(s.id)}
+ icon={<Icon size={14} />}
+ label={s.name}
+ count={s.doc_count}
+ dot={
+ SYNCING_KINDS.has(s.kind) || s.kind === "api"
+ ? SYNC_DOT[s.last_sync_status]
+ : undefined
+ }
+ />
+ );
+ })}
+ </div>
+ </aside>
+ );
+}
diff --git a/web/src/pages/UserMenu.tsx b/web/src/pages/UserMenu.tsx
new file mode 100644
index 00000000..37f0fa99
--- /dev/null
+++ b/web/src/pages/UserMenu.tsx
@@ -0,0 +1,186 @@
+/* 用户菜单:顶栏右侧的头像胶囊 + 弹出面板(个人信息 / 系统管理 / 登出)。
+ Shell(KB 工作区)与 AccountShell(账户层)共用。 */
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useNavigate } from "@tanstack/react-router";
+import { BookMarked, LogOut, ShieldCheck, UserRound } from "lucide-react";
+import { api, type User } from "../api";
+import { S } from "../i18n";
+
+/** 首字母头像:中性灰底(chrome 零色偏),拉丁取词首两枚,CJK 取前两字。 */
+export function Avatar({ name, size = 24 }: { name: string; size?: number }) {
+ const trimmed = name.trim();
+ const words = trimmed.split(/\s+/).filter(Boolean);
+ const initials =
+ words.length >= 2
+ ? (words[0][0] + words[1][0]).toUpperCase()
+ : [...trimmed].slice(0, 2).join("").toUpperCase();
+ return (
+ <span
+ className="inline-grid place-items-center rounded-full bg-white/[0.09] border border-white/10 text-neutral-200 select-none shrink-0"
+ style={{ width: size, height: size, fontSize: Math.round(size * 0.38) }}
+ >
+ {initials}
+ </span>
+ );
+}
+
+export function UserMenu({ user }: { user: User }) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const chipRef = useRef<HTMLButtonElement>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ const navigate = useNavigate();
+ const queryClient = useQueryClient();
+
+ // 原地变形(FLIP):面板盖在胶囊原位,首帧压到胶囊的真实边界
+ //(右上角对齐,圆角 999px),下一帧过渡到面板全形——胶囊"长成"面板
+ useLayoutEffect(() => {
+ if (!open) return;
+ const panel = panelRef.current;
+ const chip = chipRef.current;
+ if (!panel || !chip) return;
+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
+ const c = chip.getBoundingClientRect();
+ const p = panel.getBoundingClientRect();
+ if (p.width < 1 || p.height < 1) return;
+ panel.style.transformOrigin = "top right";
+ panel.style.transform = `scale(${c.width / p.width}, ${c.height / p.height})`;
+ panel.style.borderRadius = "999px";
+ panel.style.opacity = "0.35";
+ const raf = requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ panel.style.transition =
+ "transform 0.26s cubic-bezier(0.16,1,0.3,1), border-radius 0.26s cubic-bezier(0.16,1,0.3,1), opacity 0.18s ease";
+ panel.style.transform = "scale(1, 1)";
+ panel.style.borderRadius = "12px";
+ panel.style.opacity = "1";
+ }),
+ );
+ return () => cancelAnimationFrame(raf);
+ }, [open]);
+
+ // 反向变形收回:面板缩回胶囊边界后再卸载(导航等即时场景直接关)
+ const closingRef = useRef(false);
+ const close = () => {
+ const panel = panelRef.current;
+ const chip = chipRef.current;
+ if (closingRef.current) return;
+ if (!panel || !chip || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ setOpen(false);
+ return;
+ }
+ closingRef.current = true;
+ const c = chip.getBoundingClientRect();
+ // offsetWidth/Height:布局尺寸,不受当前 transform 影响
+ panel.style.transition =
+ "transform 0.2s cubic-bezier(0.5,0,0.9,0.4), border-radius 0.2s cubic-bezier(0.5,0,0.9,0.4), opacity 0.16s ease";
+ panel.style.transform = `scale(${c.width / panel.offsetWidth}, ${c.height / panel.offsetHeight})`;
+ panel.style.borderRadius = "999px";
+ panel.style.opacity = "0.3";
+ window.setTimeout(() => {
+ closingRef.current = false;
+ setOpen(false);
+ }, 190);
+ };
+
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ if (rootRef.current && !rootRef.current.contains(e.target as Node)) close();
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") close();
+ };
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ const go = (to: string) => {
+ setOpen(false);
+ navigate({ to });
+ };
+
+ const logout = async () => {
+ await api.logout();
+ queryClient.clear();
+ navigate({ to: "/login" });
+ };
+
+ // 行通到面板边缘(与 Dropdown 同语汇):容器不留内衬,高度由行自身撑
+ const item =
+ "w-full flex items-center gap-2.5 px-3.5 py-2.5 text-[13px] text-neutral-300 hover:bg-white/[0.06] hover:text-white transition-colors";
+
+ return (
+ <div ref={rootRef} className="relative">
+ <button
+ ref={chipRef}
+ onClick={() => setOpen((v) => !v)}
+ className={`flex items-center gap-2 rounded-full py-1 pl-1 pr-3 transition-[background-color,opacity] duration-150 ${
+ open ? "opacity-0" : "hover:bg-white/[0.06]"
+ }`}
+ >
+ <Avatar name={user.display_name} size={24} />
+ <span className="text-sm text-neutral-300">{user.display_name}</span>
+ </button>
+
+ {open && (
+ <div
+ ref={panelRef}
+ className="u-menu-glass absolute right-0 top-0 w-64 rounded-xl shadow-2xl z-50 overflow-hidden"
+ >
+ {/* 身份头:再点一下缩回胶囊 */}
+ <div
+ onClick={close}
+ className="flex items-center gap-3 px-3.5 py-3 border-b border-white/10 cursor-pointer hover:bg-white/[0.04] transition-colors"
+ >
+ <Avatar name={user.display_name} size={32} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-[13px] font-medium text-neutral-100">
+ {user.display_name}
+ </span>
+ {user.is_admin && (
+ <span className="u-chip u-chip-neutral !text-[10px] !px-1.5">
+ {S.account.adminChip}
+ </span>
+ )}
+ </div>
+ <div className="truncate text-[11px] text-neutral-500">{user.email}</div>
+ </div>
+ </div>
+
+ <div>
+ <button onClick={() => go("/account")} className={item}>
+ <UserRound size={13} className="text-neutral-500" />
+ {S.account.profile}
+ </button>
+ {/* 人人可看:全部可见库 + 我在每个库的身份 */}
+ <button onClick={() => go("/account/kbs")} className={item}>
+ <BookMarked size={13} className="text-neutral-500" />
+ {S.account.kbsNav}
+ </button>
+ {user.is_admin && (
+ <button onClick={() => go("/admin")} className={item}>
+ <ShieldCheck size={13} className="text-neutral-500" />
+ {S.account.administration}
+ </button>
+ )}
+ </div>
+
+ <div className="border-t border-white/10">
+ <button onClick={logout} className={`${item} !text-[var(--u-danger)]`}>
+ <LogOut size={13} />
+ {S.nav.signOut}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/pages/squareShellProgram.ts b/web/src/pages/squareShellProgram.ts
new file mode 100644
index 00000000..5b9cb8bb
--- /dev/null
+++ b/web/src/pages/squareShellProgram.ts
@@ -0,0 +1,187 @@
+// 方形节点的四层渲染 program —— 与圆形 createNodeBorderProgram 完全同构:
+// 状态环(0.1) → 钢灰描边(0.07) → 深色壳(0.3) → 微彩核心(fill)。
+// 圆形用欧氏距离 length(),方形改用切比雪夫距离 max(|x|,|y|),
+// 几何沿用 @sigma/node-square:6 顶点四边形、角点 ±45°/±135°、sqrt8 缩放
+//(等效半边长与圆形半径一致,hover/selected 状态环两种形状表现对齐)。
+
+import { NodeProgram } from "sigma/rendering";
+import type { ProgramInfo } from "sigma/rendering";
+import type { NodeDisplayData, RenderParams } from "sigma/types";
+import { floatColor } from "sigma/utils";
+
+const { UNSIGNED_BYTE, FLOAT } = WebGLRenderingContext;
+
+const UNIFORMS = ["u_sizeRatio", "u_correctionRatio", "u_cameraAngle", "u_matrix"] as const;
+
+const VERTEX_SHADER_SOURCE = /*glsl*/ `
+attribute vec2 a_position;
+attribute float a_size;
+attribute float a_angle;
+
+uniform mat3 u_matrix;
+uniform float u_sizeRatio;
+uniform float u_cameraAngle;
+uniform float u_correctionRatio;
+
+varying vec2 v_diffVector;
+varying float v_radius;
+
+#ifdef PICKING_MODE
+attribute vec4 a_id;
+varying vec4 v_color;
+#else
+attribute vec4 a_ringColor;
+attribute vec4 a_borderColor;
+attribute vec4 a_shellColor;
+attribute vec4 a_color;
+varying vec4 v_ringColor;
+varying vec4 v_borderColor;
+varying vec4 v_shellColor;
+varying vec4 v_fillColor;
+#endif
+
+const float sqrt_8 = sqrt(8.0);
+const float sqrt_2 = sqrt(2.0);
+
+void main() {
+ float size = a_size * u_correctionRatio / u_sizeRatio * sqrt_8;
+ // 屏幕上保持轴对齐(跟随相机旋转),切比雪夫度量用未旋转的本地坐标
+ float angle = a_angle + u_cameraAngle;
+ vec2 diffVector = size * vec2(cos(angle), sin(angle));
+ vec2 position = a_position + diffVector;
+ gl_Position = vec4((u_matrix * vec3(position, 1)).xy, 0, 1);
+
+ v_diffVector = size * vec2(cos(a_angle), sin(a_angle));
+ v_radius = size / sqrt_2; // 半边长,与圆形程序的半径等值
+
+ #ifdef PICKING_MODE
+ v_color = a_id;
+ #else
+ v_ringColor = a_ringColor;
+ v_borderColor = a_borderColor;
+ v_shellColor = a_shellColor;
+ v_fillColor = a_color;
+ #endif
+}
+`;
+
+const FRAGMENT_SHADER_SOURCE = /*glsl*/ `
+precision highp float;
+
+varying vec2 v_diffVector;
+varying float v_radius;
+
+#ifdef PICKING_MODE
+varying vec4 v_color;
+#else
+varying vec4 v_ringColor;
+varying vec4 v_borderColor;
+varying vec4 v_shellColor;
+varying vec4 v_fillColor;
+#endif
+
+uniform float u_correctionRatio;
+
+const float bias = 255.0 / 254.0;
+const vec4 transparent = vec4(0.0, 0.0, 0.0, 0.0);
+
+void main(void) {
+ float dist = max(abs(v_diffVector.x), abs(v_diffVector.y));
+
+ #ifdef PICKING_MODE
+ if (dist > v_radius)
+ gl_FragColor = transparent;
+ else {
+ gl_FragColor = v_color;
+ gl_FragColor.a *= bias;
+ }
+ #else
+ float aaBorder = 2.0 * u_correctionRatio;
+ // 层厚比例与圆形配置一致:0.1 / 0.07 / 0.3 / 剩余为核心
+ float r0 = v_radius;
+ float r1 = r0 - v_radius * 0.1;
+ float r2 = r1 - v_radius * 0.07;
+ float r3 = r2 - v_radius * 0.3;
+
+ vec4 c1 = v_ringColor; c1.a *= bias;
+ vec4 c2 = v_borderColor; c2.a *= bias;
+ vec4 c3 = v_shellColor; c3.a *= bias;
+ vec4 c4 = v_fillColor; c4.a *= bias;
+
+ if (dist > r0) {
+ gl_FragColor = transparent;
+ } else if (dist > r0 - aaBorder) {
+ gl_FragColor = mix(c1, transparent, (dist - r0 + aaBorder) / aaBorder);
+ } else if (dist > r1) {
+ gl_FragColor = c1;
+ } else if (dist > r1 - aaBorder) {
+ gl_FragColor = mix(c2, c1, (dist - r1 + aaBorder) / aaBorder);
+ } else if (dist > r2) {
+ gl_FragColor = c2;
+ } else if (dist > r2 - aaBorder) {
+ gl_FragColor = mix(c3, c2, (dist - r2 + aaBorder) / aaBorder);
+ } else if (dist > r3) {
+ gl_FragColor = c3;
+ } else if (dist > r3 - aaBorder) {
+ gl_FragColor = mix(c4, c3, (dist - r3 + aaBorder) / aaBorder);
+ } else {
+ gl_FragColor = c4;
+ }
+ #endif
+}
+`;
+
+export class NodeSquareShellProgram extends NodeProgram<(typeof UNIFORMS)[number]> {
+ getDefinition() {
+ return {
+ VERTICES: 6,
+ VERTEX_SHADER_SOURCE,
+ FRAGMENT_SHADER_SOURCE,
+ METHOD: WebGLRenderingContext.TRIANGLES,
+ UNIFORMS,
+ ATTRIBUTES: [
+ { name: "a_position", size: 2, type: FLOAT },
+ { name: "a_id", size: 4, type: UNSIGNED_BYTE, normalized: true },
+ { name: "a_size", size: 1, type: FLOAT },
+ { name: "a_ringColor", size: 4, type: UNSIGNED_BYTE, normalized: true },
+ { name: "a_borderColor", size: 4, type: UNSIGNED_BYTE, normalized: true },
+ { name: "a_shellColor", size: 4, type: UNSIGNED_BYTE, normalized: true },
+ { name: "a_color", size: 4, type: UNSIGNED_BYTE, normalized: true },
+ ],
+ CONSTANT_ATTRIBUTES: [{ name: "a_angle", size: 1, type: FLOAT }],
+ CONSTANT_DATA: [
+ [Math.PI / 4],
+ [(3 * Math.PI) / 4],
+ [-Math.PI / 4],
+ [(3 * Math.PI) / 4],
+ [-Math.PI / 4],
+ [(-3 * Math.PI) / 4],
+ ],
+ };
+ }
+
+ processVisibleItem(nodeIndex: number, startIndex: number, data: NodeDisplayData): void {
+ const array = this.array;
+ const d = data as NodeDisplayData & {
+ ringColor?: string;
+ borderColor?: string;
+ shellColor?: string;
+ };
+ array[startIndex++] = data.x;
+ array[startIndex++] = data.y;
+ array[startIndex++] = nodeIndex;
+ array[startIndex++] = data.size;
+ array[startIndex++] = floatColor(d.ringColor || "rgba(0,0,0,0)");
+ array[startIndex++] = floatColor(d.borderColor || "rgba(0,0,0,0)");
+ array[startIndex++] = floatColor(d.shellColor || "rgba(0,0,0,0)");
+ array[startIndex++] = floatColor(data.color);
+ }
+
+ setUniforms(params: RenderParams, { gl, uniformLocations }: ProgramInfo): void {
+ const { u_sizeRatio, u_correctionRatio, u_cameraAngle, u_matrix } = uniformLocations;
+ gl.uniform1f(u_sizeRatio, params.sizeRatio);
+ gl.uniform1f(u_correctionRatio, params.correctionRatio);
+ gl.uniform1f(u_cameraAngle, params.cameraAngle);
+ gl.uniformMatrix3fv(u_matrix, false, params.matrix);
+ }
+}
diff --git a/web/src/router.tsx b/web/src/router.tsx
new file mode 100644
index 00000000..ce700380
--- /dev/null
+++ b/web/src/router.tsx
@@ -0,0 +1,222 @@
+import {
+ createRootRoute,
+ createRoute,
+ createRouter,
+ redirect,
+} from "@tanstack/react-router";
+import { Account } from "./pages/Account";
+import { AccountShell } from "./pages/AccountShell";
+import { Chat } from "./pages/Chat";
+import { DocViewer } from "./pages/DocViewer";
+import { DocsPage } from "./pages/Docs";
+import { Graph } from "./pages/Graph";
+import { Library } from "./pages/Library";
+import { Login } from "./pages/Login";
+import { Privacy, Terms } from "./pages/Legal";
+import { KbSettings } from "./pages/KbSettings";
+import { MyKbs } from "./pages/MyKbs";
+import { NotFound } from "./pages/ServerDown";
+import { Ontology } from "./pages/Ontology";
+import { Review } from "./pages/Review";
+import { Search } from "./pages/Search";
+import { Settings } from "./pages/Settings";
+import { Shell } from "./pages/Shell";
+
+const rootRoute = createRootRoute();
+
+const loginRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/login",
+ component: Login,
+});
+
+// 公共法务页:登录前可达
+const privacyRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/privacy",
+ component: Privacy,
+});
+
+const termsRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/terms",
+ component: Terms,
+});
+
+const appRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ id: "app",
+ component: Shell,
+});
+
+const indexRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/",
+ beforeLoad: () => {
+ // 首页 = 图谱:产品的差异化门面
+ throw redirect({ to: "/graph" });
+ },
+});
+
+const chatRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/chat",
+ component: Chat,
+});
+
+// 会话即路由:/chat/$conversationId 只承载 URL(刷新/分享回到同一会话),
+// 渲染仍由父级 Chat 负责——父级在 /chat ↔ /chat/$id 间保持挂载,流式不断
+const chatConversationRoute = createRoute({
+ getParentRoute: () => chatRoute,
+ path: "$conversationId",
+ component: () => null,
+});
+
+const searchRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/search",
+ component: Search,
+});
+
+const graphRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/graph",
+ validateSearch: (search: Record<string, unknown>): { entity?: string } => ({
+ entity: typeof search.entity === "string" ? search.entity : undefined,
+ }),
+ component: Graph,
+});
+
+const docRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/doc/$docId",
+ validateSearch: (search: Record<string, unknown>): { chunk?: string } => ({
+ chunk: typeof search.chunk === "string" ? search.chunk : undefined,
+ }),
+ component: DocViewer,
+});
+
+const libraryRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/library",
+ validateSearch: (search: Record<string, unknown>): { src?: string } => ({
+ src: typeof search.src === "string" ? search.src : undefined,
+ }),
+ component: Library,
+});
+
+const ontologyRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/ontology",
+ component: Ontology,
+});
+
+const reviewRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/review",
+ component: Review,
+});
+
+// 内置文档:公开路由(登录前可读;私有部署离线可用)
+const docsIndexRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/docs",
+ beforeLoad: () => {
+ throw redirect({ to: "/docs/$slug", params: { slug: "ingest" } });
+ },
+});
+
+const docsRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/docs/$slug",
+ component: DocsPage,
+});
+
+// 账户层(Profile / Administration):与 KB 无关,用无 tab 导航的独立壳
+const accountShellRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ id: "account",
+ component: AccountShell,
+});
+
+const accountRoute = createRoute({
+ getParentRoute: () => accountShellRoute,
+ path: "/account",
+ component: Account,
+});
+
+const myKbsRoute = createRoute({
+ getParentRoute: () => accountShellRoute,
+ path: "/account/kbs",
+ component: MyKbs,
+});
+
+const adminRoute = createRoute({
+ getParentRoute: () => accountShellRoute,
+ path: "/admin",
+ // 深链指定页签(如 KB 数据节的"注册新连接"直达 Data sources)
+ validateSearch: (
+ search: Record<string, unknown>,
+ ): { tab?: "models" | "members" | "kbs" | "datasources" | "deployment" } => ({
+ tab:
+ search.tab === "models" ||
+ search.tab === "members" ||
+ search.tab === "kbs" ||
+ search.tab === "datasources" ||
+ search.tab === "deployment"
+ ? search.tab
+ : undefined,
+ }),
+ component: Settings,
+});
+
+// 旧路径兼容:/settings → /admin
+const settingsRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: "/settings",
+ beforeLoad: () => {
+ throw redirect({ to: "/admin" });
+ },
+});
+
+const kbSettingsRoute = createRoute({
+ getParentRoute: () => appRoute,
+ path: "/kb-settings",
+ validateSearch: (search: Record<string, unknown>): { kb?: string } => ({
+ kb: typeof search.kb === "string" ? search.kb : undefined,
+ }),
+ component: KbSettings,
+});
+
+const routeTree = rootRoute.addChildren([
+ loginRoute,
+ privacyRoute,
+ termsRoute,
+ settingsRoute,
+ docsIndexRoute,
+ docsRoute,
+ accountShellRoute.addChildren([accountRoute, myKbsRoute, adminRoute]),
+ appRoute.addChildren([
+ indexRoute,
+ chatRoute.addChildren([chatConversationRoute]),
+ searchRoute,
+ graphRoute,
+ docRoute,
+ libraryRoute,
+ reviewRoute,
+ ontologyRoute,
+ kbSettingsRoute,
+ ]),
+]);
+
+export const router = createRouter({
+ routeTree,
+ // 迷失之城:未知路径的惩戒页
+ defaultNotFoundComponent: NotFound,
+});
+
+declare module "@tanstack/react-router" {
+ interface Register {
+ router: typeof router;
+ }
+}
diff --git a/web/src/styles.css b/web/src/styles.css
new file mode 100644
index 00000000..f4f47c5e
--- /dev/null
+++ b/web/src/styles.css
@@ -0,0 +1,657 @@
+@import "tailwindcss";
+@plugin "@tailwindcss/typography";
+
+@theme {
+ --font-display: "Geist", "Inter", "Noto Sans SC", system-ui, sans-serif;
+ --font-sans: "Geist", "Inter", "Noto Sans SC", system-ui, sans-serif;
+}
+
+/* ============================================================
+ Utopia design tokens — Vercel-style neutral dark + glass.
+ Chromatic color is reserved for DATA (graph entities, status);
+ the chrome itself is monochrome.
+ ============================================================ */
+:root {
+ font-family: var(--font-sans);
+ color-scheme: dark;
+
+ /* 品牌字:碑铭式衬线(Marcellus 仅 400,一字不粗) */
+ --font-brand: "Marcellus", "Georgia", "Times New Roman", serif;
+
+ --u-ground: #0a0a0a;
+ --u-text: #ededed;
+ --u-text-2: #a1a1a1;
+ --u-text-3: #6e6e6e;
+
+ /* 单色 chrome:accent 也是中性亮灰,彩色只属于数据(实体色/状态语义色) */
+ --u-accent: #d4d4d4;
+ --u-accent-deep: 255, 255, 255;
+
+ --u-ok: #4cc38a;
+ --u-warn: #f2b66d;
+ /* 浅玫瑰:深底上的危险"文字/描边/点"专用(够亮才可读) */
+ --u-danger: #ff9daf;
+ /* 深红:危险"实底按钮"专用(浅玫瑰做底会发粉;亮红在单色 chrome 上嗓门过大),配白字 */
+ --u-danger-solid: #c9353a;
+ --u-violet: #c4a5ff;
+
+ --u-line: rgba(255, 255, 255, 0.08);
+ --u-line-strong: rgba(255, 255, 255, 0.14);
+ --u-surface: rgba(255, 255, 255, 0.04);
+ --u-surface-strong: rgba(10, 10, 10, 0.72);
+}
+
+body {
+ background-color: var(--u-ground);
+ color: var(--u-text);
+ min-height: 100vh;
+}
+
+/* 选中态:中性白纱替掉浏览器默认蓝(零色偏原则同样管到这里)。
+ 只设底色不改字色——半透明白纱下内容自身的颜色(代码令牌、实体色)仍透出 */
+::selection {
+ background: rgba(255, 255, 255, 0.22);
+}
+
+/* 空间感:极克制的中性顶光 + 暗角,零色偏 */
+body::before {
+ content: "";
+ position: fixed;
+ inset: 0;
+ z-index: -1;
+ background:
+ radial-gradient(1000px 600px at 50% -20%, rgba(255, 255, 255, 0.045), transparent 60%),
+ var(--u-ground);
+}
+
+/* ---- surfaces ---- */
+.glass {
+ background: var(--u-surface);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ border: 1px solid var(--u-line);
+}
+
+.glass-strong {
+ background: var(--u-surface-strong);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ border: 1px solid var(--u-line);
+}
+
+/* 弹出层(下拉/取色器等 popover):近实底——下层内容透出只会干扰,
+ 毛玻璃留给带遮罩的大弹窗 */
+.u-pop {
+ background: rgba(16, 16, 16, 0.98);
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ border: 1px solid var(--u-line-strong);
+}
+
+/* 弹层入场:锚点为原点的缩放浮现(用户菜单/下拉共用)。
+ 160ms + 出挑缓动(与 u-rise 同族),克制但有生气 */
+@keyframes u-pop-in-kf {
+ from {
+ opacity: 0;
+ transform: scale(0.96) translateY(-4px);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+.u-pop-in {
+ transform-origin: top right;
+ animation: u-pop-in-kf 0.16s cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+.u-pop-in-tl {
+ transform-origin: top left;
+}
+/* 向上弹出的变体(composer 停靠底部时菜单开口朝上) */
+@keyframes u-pop-up-kf {
+ from {
+ opacity: 0;
+ transform: scale(0.96) translateY(4px);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+ }
+}
+.u-pop-up {
+ transform-origin: bottom left;
+ animation: u-pop-up-kf 0.16s cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+
+/* 用户菜单:半透玻璃面(比 .u-pop 更透,加强模糊补偿可读性)。
+ 原地变形动画在组件内用 FLIP 实现(首帧压到胶囊真实边界再展开),
+ CSS 只负责面板的皮 */
+.u-menu-glass {
+ background: rgba(14, 14, 16, 0.85);
+ backdrop-filter: blur(24px);
+ -webkit-backdrop-filter: blur(24px);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .u-pop-in,
+ .u-pop-up {
+ animation: none;
+ }
+}
+
+.glass-hover {
+ transition: border-color 0.15s;
+}
+.glass-hover:hover {
+ border-color: var(--u-line-strong);
+}
+
+/* ---- form controls ---- */
+.input-dark {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--u-line-strong);
+ color: var(--u-text);
+ border-radius: 0.5rem;
+}
+.input-dark::placeholder {
+ color: var(--u-text-3);
+}
+.input-dark:focus {
+ outline: none;
+ border-color: rgba(255, 255, 255, 0.4);
+ box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.08);
+}
+select.input-dark option {
+ background: #111111;
+ color: var(--u-text);
+}
+
+/* mono 输入框的 placeholder 回默认字体(提示语不是代码) */
+.u-placeholder-sans::placeholder {
+ font-family: var(--font-sans);
+}
+
+/* 数字输入:去掉原生 spinner,保持纯净外观 */
+.u-input-plain::-webkit-outer-spin-button,
+.u-input-plain::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+}
+.u-input-plain {
+ -moz-appearance: textfield;
+ appearance: textfield;
+}
+
+/* ---- buttons (Vercel: primary = white on black) ---- */
+.u-btn,
+.btn-primary,
+.btn-ghost {
+ border-radius: 0.5rem;
+ font-weight: 500;
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+}
+.u-btn:disabled,
+.btn-primary:disabled,
+.btn-ghost:disabled {
+ opacity: 0.4;
+}
+.u-btn-primary,
+.btn-primary {
+ background: var(--u-text);
+ border: 1px solid var(--u-text);
+ color: #0a0a0a;
+ font-weight: 600;
+}
+.u-btn-primary:hover:not(:disabled),
+.btn-primary:hover:not(:disabled) {
+ background: #ffffff;
+ border-color: #ffffff;
+}
+.u-btn-ghost,
+.btn-ghost {
+ border: 1px solid var(--u-line-strong);
+ color: var(--u-text-2);
+ background: transparent;
+}
+.u-btn-ghost:hover:not(:disabled),
+.btn-ghost:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--u-text);
+ border-color: rgba(255, 255, 255, 0.22);
+}
+
+/* ---- chips ---- */
+.u-chip {
+ display: inline-block;
+ border-radius: 9999px;
+ padding: 0.125rem 0.5rem;
+ font-size: 0.75rem;
+ line-height: 1.25;
+ white-space: nowrap;
+}
+.u-chip-neutral {
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--u-text-2);
+}
+.u-chip-info {
+ background: rgba(255, 255, 255, 0.12);
+ color: #ededed;
+}
+.u-chip-success {
+ background: rgba(76, 195, 138, 0.12);
+ color: var(--u-ok);
+}
+.u-chip-warn {
+ background: rgba(242, 182, 109, 0.12);
+ color: var(--u-warn);
+}
+.u-chip-danger {
+ background: rgba(255, 157, 175, 0.12);
+ color: var(--u-danger);
+}
+.u-chip-violet {
+ background: rgba(196, 165, 255, 0.12);
+ color: var(--u-violet);
+}
+
+/* ---- graph canvas: 图纸式大小网格(细密小格 + 每 4 格一条更亮的主线) ---- */
+.u-grid-bg {
+ background-image:
+ linear-gradient(rgba(255, 255, 255, 0.055) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(255, 255, 255, 0.055) 1px, transparent 1px),
+ linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);
+ background-size:
+ 104px 104px,
+ 104px 104px,
+ 26px 26px,
+ 26px 26px;
+}
+
+/* ---- interactive accents ---- */
+.u-bubble-user {
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+}
+.u-highlight {
+ border-color: rgba(255, 255, 255, 0.45) !important;
+ background: rgba(255, 255, 255, 0.06) !important;
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.12);
+}
+.u-nav-active {
+ background: rgba(255, 255, 255, 0.09);
+ color: #ffffff;
+}
+
+/* 引用定位闪现:进场强光收敛到持有亮度(运动比静态边框更抓眼)。
+ fill-mode both 让 100% 帧在类存续期间保持;移除类后由元素自身的
+ transition 淡回普通卡片 */
+@keyframes u-flash-kf {
+ 0% {
+ border-color: rgba(255, 255, 255, 0.9);
+ background-color: rgba(255, 255, 255, 0.14);
+ box-shadow:
+ 0 0 0 3px rgba(255, 255, 255, 0.3),
+ 0 0 36px rgba(255, 255, 255, 0.16);
+ }
+ 100% {
+ border-color: rgba(255, 255, 255, 0.55);
+ background-color: rgba(255, 255, 255, 0.07);
+ box-shadow:
+ 0 0 0 2px rgba(255, 255, 255, 0.16),
+ 0 0 18px rgba(255, 255, 255, 0.06);
+ }
+}
+.u-flash {
+ animation: u-flash-kf 0.9s cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+@media (prefers-reduced-motion: reduce) {
+ .u-flash {
+ animation: none;
+ border-color: rgba(255, 255, 255, 0.55);
+ background-color: rgba(255, 255, 255, 0.07);
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.16);
+ }
+}
+
+/* ---- text helpers ---- */
+.u-accent {
+ color: var(--u-accent);
+}
+.u-link {
+ color: var(--u-text);
+ text-decoration: underline;
+ text-underline-offset: 3px;
+ text-decoration-color: rgba(255, 255, 255, 0.3);
+}
+.u-link:hover {
+ text-decoration-color: rgba(255, 255, 255, 0.8);
+}
+.u-title {
+ font-family: var(--font-display);
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ color: #ffffff;
+}
+.brand-gradient {
+ color: #ffffff;
+ letter-spacing: -0.02em;
+}
+
+/* 登录卡:近实底,不用 backdrop-filter(对动画背景每帧重算模糊,代价高) */
+.u-card-opaque {
+ background: rgba(12, 12, 12, 0.92);
+ border: 1px solid var(--u-line);
+}
+
+/* ---- 入场动效(登录页等):淡入上浮 ---- */
+@keyframes u-rise-kf {
+ from {
+ opacity: 0;
+ transform: translateY(14px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+.u-rise {
+ animation: u-rise-kf 0.7s cubic-bezier(0.16, 1, 0.3, 1) both;
+}
+
+/* 登录成功谢幕:内容上浮淡出;巨构放大淡出(像穿过它进入系统) */
+@keyframes u-depart-kf {
+ to {
+ opacity: 0;
+ transform: translateY(-14px);
+ }
+}
+.u-depart {
+ animation: u-depart-kf 0.55s cubic-bezier(0.5, 0, 0.9, 0.4) forwards;
+}
+.u-scene-depart {
+ transition: transform 0.7s cubic-bezier(0.5, 0, 0.9, 0.5), opacity 0.7s ease-in;
+ transform: scale(1.16);
+ opacity: 0;
+}
+
+/* 登录后首屏入场:整体淡入,衔接登录页谢幕 */
+@keyframes u-arrive-kf {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+.u-arrive {
+ animation: u-arrive-kf 0.45s ease both;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .u-rise,
+ .u-depart,
+ .u-arrive {
+ animation: none;
+ }
+ .u-scene-depart {
+ transition: none;
+ }
+}
+
+/* Chrome 自动填充的蓝底与"零色偏"冲突:压回中性深灰 */
+input:-webkit-autofill,
+input:-webkit-autofill:hover,
+input:-webkit-autofill:focus {
+ -webkit-box-shadow: 0 0 0 1000px #141414 inset;
+ -webkit-text-fill-color: var(--u-text);
+ caret-color: var(--u-text);
+}
+
+/* ---- 品牌字标:逐字母左→右淡入;hover 浮出外链箭头 ---- */
+@keyframes u-letter-kf {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+.u-letter {
+ animation: u-letter-kf 0.5s ease both;
+}
+.u-mark-arrow {
+ position: absolute;
+ right: -0.6em;
+ top: -0.08em;
+ width: 0.5em;
+ height: 0.5em;
+ color: var(--u-text-2);
+ opacity: 0;
+ transform: translate(-3px, 3px);
+ transition: opacity 0.18s ease, transform 0.18s ease;
+}
+a:hover > .u-mark-arrow {
+ opacity: 1;
+ transform: none;
+}
+@media (prefers-reduced-motion: reduce) {
+ .u-letter {
+ animation: none;
+ }
+ .u-mark-arrow {
+ transition: none;
+ }
+}
+
+/* toast 入场:复用淡入上浮关键帧,节奏更快 */
+.u-toast-in {
+ animation: u-rise-kf 0.25s ease both;
+}
+@media (prefers-reduced-motion: reduce) {
+ .u-toast-in {
+ animation: none;
+ }
+}
+
+/* 多行居中的短句:两行长度均衡,避免孤词 */
+.u-balance {
+ text-wrap: balance;
+}
+
+/* ---- numbers in chrome: 默认字体(Geist)+ 等宽数字,不再用 mono ---- */
+.u-num {
+ font-variant-numeric: tabular-nums;
+}
+
+/* ---- 全局滚动条:统一细条风格(Chromium 走 webkit 自绘;Firefox 走标准属性) ---- */
+@supports not selector(::-webkit-scrollbar) {
+ * {
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255, 255, 255, 0.14) transparent;
+ }
+}
+*::-webkit-scrollbar {
+ width: 7px;
+ height: 7px;
+}
+*::-webkit-scrollbar-track {
+ background: transparent;
+}
+*::-webkit-scrollbar-thumb {
+ background: rgba(255, 255, 255, 0.14);
+ border-radius: 4px;
+}
+*::-webkit-scrollbar-thumb:hover {
+ background: rgba(255, 255, 255, 0.26);
+}
+*::-webkit-scrollbar-corner {
+ background: transparent;
+}
+
+/* 面板内滚动区(滚动条样式已全局统一,这里只保留滚动隔离) */
+.u-scroll {
+ overscroll-behavior: contain;
+}
+
+/* ---- timeline scrubber ---- */
+.scrubber-range {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ position: absolute;
+ inset: 0;
+ margin: 0;
+ cursor: ew-resize;
+}
+.scrubber-range::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 2px;
+ height: 28px;
+ border-radius: 1px;
+ background: #ffffff;
+ box-shadow: 0 0 6px rgba(255, 255, 255, 0.5);
+ cursor: ew-resize;
+}
+.scrubber-range::-moz-range-thumb {
+ width: 2px;
+ height: 28px;
+ border: none;
+ border-radius: 1px;
+ background: #ffffff;
+ box-shadow: 0 0 6px rgba(255, 255, 255, 0.5);
+ cursor: ew-resize;
+}
+.scrubber-range::-webkit-slider-runnable-track {
+ background: transparent;
+}
+.scrubber-range::-moz-range-track {
+ background: transparent;
+}
+
+/* ---- 代码高亮(rehype-highlight / hljs):克制的粉彩令牌色,
+ 与实体色板同族——颜色属于内容,chrome 保持无色 ---- */
+.u-chat-prose .hljs-comment,
+.u-chat-prose .hljs-quote {
+ color: #7d8590;
+ font-style: italic;
+}
+.u-chat-prose .hljs-keyword,
+.u-chat-prose .hljs-selector-tag,
+.u-chat-prose .hljs-meta {
+ color: #9fa8ff;
+}
+.u-chat-prose .hljs-string,
+.u-chat-prose .hljs-regexp,
+.u-chat-prose .hljs-addition {
+ color: #63e2b7;
+}
+.u-chat-prose .hljs-number,
+.u-chat-prose .hljs-literal,
+.u-chat-prose .hljs-symbol {
+ color: #ffd479;
+}
+.u-chat-prose .hljs-title,
+.u-chat-prose .hljs-title.function_,
+.u-chat-prose .hljs-section {
+ color: #7fd0ff;
+}
+.u-chat-prose .hljs-type,
+.u-chat-prose .hljs-built_in,
+.u-chat-prose .hljs-class .hljs-title {
+ color: #5fd4d0;
+}
+.u-chat-prose .hljs-attr,
+.u-chat-prose .hljs-attribute,
+.u-chat-prose .hljs-variable,
+.u-chat-prose .hljs-template-variable {
+ color: #c4a5ff;
+}
+.u-chat-prose .hljs-deletion {
+ color: #ff8a9e;
+}
+
+/* 对话气泡内的 markdown:紧凑排版,色彩服从气泡 */
+.u-chat-prose > :first-child {
+ margin-top: 0;
+}
+.u-chat-prose > :last-child {
+ margin-bottom: 0;
+}
+.u-chat-prose p {
+ margin: 0.4em 0;
+}
+.u-chat-prose ul,
+.u-chat-prose ol {
+ margin: 0.4em 0;
+ padding-left: 1.25em;
+}
+.u-chat-prose ul {
+ list-style: disc;
+}
+.u-chat-prose ol {
+ list-style: decimal;
+}
+.u-chat-prose li {
+ margin: 0.15em 0;
+}
+.u-chat-prose strong {
+ color: #ffffff;
+ font-weight: 600;
+}
+.u-chat-prose h1,
+.u-chat-prose h2,
+.u-chat-prose h3 {
+ font-weight: 600;
+ color: #ffffff;
+ margin: 0.7em 0 0.3em;
+ font-size: 1em;
+}
+/* 分割线(模型爱写 ---):几乎隐形的发丝线,只当呼吸口,不当版面元素 */
+.u-chat-prose hr {
+ border: 0;
+ border-top: 1px solid var(--u-line);
+ margin: 1em 0;
+}
+.u-chat-prose code {
+ font-size: 0.85em;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 4px;
+ padding: 0.1em 0.35em;
+}
+.u-chat-prose pre {
+ background: rgba(0, 0, 0, 0.45);
+ border: 1px solid var(--u-line);
+ border-radius: 8px;
+ padding: 0.6em 0.8em;
+ overflow-x: auto;
+ margin: 0.5em 0;
+}
+.u-chat-prose pre code {
+ background: transparent;
+ padding: 0;
+}
+.u-chat-prose table {
+ border-collapse: collapse;
+ margin: 0.5em 0;
+ font-size: 0.9em;
+}
+.u-chat-prose th,
+.u-chat-prose td {
+ border: 1px solid var(--u-line-strong);
+ padding: 0.25em 0.6em;
+}
+.u-chat-prose a {
+ text-decoration: underline;
+ text-underline-offset: 2px;
+}
+.u-chat-prose blockquote {
+ border-left: 2px solid var(--u-line-strong);
+ padding-left: 0.75em;
+ color: var(--u-text-2);
+ margin: 0.4em 0;
+}
diff --git a/web/src/toast.tsx b/web/src/toast.tsx
new file mode 100644
index 00000000..3d673dbf
--- /dev/null
+++ b/web/src/toast.tsx
@@ -0,0 +1,70 @@
+/* 全局消息(toast):模块级单例 + <ToastHost/>(挂在应用根部一次)。
+ 任何模块 `import { toast } from "./toast"` 即可弹消息,无需 context 接线。
+ 右下角堆叠,success/info 3.8s、error 6s 自动消失,可手动关闭。 */
+import { useEffect, useState } from "react";
+import { AlertCircle, CheckCircle2, Info, X } from "lucide-react";
+
+type Kind = "success" | "error" | "info";
+type Item = { id: number; kind: Kind; text: string };
+
+let nextId = 1;
+let items: Item[] = [];
+let listener: ((items: Item[]) => void) | null = null;
+
+function dismiss(id: number) {
+ items = items.filter((t) => t.id !== id);
+ listener?.(items);
+}
+
+function push(kind: Kind, text: string) {
+ const id = nextId++;
+ items = [...items, { id, kind, text }];
+ listener?.(items);
+ window.setTimeout(() => dismiss(id), kind === "error" ? 6000 : 3800);
+}
+
+export const toast = {
+ success: (text: string) => push("success", text),
+ error: (text: string) => push("error", text),
+ info: (text: string) => push("info", text),
+};
+
+const ICON = { success: CheckCircle2, error: AlertCircle, info: Info } as const;
+const ICON_COLOR: Record<Kind, string> = {
+ success: "text-[var(--u-ok)]",
+ error: "text-[var(--u-danger)]",
+ info: "text-neutral-400",
+};
+
+export function ToastHost() {
+ const [list, setList] = useState<Item[]>(items);
+ useEffect(() => {
+ listener = setList;
+ return () => {
+ if (listener === setList) listener = null;
+ };
+ }, []);
+ if (!list.length) return null;
+ return (
+ <div className="pointer-events-none fixed bottom-5 right-5 z-[100] flex flex-col items-end gap-2">
+ {list.map((t) => {
+ const Icon = ICON[t.kind];
+ return (
+ <div
+ key={t.id}
+ className="u-pop u-toast-in pointer-events-auto flex items-center gap-2.5 rounded-xl py-2.5 pl-3.5 pr-2.5 text-sm text-neutral-200 shadow-xl"
+ >
+ <Icon size={15} className={`shrink-0 ${ICON_COLOR[t.kind]}`} />
+ <span className="max-w-xs">{t.text}</span>
+ <button
+ onClick={() => dismiss(t.id)}
+ className="text-neutral-600 hover:text-neutral-300"
+ >
+ <X size={13} />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/web/src/ui/index.tsx b/web/src/ui/index.tsx
new file mode 100644
index 00000000..bc17e7cf
--- /dev/null
+++ b/web/src/ui/index.tsx
@@ -0,0 +1,617 @@
+/* Utopia UI 组件库 — 页面只用这里的组件与 styles.css 语义类,不写颜色字面量。 */
+import { useEffect, useRef, useState } from "react";
+import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactNode } from "react";
+import {
+ ArrowUpRight,
+ Check,
+ ChevronDown,
+ ChevronLeft,
+ ChevronRight,
+ Search as SearchIcon,
+} from "lucide-react";
+import { S } from "../i18n";
+
+/** 应用内左栏统一底座:宽度 + 玻璃面(各页在此之上加 flex/padding)。
+ 以最宽的 Ontology(w-64)为基准——rail 装的是名字,宽一档少截断。 */
+export const RAIL_CLS = "w-64 shrink-0 glass-strong border-y-0 border-l-0";
+
+/** 品牌字标:Marcellus 衬线,逐字母从左到右淡入;hover 浮出 ↗,点击去官网。
+ 箭头/偏移全部用 em,跟随使用处的字号缩放(登录大标题与顶栏共用)。 */
+export function Wordmark({ className }: { className?: string }) {
+ return (
+ <a
+ href={S.app.siteUrl}
+ target="_blank"
+ rel="noreferrer"
+ title="utopia.bi"
+ className={cn("relative inline-flex text-white", className)}
+ style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.06em" }}
+ >
+ {[...S.app.name].map((ch, i) => (
+ <span key={i} className="u-letter" style={{ animationDelay: `${80 + i * 65}ms` }}>
+ {ch}
+ </span>
+ ))}
+ <ArrowUpRight className="u-mark-arrow" aria-hidden />
+ </a>
+ );
+}
+
+export function cn(...parts: (string | false | null | undefined)[]): string {
+ return parts.filter(Boolean).join(" ");
+}
+
+/* ---------- Button ---------- */
+type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
+ variant?: "primary" | "ghost";
+ size?: "sm" | "md";
+};
+
+export function Button({ variant = "primary", size = "md", className, ...props }: ButtonProps) {
+ return (
+ <button
+ className={cn(
+ "u-btn",
+ variant === "primary" ? "u-btn-primary" : "u-btn-ghost",
+ size === "sm" ? "px-3 py-1.5 text-xs" : "px-4 py-2 text-sm",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+/* ---------- Input / Select ---------- */
+export function Input({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) {
+ return <input className={cn("input-dark px-3 py-2 text-sm", className)} {...props} />;
+}
+
+/* ---------- Dropdown(自制下拉,替代原生 select:原生弹层无法主题化) ---------- */
+export interface DropdownOption {
+ value: string;
+ label: ReactNode;
+}
+
+export function Dropdown({
+ value,
+ options,
+ onChange,
+ placeholder,
+ className,
+ size = "md",
+ icon,
+ menuLabel,
+ footer,
+}: {
+ value: string;
+ options: DropdownOption[];
+ onChange: (v: string) => void;
+ placeholder?: string;
+ className?: string;
+ size?: "sm" | "md";
+ /** 触发器左侧的语义图标(说明"这一级是什么") */
+ icon?: ReactNode;
+ /** 弹层顶部的小标题(同时作为触发器 title 提示) */
+ menuLabel?: string;
+ /** 弹层底部固定操作区(点击后弹层关闭) */
+ footer?: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const onDoc = (e: MouseEvent) => {
+ if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("mousedown", onDoc);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDoc);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ const current = options.find((o) => o.value === value);
+ const pad = size === "sm" ? "px-2.5 py-1 text-xs" : "px-3 py-1.5 text-sm";
+
+ return (
+ <div ref={rootRef} className={cn("relative", className)}>
+ <button
+ type="button"
+ onClick={() => setOpen(!open)}
+ title={menuLabel}
+ className={cn("input-dark w-full flex items-center gap-2 text-left", pad)}
+ >
+ {icon && <span className="shrink-0 text-neutral-500">{icon}</span>}
+ <span className="flex-1 min-w-0 truncate">
+ {current?.label ?? <span className="text-neutral-600">{placeholder ?? ""}</span>}
+ </span>
+ <ChevronDown
+ size={12}
+ className={cn("shrink-0 text-neutral-500 transition-transform", open && "rotate-180")}
+ />
+ </button>
+ {open && (
+ <div className="u-pop u-pop-in u-pop-in-tl absolute z-50 mt-1 w-full rounded-lg shadow-xl overflow-hidden">
+ {menuLabel && (
+ <div className="px-2.5 pt-2 pb-1 text-[9.5px] font-medium uppercase tracking-[0.1em] text-neutral-600 border-b border-white/5">
+ {menuLabel}
+ </div>
+ )}
+ {/* 选项行顶满面板边缘(无内衬):单选项时整个菜单被这一项填满 */}
+ <div className="u-scroll max-h-60 overflow-y-auto">
+ {options.map((o) => (
+ <button
+ key={o.value}
+ type="button"
+ onClick={() => {
+ onChange(o.value);
+ setOpen(false);
+ }}
+ className={cn(
+ "w-full flex items-center gap-2 text-left",
+ pad,
+ o.value === value
+ ? "bg-white/[0.12] text-white"
+ : "text-neutral-300 hover:bg-white/[0.06] hover:text-white",
+ )}
+ >
+ <span className="flex-1 min-w-0 truncate">{o.label}</span>
+ {o.value === value && <Check size={12} className="shrink-0 text-neutral-400" />}
+ </button>
+ ))}
+ </div>
+ {footer && (
+ <div className="border-t border-white/10" onClick={() => setOpen(false)}>
+ {footer}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---------- SearchSelect(可搜索选择器:无界对象列表专用——成员、父类、数据源…)
+ 触发器本身是输入框:聚焦即开、键入即过滤;渲染上限 maxVisible,超出提示继续
+ 输入收窄。小而有界的枚举(角色/数据类型…)仍用 Dropdown,两击即达不必打字。 ---------- */
+export interface SearchSelectOption {
+ value: string;
+ /** 主文案:过滤与选中回显的依据(纯字符串,不能是节点) */
+ label: string;
+ /** 次要文案(邮箱、连接摘要…),一并参与过滤,弱化显示 */
+ hint?: string;
+ /** 层级缩进(浏览态展示树形;键入过滤后拉平对齐) */
+ indent?: number;
+}
+
+export function SearchSelect({
+ value,
+ options,
+ onChange,
+ placeholder,
+ className,
+ size = "md",
+ maxVisible = 8,
+}: {
+ value: string;
+ options: SearchSelectOption[];
+ onChange: (v: string) => void;
+ placeholder?: string;
+ className?: string;
+ size?: "sm" | "md";
+ maxVisible?: number;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [active, setActive] = useState(0);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const current = options.find((o) => o.value === value);
+ const q = query.trim().toLowerCase();
+ const matches = q
+ ? options.filter((o) => `${o.label} ${o.hint ?? ""}`.toLowerCase().includes(q))
+ : options;
+ const visible = matches.slice(0, maxVisible);
+ const hidden = matches.length - visible.length;
+
+ const pick = (v: string) => {
+ onChange(v);
+ setOpen(false);
+ setQuery("");
+ inputRef.current?.blur();
+ };
+
+ const pad = size === "sm" ? "pl-7 pr-2.5 py-1 text-xs" : "pl-8 pr-3 py-1.5 text-sm";
+ const rowPad = size === "sm" ? "px-2.5 py-1 text-xs" : "px-3 py-1.5 text-sm";
+
+ return (
+ <div className={cn("relative", className)}>
+ <SearchIcon
+ size={size === "sm" ? 11 : 13}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-600 pointer-events-none"
+ />
+ <input
+ ref={inputRef}
+ className={cn("input-dark w-full", pad)}
+ value={open ? query : (current?.label ?? "")}
+ /* 打开后把当前选中项挪进 placeholder:边打字边能看到现值 */
+ placeholder={open ? current?.label || placeholder : placeholder}
+ onFocus={() => {
+ setOpen(true);
+ setQuery("");
+ setActive(0);
+ }}
+ /* 选项行 mousedown 已 preventDefault(不夺焦点),走到这里的失焦都是真离开 */
+ onBlur={() => setOpen(false)}
+ onChange={(e) => {
+ setQuery(e.target.value);
+ setActive(0);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ setOpen(false);
+ inputRef.current?.blur();
+ } else if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setActive((a) => Math.min(a + 1, visible.length - 1));
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setActive((a) => Math.max(a - 1, 0));
+ } else if (e.key === "Enter" && visible[active]) {
+ e.preventDefault();
+ pick(visible[active].value);
+ }
+ }}
+ />
+ {open && (
+ <div className="u-pop u-pop-in u-pop-in-tl absolute z-50 mt-1 w-full rounded-lg shadow-xl overflow-hidden">
+ {visible.map((o, i) => (
+ <button
+ key={o.value}
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => pick(o.value)}
+ onMouseEnter={() => setActive(i)}
+ className={cn(
+ "w-full flex items-center gap-2 text-left",
+ rowPad,
+ i === active ? "bg-white/[0.08] text-white" : "text-neutral-300",
+ )}
+ >
+ {!q && !!o.indent && (
+ <span className="shrink-0" style={{ width: o.indent * 14 }} />
+ )}
+ <span className="min-w-0 flex-1 truncate">
+ {o.label}
+ {o.hint && <span className="ml-2 text-neutral-500">{o.hint}</span>}
+ </span>
+ {o.value === value && <Check size={12} className="shrink-0 text-neutral-400" />}
+ </button>
+ ))}
+ {visible.length === 0 && (
+ <p className={cn(rowPad, "text-neutral-600")}>{S.ui.noMatches}</p>
+ )}
+ {hidden > 0 && (
+ <div
+ className={cn(
+ rowPad,
+ "border-t border-white/5 text-[11px] text-neutral-600",
+ )}
+ >
+ {S.ui.keepTyping(hidden)}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---------- ColorPicker(精选粉彩色板 + hex 兜底;实体色刻意不开放全色域) ---------- */
+export const ENTITY_PALETTE = [
+ "#7fd0ff", "#5fa8ff", "#5fd4d0", "#63e2b7",
+ "#4cc38a", "#a8d878", "#ffd479", "#f2b66d",
+ "#ff9d76", "#ff8a9e", "#ff9daf", "#e797d8",
+ "#c4a5ff", "#9fa8ff", "#8ea5bd", "#b3b9c4",
+];
+
+export function ColorPicker({
+ value,
+ onChange,
+ shape,
+}: {
+ value: string;
+ onChange: (v: string) => void;
+ /** 给定时,色井渲染"形状 + 颜色"而不是整块填充(方形是直角,与图谱节点一致) */
+ shape?: "circle" | "square";
+}) {
+ const [open, setOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const valid = /^#[0-9a-fA-F]{6}$/.test(value);
+
+ useEffect(() => {
+ if (!open) return;
+ const onDoc = (e: MouseEvent) => {
+ if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ document.addEventListener("mousedown", onDoc);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDoc);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+
+ return (
+ <div ref={rootRef} className="relative inline-block">
+ {/* 触发器:当前颜色色块(Figma 式 color well);带 shape 时渲染形状 + 颜色 */}
+ {shape ? (
+ <button
+ type="button"
+ title={value}
+ onClick={() => setOpen(!open)}
+ className="h-8 w-14 rounded-lg border border-white/15 hover:border-white/35 transition-colors bg-white/[0.04] grid place-items-center"
+ >
+ <span
+ className={cn("h-3.5 w-3.5", shape === "circle" && "rounded-full")}
+ style={{ background: valid ? value : "#8ea5bd" }}
+ />
+ </button>
+ ) : (
+ <button
+ type="button"
+ title={value}
+ onClick={() => setOpen(!open)}
+ className="h-8 w-14 rounded-lg border border-white/15 hover:border-white/35 transition-colors"
+ style={{ background: valid ? value : "#8ea5bd" }}
+ />
+ )}
+ {open && (
+ // 显式宽度:绝对定位的收缩宽度会被 inline-block 触发器的 56px 容器块钳死
+ <div className="u-pop u-pop-in u-pop-in-tl absolute z-50 left-0 top-full mt-2 w-56 rounded-xl p-3 shadow-xl">
+ <div className="grid grid-cols-8 gap-1.5 mb-2.5">
+ {ENTITY_PALETTE.map((c) => (
+ <button
+ key={c}
+ type="button"
+ title={c}
+ onClick={() => {
+ onChange(c);
+ setOpen(false);
+ }}
+ className={cn(
+ "h-5 w-5 rounded-full transition-transform hover:scale-110",
+ value.toLowerCase() === c &&
+ "outline outline-2 outline-white/80 outline-offset-1",
+ )}
+ style={{ background: c }}
+ />
+ ))}
+ </div>
+ <input
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder="#8ea5bd"
+ className={cn(
+ "input-dark w-full px-2 py-1 text-xs font-mono",
+ !valid && "!border-[var(--u-danger)]",
+ )}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
+
+/* ---------- Pager(列表分页条:不足一页时自动隐藏) ---------- */
+export function Pager({
+ total,
+ pageSize,
+ page,
+ onPage,
+}: {
+ total: number;
+ pageSize: number;
+ page: number;
+ onPage: (p: number) => void;
+}) {
+ const pageCount = Math.max(1, Math.ceil(total / pageSize));
+ const safe = Math.min(page, pageCount - 1);
+ if (total <= pageSize) return null;
+ return (
+ <div className="mt-3 flex items-center justify-end gap-2 text-xs text-neutral-500">
+ <span className="u-num">
+ {S.library.pageOf(safe * pageSize + 1, Math.min((safe + 1) * pageSize, total), total)}
+ </span>
+ <button
+ onClick={() => onPage(safe - 1)}
+ disabled={safe === 0}
+ className="u-btn u-btn-ghost h-7 w-7 grid place-items-center rounded-lg"
+ >
+ <ChevronLeft size={13} />
+ </button>
+ <button
+ onClick={() => onPage(safe + 1)}
+ disabled={safe >= pageCount - 1}
+ className="u-btn u-btn-ghost h-7 w-7 grid place-items-center rounded-lg"
+ >
+ <ChevronRight size={13} />
+ </button>
+ </div>
+ );
+}
+
+/** 分页切片辅助:返回当前页数据与安全页号。 */
+export function pageSlice<T>(items: T[], page: number, pageSize: number): { rows: T[]; safe: number } {
+ const pageCount = Math.max(1, Math.ceil(items.length / pageSize));
+ const safe = Math.min(page, pageCount - 1);
+ return { rows: items.slice(safe * pageSize, (safe + 1) * pageSize), safe };
+}
+
+/* ---------- DangerConfirm(危险操作确认弹窗:可要求输入指定文本解锁) ---------- */
+export function DangerConfirm({
+ title,
+ hint,
+ requireText,
+ confirmLabel,
+ cancelLabel,
+ busy,
+ onConfirm,
+ onCancel,
+}: {
+ title: string;
+ hint: string;
+ /** 要求逐字输入的解锁文本(如资源名称);缺省则直接可确认 */
+ requireText?: string;
+ confirmLabel: string;
+ cancelLabel: string;
+ busy?: boolean;
+ onConfirm: () => void;
+ onCancel: () => void;
+}) {
+ const [text, setText] = useState("");
+ const unlocked = !requireText || text === requireText;
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") onCancel();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [onCancel]);
+
+ return (
+ <div
+ className="fixed inset-0 z-50 grid place-items-center bg-black/60 backdrop-blur-sm"
+ onMouseDown={(e) => {
+ if (e.target === e.currentTarget) onCancel();
+ }}
+ >
+ <div className="glass-strong w-[24rem] max-w-[calc(100vw-2rem)] rounded-2xl shadow-2xl p-5">
+ <h2 className="text-[15px] font-semibold text-[var(--u-danger)] mb-2">{title}</h2>
+ <p className="text-xs text-neutral-400 leading-relaxed mb-4">{hint}</p>
+ {requireText && (
+ <input
+ autoFocus
+ className="input-dark w-full px-3 py-2 text-sm mb-4"
+ placeholder={requireText}
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ />
+ )}
+ <div className="flex justify-end gap-2">
+ <button className="u-btn u-btn-ghost px-3.5 py-1.5 text-xs" onClick={onCancel}>
+ {cancelLabel}
+ </button>
+ <button
+ className="u-btn px-3.5 py-1.5 text-xs font-semibold disabled:opacity-40"
+ style={{ background: "var(--u-danger-solid)", color: "#ffffff" }}
+ disabled={!unlocked || busy}
+ onClick={onConfirm}
+ >
+ {confirmLabel}
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/* ---------- Panel(玻璃面板) ---------- */
+export function Panel({
+ strong = false,
+ className,
+ children,
+}: {
+ strong?: boolean;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className={cn(strong ? "glass-strong" : "glass", "rounded-xl", className)}>{children}</div>
+ );
+}
+
+/* ---------- Chip(状态胶囊) ---------- */
+export type ChipTone = "neutral" | "info" | "success" | "warn" | "danger" | "violet";
+
+export function Chip({
+ tone = "neutral",
+ className,
+ title,
+ children,
+}: {
+ tone?: ChipTone;
+ className?: string;
+ title?: string;
+ children: ReactNode;
+}) {
+ return (
+ <span className={cn("u-chip", `u-chip-${tone}`, className)} title={title}>
+ {children}
+ </span>
+ );
+}
+
+/* ---------- PageTitle ---------- */
+export function PageTitle({ className, children }: { className?: string; children: ReactNode }) {
+ return <h2 className={cn("u-title text-lg", className)}>{children}</h2>;
+}
+
+/* ---------- EmptyState ---------- */
+export function EmptyState({ icon, children }: { icon: ReactNode; children: ReactNode }) {
+ return (
+ <div className="text-center">
+ <div className="glass mx-auto mb-4 h-14 w-14 rounded-2xl grid place-items-center text-xl font-bold text-neutral-300">
+ {icon}
+ </div>
+ <div className="text-sm text-neutral-500 whitespace-pre-line">{children}</div>
+ </div>
+ );
+}
+
+/* ---------- Loading / ErrorText ---------- */
+export function Loading({ children }: { children: ReactNode }) {
+ return <div className="p-8 text-sm text-neutral-500">{children}</div>;
+}
+
+export function ErrorText({ children }: { children: ReactNode }) {
+ return <p className="text-sm text-rose-400">{children}</p>;
+}
+
+/* ---------- GithubMark(lucide 无品牌图标,官方 mark 内联) ---------- */
+export function GithubMark({ size = 16 }: { size?: number }) {
+ return (
+ <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
+ <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
+ </svg>
+ );
+}
+
+/* ---------- SectionMark(分区字标:Docs/账户层等,逐字母入场,点击回应用) ---------- */
+import { Link as RouterLink } from "@tanstack/react-router";
+export function SectionMark({ text, title }: { text: string; title: string }) {
+ return (
+ <RouterLink
+ to="/graph"
+ title={title}
+ className="relative inline-flex text-white text-[17px]"
+ style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.06em" }}
+ >
+ {[...text].map((ch, i) => (
+ <span key={i} className="u-letter" style={{ animationDelay: `${80 + i * 45}ms` }}>
+ {/* inline-flex 会折叠纯空格 span——换不折叠空格 */}
+ {ch === " " ? " " : ch}
+ </span>
+ ))}
+ </RouterLink>
+ );
+}
diff --git a/web/src/useKbEvents.ts b/web/src/useKbEvents.ts
new file mode 100644
index 00000000..17a006ae
--- /dev/null
+++ b/web/src/useKbEvents.ts
@@ -0,0 +1,25 @@
+// KB 事件流订阅:收到事件只做 react-query 失效重取(事件不带业务数据,天然幂等)。
+// EventSource 断线自动重连;替代 Library/Review 的轮询。
+import { useEffect } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+
+export function useKbEvents(kbId: string | undefined) {
+ const queryClient = useQueryClient();
+
+ useEffect(() => {
+ if (!kbId) return;
+ const es = new EventSource(`/api/v1/kbs/${kbId}/events`);
+ es.addEventListener("document", () => {
+ queryClient.invalidateQueries({ queryKey: ["documents", kbId] });
+ queryClient.invalidateQueries({ queryKey: ["graph"] });
+ });
+ es.addEventListener("review", () => {
+ queryClient.invalidateQueries({ queryKey: ["review", kbId] });
+ });
+ es.addEventListener("source", () => {
+ queryClient.invalidateQueries({ queryKey: ["sources", kbId] });
+ queryClient.invalidateQueries({ queryKey: ["documents", kbId] });
+ });
+ return () => es.close();
+ }, [kbId, queryClient]);
+}
diff --git a/web/src/useTitle.ts b/web/src/useTitle.ts
new file mode 100644
index 00000000..46b1f804
--- /dev/null
+++ b/web/src/useTitle.ts
@@ -0,0 +1,10 @@
+/* 网页标题系统:`{域} | {页面}`,品牌在前(产品决策;代价是多标签截断后同前缀)。
+ 域:Utopia(主应用)/ Utopia Charter(文档)/ Utopia Persona(账户)。 */
+import { useEffect } from "react";
+
+export function usePageTitle(...parts: (string | null | undefined)[]) {
+ const title = parts.filter(Boolean).join(" | ");
+ useEffect(() => {
+ if (title) document.title = title;
+ }, [title]);
+}
diff --git a/web/src/vite-env.d.ts b/web/src/vite-env.d.ts
new file mode 100644
index 00000000..11f02fe2
--- /dev/null
+++ b/web/src/vite-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="vite/client" />
diff --git a/web/src/wsStore.ts b/web/src/wsStore.ts
new file mode 100644
index 00000000..9822e138
--- /dev/null
+++ b/web/src/wsStore.ts
@@ -0,0 +1,23 @@
+// 当前工作区/知识库选择:localStorage 持久化 + useSyncExternalStore 订阅。
+function makeStore(key: string) {
+ let current: string | null =
+ typeof localStorage !== "undefined" ? localStorage.getItem(key) : null;
+ const listeners = new Set<() => void>();
+ return {
+ get: () => current,
+ set: (id: string) => {
+ current = id;
+ localStorage.setItem(key, id);
+ listeners.forEach((l) => l());
+ },
+ subscribe: (l: () => void) => {
+ listeners.add(l);
+ return () => {
+ listeners.delete(l);
+ };
+ },
+ };
+}
+
+export const wsStore = makeStore("utopia.ws");
+export const kbStore = makeStore("utopia.kb");
diff --git a/web/tsconfig.json b/web/tsconfig.json
new file mode 100644
index 00000000..60173bde
--- /dev/null
+++ b/web/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true,
+ "isolatedModules": true,
+ "noUnusedLocals": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src", "vite.config.ts"]
+}
diff --git a/web/vite.config.ts b/web/vite.config.ts
new file mode 100644
index 00000000..3dfe10fc
--- /dev/null
+++ b/web/vite.config.ts
@@ -0,0 +1,15 @@
+import { defineConfig } from "vite";
+import react from "@vitejs/plugin-react";
+import tailwindcss from "@tailwindcss/vite";
+
+export default defineConfig({
+ plugins: [react(), tailwindcss()],
+ server: {
+ // 多会话并行开发:PORT 由启动器分配(5173 被占时换口),未设时保持默认
+ port: process.env.PORT ? Number(process.env.PORT) : 5173,
+ proxy: {
+ // 后端端口可用 UTOPIA_DEV_API 覆盖(默认 18080,与 .env 的 UTOPIA_BIND_ADDR 一致)
+ "/api": process.env.UTOPIA_DEV_API ?? "http://127.0.0.1:18080",
+ },
+ },
+});