/** 数字人核心规则回归:分流域隔离、人群边界、世界书预算、SSE分片和鉴权。 */ import "./digital-env"; import test from "node:test"; import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import assert from "node:assert/strict"; import { bucket, decide, eligible, planValue, activeExperiment, type Experiment, } from "../src/modules/digital/digital.experiments"; import { assemblePrompt, selectLore, } from "../src/modules/digital/digital.prompt"; import { contentSchema, entrySchema, experimentSchema, } from "../src/modules/digital/digital.schema"; import { choosePresetBody, completionDeltas, } from "../src/modules/digital/digital.chat"; import { createApp } from "../src/app"; import { validateTypeValue, normalizePlanValues, type ExperimentType, } from "../src/modules/digital/digital.experiment-types"; const config = experimentSchema.parse({ name: "test", scope: "ui", config: { audience: "all" }, }).config; test("新老用户在注册分界精确互补,指定名单不能混入其他账号", () => { const cutoff = "2026-10-26T00:00:00.000Z"; assert.equal( eligible({ ...config, audience: "new", cutoff }, "employee:1", cutoff), true, ); assert.equal( eligible({ ...config, audience: "existing", cutoff }, "employee:1", cutoff), false, ); assert.equal( eligible( { ...config, audience: "existing", cutoff }, "employee:1", "2026-10-25T23:59:59.999Z", ), true, ); assert.equal( eligible({ ...config, audience: "new" }, "employee:1", cutoff), false, ); assert.equal( eligible( { ...config, audience: "specified", accounts: ["employee:1"] }, "super_admin:1", cutoff, ), false, ); }); test("独立流量和变体哈希在10%流量下仍覆盖两组且稳定", () => { let enrolled = 0, b = 0; for (let i = 0; i < 20000; i++) { const account = `employee:${i}`; const n = bucket("exp", account, "traffic"); assert.equal(n, bucket("exp", account, "traffic")); if (n < 1000) { enrolled++; if (bucket("exp", account, "variant") < 5000) b++; } } assert.ok(enrolled > 1700 && enrolled < 2300); assert.ok(b / enrolled > 0.45 && b / enrolled < 0.55); assert.notEqual( bucket("exp", "employee:1", "variant"), bucket("exp", "super_admin:1", "variant"), ); }); test("世界书按优先级入预算、支持次关键词、扫描深度和禁用", () => { const entries = [ entrySchema.parse({ id: "a", name: "高", keys: ["灯塔"], content: "蓝光", priority: 200, }), entrySchema.parse({ id: "b", name: "低", keys: ["灯塔"], content: "低优先级", priority: 10, }), entrySchema.parse({ id: "c", name: "次词", keys: ["灯塔"], secondaryKeys: ["口令"], content: "秘密", priority: 500, }), entrySchema.parse({ id: "d", name: "禁用", constant: true, content: "不要出现", enabled: false, }), ]; assert.deepEqual( selectLore(entries, [{ role: "user", content: "灯塔" }], 3).map( (v) => v.id, ), ["a"], ); assert.deepEqual( selectLore(entries, [{ role: "user", content: "灯塔口令" }], 4).map( (v) => v.id, ), ["c", "a"], ); const recent = entrySchema.parse({ id: "last", name: "近期", keys: ["灯塔"], content: "x", scanDepth: 1, }); assert.equal( selectLore( [recent], [ { role: "user", content: "灯塔" }, { role: "assistant", content: "你好" }, ], 100, ).length, 0, ); }); test("超长角色不能突破上下文预算,最新用户输入保留", () => { const card = { ...contentSchema.shape.body.parse({ cover: "", description: "角".repeat(12000), personality: "人".repeat(12000), }), name: "角色", }; const preset = contentSchema.shape.body.parse({ cover: "", contextBudget: 6000, }); const latest = "用".repeat(4000); const result = assemblePrompt( card, preset, [], [{ role: "user", content: latest }], { persona: "", userName: "旅人", memory: "" }, [], ); assert.ok(result.characters <= 6000); assert.equal(result.messages.at(-1)?.content, latest); }); test("SSE中文跨字节分片仍只返回正文,不转发思考内容", async () => { const raw = new TextEncoder().encode( 'data: {"choices":[{"delta":{"reasoning_content":"hidden"}}]}\n\ndata: {"choices":[{"delta":{"content":"你好🌙"}}]}\n\ndata: [DONE]\n\n', ); const stream = new ReadableStream({ start(c) { for (let i = 0; i < raw.length; i += 3) c.enqueue(raw.slice(i, i + 3)); c.close(); }, }); let text = ""; for await (const delta of completionDeltas(stream)) text += delta; assert.equal(text, "你好🌙"); }); test("数字人及后台接口不接受匿名请求", async () => { const app = createApp(); try { for (const url of [ "/api/digital/bootstrap", "/api/digital/conversations/unit-conversation/style-policy", "/api/digital/decisions/ui", "/api/digital/conversations", "/api/digital-admin/content", "/api/digital-admin/experiments", "/api/digital-admin/experiment-types", "/api/digital-admin/experiment-users", ]) { const r = await app.inject({ method: "GET", url }); assert.equal(r.statusCode, 401, url); } } finally { await app.close(); } }); test("上游未发送完成标记的断流不得误报成功", async () => { const raw = new TextEncoder().encode( 'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n', ); const stream = new ReadableStream({ start(c) { c.enqueue(raw); c.close(); }, }); await assert.rejects(async () => { for await (const _ of completionDeltas(stream)) { } }, /before completion/); }); test("预设进入系统提示,共用前言保持中性并尊重边界", () => { const body = contentSchema.shape.body.parse({ cover: "", systemPrompt: "亲密直写标记", age: 24, }); const result = assemblePrompt( { ...body, name: "角色" }, body, [], [{ role: "user", content: "继续" }], { persona: "", userName: "旅人", memory: "" }, [], ); const system = result.messages[0]?.content ?? ""; assert.equal(system.includes("身份都视为已满18岁"), false); assert.match(system, /未成年人/); assert.match(system, /亲密直写标记/); assert.match(system, /尊重边界/); assert.equal(system.includes("不要说教、淡出或突然中断"), false); }); test("下架预设回退到角色默认,两者都没有时用内置写法", () => { const base = contentSchema.shape.body.parse({ cover: "", systemPrompt: "内置", }); const selected = contentSchema.shape.body.parse({ cover: "", systemPrompt: "亲密直写", }); const characterDefault = contentSchema.shape.body.parse({ cover: "", systemPrompt: "角色默认", }); assert.equal( choosePresetBody(selected, characterDefault, base).systemPrompt, "亲密直写", ); assert.equal( choosePresetBody(null, characterDefault, base).systemPrompt, "角色默认", ); assert.equal(choosePresetBody(null, null, base).systemPrompt, "内置"); }); test("角色输入拒绝未成年和前台外部执行资源", () => { assert.throws(() => contentSchema.parse({ kind: "character", name: "test", body: { cover: "", age: 17 }, }), ); assert.throws(() => contentSchema.parse({ kind: "character", name: "test", body: { cover: "javascript:alert(1)" }, }), ); const parsed = contentSchema.parse({ kind: "character", name: "test", body: { cover: "", experimentVariant: "B" }, }); assert.equal("experimentVariant" in parsed.body, false); }); test("用户消息中的占位符保持原样,避免内容意外膨胀或被改写", () => { const body = contentSchema.shape.body.parse({ cover: "" }); const latest = "{{user}}".repeat(500); const result = assemblePrompt( { ...body, name: "角色" }, body, [], [{ role: "user", content: latest }], { persona: "", userName: "名".repeat(60), memory: "" }, [], ); assert.equal(result.messages.at(-1)?.content, latest); assert.ok(result.characters <= body.contextBudget); }); test("空正文增量不触发前台打字", async () => { const raw = new TextEncoder().encode( 'data: {"choices":[{"delta":{"content":""}}]}\n\ndata: [DONE]\n\n', ); const stream = new ReadableStream({ start(c) { c.enqueue(raw); c.close(); }, }); const chunks = []; for await (const text of completionDeltas(stream)) chunks.push(text); assert.deepEqual(chunks, []); }); test("员工即使持有旧管理员权限声明,也不能进入数字人运营接口", async () => { const { authService } = await import("../src/modules/auth/auth.service"); const original = authService.getCurrentUser; authService.getCurrentUser = async () => ({ id: 99, username: "unit", displayName: "unit", accountType: "EMPLOYEE", roles: [], permissions: ["*"], canManage: true, }); const app = createApp(); try { await app.ready(); const token = app.jwt.sign({ sub: "employee:99", employeeId: 99, accountType: "EMPLOYEE", scene: "EMPLOYEE_APP", username: "unit", roleCodes: ["admin"], permissions: ["*"], canManage: true, }); for (const url of [ "/api/digital-admin/content", "/api/digital-admin/experiments", "/api/digital-admin/experiment-types", "/api/digital-admin/experiment-users", ]) assert.equal( ( await app.inject({ method: "GET", url, headers: { authorization: `Bearer ${token}` }, }) ).statusCode, 403, ); } finally { authService.getCurrentUser = original; await app.close(); } }); test("自定义场景按应用接入点生效,停用场景不再参与决策", async () => { const { activeExperiment } = await import( "../src/modules/digital/digital.experiments" ); const custom = { id: "e1", scope: "my-ui-scene", runtime: "ui", sceneEnabled: 1, state: "running", }; const disabled = { ...custom, id: "e2", scope: "disabled-scene", sceneEnabled: 0, }; const chat = { ...custom, id: "e3", runtime: "chat" }; const list = [disabled, chat, custom] as Parameters< typeof activeExperiment >[0]; assert.equal(activeExperiment(list, "ui")?.id, "e1"); assert.equal(activeExperiment(list, "chat")?.id, "e3"); assert.equal( activeExperiment( [disabled] as Parameters[0], "ui", ), undefined, ); }); test("类型数据契约保留 false、0、null,拒绝错误格式和非 JSON 数据", () => { for (const [kind, value] of [ ["boolean", false], ["number", 0], ["json", null], ["json", { a: false, b: 0 }], ["string", ""], ] as const) assert.doesNotThrow(() => validateTypeValue(kind, value)); for (const [kind, value] of [ ["boolean", "false"], ["number", "0"], ["number", Infinity], ["string", {}], ["json", undefined], ["json", { a: NaN }], ["json", "x".repeat(25000)], ] as const) assert.throws(() => validateTypeValue(kind, value)); }); test("自定义 A/B 值按注册契约验证,旧 UI 值和预设合同保持兼容", () => { const t = { valueType: "boolean", contract: {} } as ExperimentType; assert.deepEqual( normalizePlanValues(t, { values: { A: false, B: true } }).values, { A: false, B: true }, ); assert.throws(() => normalizePlanValues(t, {})); assert.throws(() => normalizePlanValues(t, { values: { A: "false", B: true } }), ); const ui = { ...t, valueType: "string", contract: { fixedValues: { A: "old", B: "new" } }, } as ExperimentType; assert.deepEqual( normalizePlanValues(ui, { values: { A: "malicious", B: "other" } }).values, { A: "old", B: "new" }, ); const chat = { ...ui, contract: { optionsSource: "presets" } }; assert.equal( normalizePlanValues(chat, { presetA: "one", presetB: "two" }).presetA, "one", ); const plan = { config: { values: { A: false, B: 0 } }, consumerKey: "custom", } as unknown as Experiment; assert.equal(planValue(plan, "A", "fallback"), false); assert.equal(planValue(plan, "B", "fallback"), 0); }); test("独立新类型不会共享分流;历史同消费者别名仍互斥选择", () => { const e = (id: string, consumerKey: string, state: Experiment["state"]) => ({ id, scope: id, consumerKey, state, sceneEnabled: 1 }) as Experiment; const list = [ e("draft", "one", "draft"), e("a", "one", "running"), e("b", "two", "running"), ]; assert.equal(activeExperiment(list, "one")?.id, "a"); assert.equal(activeExperiment(list, "two")?.id, "b"); assert.equal(activeExperiment(list, "missing"), undefined); assert.equal( activeExperiment( [e("ended", "one", "finished"), e("alias", "one", "paused")], "one", )?.id, "alias", ); }); test("新增预设的数据库迁移与初始化种子保持同一数据契约", () => { const seed = JSON.parse( readFileSync(resolve("data/digital-seed.json"), "utf8"), ) as Array<{ id: string; kind: string; name: string; status: string; body: unknown; }>; const record = seed.find((v) => v.id === "preset-intimate"); assert.ok(record); const sql = readFileSync( resolve("migrations/015_seed_intimate_preset.sql"), "utf8", ); const fields = Array.from(sql.matchAll(/0x([0-9a-f]+)/gi), (m) => Buffer.from(m[1], "hex").toString("utf8"), ); assert.deepEqual(fields.slice(0, 4), [ record.id, record.kind, record.name, record.status, ]); assert.deepEqual(JSON.parse(fields[4]), record.body); assert.equal(contentSchema.safeParse(record).success, true); assert.ok(/INSERT IGNORE/.test(sql)); }); test("空白实验注册表保持为空,应用默认决策不创建类型或伪造接入", async (t) => { const { pool } = await import("../src/db/pool"); const { experimentTypes } = await import("../src/modules/digital/digital.experiment-types"); const queries: string[] = []; t.mock.method(pool, "query", async (options: { sql: string }) => { queries.push(options.sql); assert.match(options.sql, /^SELECT .* FROM dh_scenes /); return [[], []]; }); assert.deepEqual(await experimentTypes(), []); for (const [key, value] of [["ui", "old"], ["chat", ""], ["custom", false]] as const) { const d = await decide("employee:1", key, { value }); assert.equal(d.value, value); assert.equal(d.typeRevision, 0); assert.equal(d.reason, "default"); assert.equal(d.decisionId, null); assert.equal(d.experimentId, null); assert.equal(d.presetId, undefined); } await assert.rejects(decide("employee:1", "missing"), (e: unknown) => !!e && typeof e === "object" && "statusCode" in e && e.statusCode === 404); assert.equal(queries.length, 5); }); test("应用未配置实验的默认行为不能吞掉数据库故障", async (t) => { const { pool } = await import("../src/db/pool"); t.mock.method(pool, "query", async () => { throw new Error("database unavailable"); }); await assert.rejects(decide("employee:1", "ui", { value: "old" }), /database unavailable/); }); test("空白实验系统仍能启动前台,且不为默认界面写入实验记录", async (t) => { const { pool } = await import("../src/db/pool"); const { authService } = await import("../src/modules/auth/auth.service"); t.mock.method(authService, "getCurrentUser", async () => ({ accountType: "EMPLOYEE" })); t.mock.method(pool, "query", async (options: { sql: string }) => { assert.match(options.sql, /^SELECT .* FROM (dh_scenes|dh_content|dh_profiles) /); return [[], []]; }); const app = createApp(); try { await app.ready(); const token = app.jwt.sign({ sub: "employee:1", accountType: "EMPLOYEE" }); const result = await app.inject({ method: "GET", url: "/api/digital/bootstrap", headers: { authorization: `Bearer ${token}` }, }); assert.equal(result.statusCode, 200); const data = result.json().data; assert.deepEqual(data.catalog, []); assert.equal(data.decision.variant, "A"); assert.equal(data.decision.experimentId, null); assert.equal(data.decision.decisionId, null); } finally { await app.close(); } });