| 1 | #!/usr/bin/env node |
| 2 | // 端到端:实体消解的类型漂移处理。 |
| 3 | // |
| 4 | // 场景:同一团队名被三份文档抽成三种类型——organization / project / team(白名单外, |
| 5 | // 降级 concept 兜底)。期望:漂移对进审核队列 → mock 裁决全部 "same" → 链式合并收敛为 |
| 6 | // 一个实体(类型调和后非 concept),leads 时间线连贯(前任在新任起点自动闭合)。 |
| 7 | // |
| 8 | // 本脚本内嵌 mock LLM(OpenAI 兼容 /chat/completions:按分块标记回放抽取结果, |
| 9 | // 按提示词特征识别裁决请求并全判 same)。无 embedding 配置 → 走"无上下文可比"的 |
| 10 | // 宁分勿合 + 审核对路径。 |
| 11 | // |
| 12 | // 前置:utopia-server 已启动并连到一个干净的库。编排见 scripts/e2e_type_drift.sh。 |
| 13 | // 环境变量:E2E_BASE(默认 http://127.0.0.1:8317)、E2E_MOCK_PORT(默认 9317)。 |
| 14 | |
| 15 | import http from "node:http"; |
| 16 | |
| 17 | const BASE = process.env.E2E_BASE || "http://127.0.0.1:8317"; |
| 18 | const MOCK_PORT = Number(process.env.E2E_MOCK_PORT || 9317); |
| 19 | |
| 20 | // --------------------------------------------------------------------------- |
| 21 | // mock LLM |
| 22 | // --------------------------------------------------------------------------- |
| 23 | |
| 24 | const EXTRACTIONS = { |
| 25 | "E2E-DOC1": { |
| 26 | entities: [ |
| 27 | { name: "Orion platform team", type: "organization" }, |
| 28 | { name: "Alice Zhang", type: "person" }, |
| 29 | ], |
| 30 | facts: [ |
| 31 | { |
| 32 | subject: "Alice Zhang", |
| 33 | predicate: "leads", |
| 34 | object: "Orion platform team", |
| 35 | valid_from: "2023-01-15", |
| 36 | confidence: 0.95, |
| 37 | quote: "Alice Zhang has led the Orion platform team since 2023-01-15.", |
| 38 | }, |
| 39 | ], |
| 40 | }, |
| 41 | "E2E-DOC2": { |
| 42 | entities: [ |
| 43 | { name: "Orion platform team", type: "project" }, |
| 44 | { name: "Bob Li", type: "person" }, |
| 45 | ], |
| 46 | facts: [ |
| 47 | { |
| 48 | subject: "Bob Li", |
| 49 | predicate: "leads", |
| 50 | object: "Orion platform team", |
| 51 | valid_from: "2024-05-20", |
| 52 | confidence: 0.95, |
| 53 | quote: "Bob Li took over as lead of the Orion platform team on 2024-05-20.", |
| 54 | }, |
| 55 | ], |
| 56 | }, |
| 57 | // "team" 不在内置本体白名单 → 抽取端降级 concept(record_miss + 兜底), |
| 58 | // 正是类型漂移的第三条腿 |
| 59 | "E2E-DOC3": { |
| 60 | entities: [ |
| 61 | { name: "Orion platform team", type: "team" }, |
| 62 | { name: "Utopia Labs", type: "organization" }, |
| 63 | ], |
| 64 | facts: [ |
| 65 | { |
| 66 | subject: "Orion platform team", |
| 67 | predicate: "part_of", |
| 68 | object: "Utopia Labs", |
| 69 | confidence: 0.9, |
| 70 | quote: "The Orion platform team is part of Utopia Labs.", |
| 71 | }, |
| 72 | ], |
| 73 | }, |
| 74 | }; |
| 75 | |
| 76 | function mockReply(messages) { |
| 77 | const all = messages.map((m) => m.content).join("\n"); |
| 78 | let payload; |
| 79 | if (all.includes("entity-resolution adjudicator")) { |
| 80 | const pairs = [...all.matchAll(/^Pair (\d+):/gm)].map((m) => Number(m[1])); |
| 81 | payload = { |
| 82 | verdicts: pairs.map((i) => ({ i, verdict: "same", confidence: 0.95 })), |
| 83 | }; |
| 84 | } else { |
| 85 | const marker = Object.keys(EXTRACTIONS).find((k) => all.includes(k)); |
| 86 | payload = marker ? EXTRACTIONS[marker] : { entities: [], facts: [] }; |
| 87 | } |
| 88 | return "```json\n" + JSON.stringify(payload) + "\n```"; |
| 89 | } |
| 90 | |
| 91 | function startMock() { |
| 92 | return new Promise((resolve) => { |
| 93 | const srv = http.createServer((req, res) => { |
| 94 | let body = ""; |
| 95 | req.on("data", (c) => (body += c)); |
| 96 | req.on("end", () => { |
| 97 | if (!req.url.endsWith("/chat/completions")) { |
| 98 | res.writeHead(404).end(); |
| 99 | return; |
| 100 | } |
| 101 | const messages = JSON.parse(body).messages || []; |
| 102 | res.writeHead(200, { "content-type": "application/json" }); |
| 103 | res.end( |
| 104 | JSON.stringify({ |
| 105 | choices: [{ message: { content: mockReply(messages) } }], |
| 106 | }), |
| 107 | ); |
| 108 | }); |
| 109 | }); |
| 110 | srv.listen(MOCK_PORT, "127.0.0.1", () => resolve(srv)); |
| 111 | }); |
| 112 | } |
| 113 | |
| 114 | // --------------------------------------------------------------------------- |
| 115 | // API driver |
| 116 | // --------------------------------------------------------------------------- |
| 117 | |
| 118 | let cookie = ""; |
| 119 | |
| 120 | async function api(method, path, body) { |
| 121 | const res = await fetch(`${BASE}/api/v1${path}`, { |
| 122 | method, |
| 123 | headers: { |
| 124 | "content-type": "application/json", |
| 125 | ...(cookie ? { cookie } : {}), |
| 126 | }, |
| 127 | body: body === undefined ? undefined : JSON.stringify(body), |
| 128 | }); |
| 129 | const setCookie = res.headers.get("set-cookie"); |
| 130 | if (setCookie) cookie = setCookie.split(";")[0]; |
| 131 | const text = await res.text(); |
| 132 | if (!res.ok) throw new Error(`${method} ${path} -> ${res.status}: ${text}`); |
| 133 | return text ? JSON.parse(text) : {}; |
| 134 | } |
| 135 | |
| 136 | const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); |
| 137 | |
| 138 | async function poll(desc, timeoutMs, fn) { |
| 139 | const deadline = Date.now() + timeoutMs; |
| 140 | for (;;) { |
| 141 | const v = await fn(); |
| 142 | if (v !== undefined) return v; |
| 143 | if (Date.now() > deadline) throw new Error(`timeout waiting for: ${desc}`); |
| 144 | await sleep(1500); |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | let failures = 0; |
| 149 | function check(cond, label) { |
| 150 | console.log(`${cond ? "PASS" : "FAIL"}: ${label}`); |
| 151 | if (!cond) failures++; |
| 152 | } |
| 153 | |
| 154 | async function pushDocAndWait(kbId, filename, content) { |
| 155 | await api("POST", `/kbs/${kbId}/ingest`, { filename, content }); |
| 156 | // 逐篇等抽取完成:消解按落库顺序看见前一篇的实体,漂移路径确定性触发 |
| 157 | await poll(`${filename} graph done`, 120000, async () => { |
| 158 | const documents = await api("GET", `/kbs/${kbId}/documents`); |
| 159 | const d = documents.find((d) => d.filename === filename); |
| 160 | if (d && d.graph_status === "failed") throw new Error(`${filename} extraction failed`); |
| 161 | return d && d.graph_status === "done" ? true : undefined; |
| 162 | }); |
| 163 | } |
| 164 | |
| 165 | async function main() { |
| 166 | const mock = await startMock(); |
| 167 | console.log(`mock LLM on 127.0.0.1:${MOCK_PORT}`); |
| 168 | |
| 169 | const stamp = Date.now(); |
| 170 | await api("POST", "/auth/register", { |
| 171 | email: `e2e-drift-${stamp}@test.local`, |
| 172 | password: "password123", |
| 173 | display_name: "Drift E2E", |
| 174 | }); |
| 175 | const wsId = (await api("POST", "/workspaces", { name: `Drift WS ${stamp}` })).id; |
| 176 | const kbId = (await api("POST", `/workspaces/${wsId}/kbs`, { name: "Drift KB" })).id; |
| 177 | |
| 178 | await api("PUT", `/workspaces/${wsId}/settings`, { |
| 179 | chat_base_url: `http://127.0.0.1:${MOCK_PORT}/v1`, |
| 180 | chat_api_key: "mock", |
| 181 | chat_model: "mock-adjudicator", |
| 182 | }); |
| 183 | |
| 184 | await pushDocAndWait(kbId, "orion-org-chart.md", |
| 185 | "[E2E-DOC1] Org chart update. Alice Zhang has led the Orion platform team since 2023-01-15."); |
| 186 | await pushDocAndWait(kbId, "orion-roadmap.md", |
| 187 | "[E2E-DOC2] Roadmap. Bob Li took over as lead of the Orion platform team on 2024-05-20."); |
| 188 | await pushDocAndWait(kbId, "orion-wiki.md", |
| 189 | "[E2E-DOC3] Wiki. The Orion platform team is part of Utopia Labs."); |
| 190 | |
| 191 | // 攒批裁决在后台链式合并:等审核队列清空且同名实体收敛为一个 |
| 192 | const survivor = await poll("adjudication converges to one entity", 90000, async () => { |
| 193 | const review = await api("GET", `/kbs/${kbId}/review`); |
| 194 | const { entities } = await api("GET", `/kbs/${kbId}/entities?q=Orion`); |
| 195 | return review.reviews.length === 0 && entities.length === 1 ? entities[0] : undefined; |
| 196 | }); |
| 197 | |
| 198 | check(survivor.name === "Orion platform team", `survivor name (${survivor.name})`); |
| 199 | check(survivor.type_key !== "concept", |
| 200 | `type reconciled to a specific type, not the concept fallback (${survivor.type_key})`); |
| 201 | check(survivor.disambiguator === null || survivor.disambiguator === undefined, |
| 202 | "no disambiguator once the group collapsed to one entity"); |
| 203 | |
| 204 | const review = await api("GET", `/kbs/${kbId}/review`); |
| 205 | check(review.merges.length >= 2, |
| 206 | `chain merges recorded in entity_merges ledger (${review.merges.length})`); |
| 207 | check(review.merges.every((m) => /auto-merge/.test(m.reason ?? "")), |
| 208 | "merges came from LLM adjudication, not manual action"); |
| 209 | |
| 210 | const { facts } = await api("GET", `/kbs/${kbId}/entities/${survivor.id}`); |
| 211 | const leads = facts.filter((f) => f.predicate_key === "leads" && f.direction === "in"); |
| 212 | check(leads.length === 2, `one coherent leads timeline with 2 live facts (${leads.length})`); |
| 213 | const alice = leads.find((f) => f.other_name === "Alice Zhang"); |
| 214 | const bob = leads.find((f) => f.other_name === "Bob Li"); |
| 215 | check(!!alice && (alice.valid_from ?? "").startsWith("2023-01-15"), |
| 216 | "Alice's tenure starts 2023-01-15"); |
| 217 | check(!!alice && (alice.valid_to ?? "").startsWith("2024-05-20"), |
| 218 | `Alice's tenure auto-closed at Bob's start (valid_to=${alice?.valid_to})`); |
| 219 | check(!!bob && (bob.valid_from ?? "").startsWith("2024-05-20") && bob.valid_to === null, |
| 220 | "Bob's tenure open from 2024-05-20"); |
| 221 | const partOf = facts.find((f) => f.predicate_key === "part_of" && f.direction === "out"); |
| 222 | check(!!partOf && partOf.other_name === "Utopia Labs", |
| 223 | "concept-side fact (part_of Utopia Labs) survived the merge onto the survivor"); |
| 224 | |
| 225 | // 可回滚:撤销最近一次合并 → 被并方复活、类型恢复快照、同名组重新出现 |
| 226 | await api("POST", `/kbs/${kbId}/merges/${review.merges[0].id}/revert`); |
| 227 | const after = await api("GET", `/kbs/${kbId}/entities?q=Orion`); |
| 228 | check(after.entities.length === 2, |
| 229 | `revert revives the merged-away entity (${after.entities.length} entities)`); |
| 230 | const revived = after.entities.find((e) => e.id !== survivor.id); |
| 231 | check(!!revived && revived.type_key !== survivor.type_key, |
| 232 | `revived entity keeps its own original type (${revived?.type_key})`); |
| 233 | const ledger = await api("GET", `/kbs/${kbId}/review`); |
| 234 | check(ledger.merges.some((m) => m.reverted_at !== null), |
| 235 | "ledger marks the merge as reverted"); |
| 236 | |
| 237 | mock.close(); |
| 238 | if (failures > 0) { |
| 239 | console.error(`\n${failures} assertion(s) failed`); |
| 240 | process.exit(1); |
| 241 | } |
| 242 | console.log("\nE2E type-drift: all assertions passed"); |
| 243 | } |
| 244 | |
| 245 | main().catch((e) => { |
| 246 | console.error(`E2E error: ${e.message}`); |
| 247 | process.exit(1); |
| 248 | }); |