Files
mnote/scripts/task538-knowledge-rag-source-scope-api-smoke.js
T
lix-2026 9551d4c1dc feat(rag): harden post-LightRAG runtime
Retire legacy OCR/media/evidence fallbacks, add local-folder event bus and Page Aggregate guards, and archive completed design checklists.

Validation: cargo test -p mnote-web -- --test-threads=1; cargo test --workspace -- --test-threads=1; git diff --check; codegraph sync .; codegraph_status.
2026-06-07 10:35:21 +08:00

189 lines
7.7 KiB
JavaScript

#!/usr/bin/env node
"use strict";
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { request } = require("playwright");
const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const ROOT_PATH = process.env.MNOTE_KNOWLEDGE_RAG_ROOT_PATH || "/mnt/Data1T/Mnote_data/users/mnote-e2e/workspaces/my-space";
const ROOT_URI = process.env.MNOTE_KNOWLEDGE_RAG_ROOT_URI || `file://${ROOT_PATH}`;
const WORKSPACE_ID = process.env.MNOTE_KNOWLEDGE_RAG_WORKSPACE_ID || "local-ws:mnote-e2e:my-space";
const FIXTURE_DIR = "knowledge-rag-fixtures-7-50";
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task538-knowledge-rag-source-scope-api-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const POLL_TIMEOUT_MS = Number(process.env.MNOTE_KNOWLEDGE_RAG_SCOPE_TIMEOUT_MS || 240_000);
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function apiJson(context, method, url, data) {
const response = await context.fetch(url, {
method,
data,
headers: {
"x-mnote-actor-id": "mnote-e2e",
"x-mnote-actor-type": "user",
"x-mnote-workspace-id": WORKSPACE_ID,
accept: "application/json",
},
timeout: UI_TIMEOUT_MS,
});
const text = await response.text();
let payload = null;
try {
payload = text ? JSON.parse(text) : null;
} catch (_) {
payload = { rawText: text };
}
return { ok: response.ok(), status: response.status(), payload, text };
}
async function signIn(context) {
const response = await context.post(`${BASE_URL}/api/auth`, {
data: {
action: "auth:signIn",
args: {
provider: "password",
params: {
email: "mnote.e2e@example.com",
password: process.env.MNOTE_E2E_PASSWORD || "MnoteE2E123!",
flow: "signIn",
},
},
},
timeout: UI_TIMEOUT_MS,
});
assert(response.ok(), `登录失败: ${response.status()} ${await response.text()}`);
}
async function status(context) {
const params = new URLSearchParams({ rootUri: ROOT_URI, workspaceId: WORKSPACE_ID });
const result = await apiJson(context, "GET", `${BASE_URL}/api/knowledge-rag/status?${params.toString()}`);
assert(result.ok, `knowledge-rag status 失败: ${result.status} ${result.text.slice(0, 1000)}`);
return result.payload;
}
function entryFor(statusPayload, sourcePath) {
const entries = statusPayload?.registry?.entries;
return Array.isArray(entries) ? entries.find((entry) => entry.sourceRootRelativePath === sourcePath) : null;
}
async function waitForIndexed(context, sourcePaths) {
const startedAt = Date.now();
let lastStatus = null;
while (Date.now() - startedAt < POLL_TIMEOUT_MS) {
lastStatus = await status(context);
const allIndexed = sourcePaths.every((sourcePath) => {
const entry = entryFor(lastStatus, sourcePath);
return entry && entry.indexedAtMs && entry.lightRagDocId && !entry.stale && !entry.deletedAtMs;
});
if (allIndexed) return lastStatus;
await sleep(5_000);
}
throw new Error(`等待 source scope fixture 入库超时: ${JSON.stringify({ sourcePaths, lastStatus }, null, 2).slice(0, 4000)}`);
}
async function ingest(context, sourcePaths) {
const result = await apiJson(context, "POST", `${BASE_URL}/api/knowledge-rag/ingest`, {
rootUri: ROOT_URI,
workspaceId: WORKSPACE_ID,
sources: sourcePaths.map((sourcePath) => ({ sourcePath })),
});
assert(result.ok, `knowledge-rag ingest 失败: ${result.status} ${result.text.slice(0, 1000)}`);
return result.payload;
}
async function query(context, queryText, sourcePaths) {
const result = await apiJson(context, "POST", `${BASE_URL}/api/knowledge-rag/query`, {
rootUri: ROOT_URI,
workspaceId: WORKSPACE_ID,
query: queryText,
mode: "mix",
topK: 12,
chunkTopK: 12,
includeChunkContent: true,
sourcePaths,
});
assert(result.ok, `knowledge-rag query 失败: ${result.status} ${result.text.slice(0, 1000)}`);
return result.payload;
}
async function deleteSource(context, sourcePath) {
const result = await apiJson(context, "POST", `${BASE_URL}/api/knowledge-rag/delete-source`, {
rootUri: ROOT_URI,
workspaceId: WORKSPACE_ID,
sourcePath,
});
assert(result.ok, `knowledge-rag delete-source 失败: ${result.status} ${result.text.slice(0, 1000)}`);
return result.payload;
}
async function main() {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
fs.mkdirSync(path.join(ROOT_PATH, FIXTURE_DIR), { recursive: true });
const marker = `SOURCE SCOPE API RAG ${Date.now()}`;
const sourceA = `${FIXTURE_DIR}/scope-api-alpha-${Date.now()}.md`;
const sourceB = `${FIXTURE_DIR}/scope-api-beta-${Date.now()}.md`;
fs.writeFileSync(path.join(ROOT_PATH, sourceA), `# Scope API Alpha\n${marker}\nOnly alpha source should remain after API scope filter.\n`, "utf8");
fs.writeFileSync(path.join(ROOT_PATH, sourceB), `# Scope API Beta\n${marker}\nBeta source must be filtered when sourcePaths targets alpha.\n`, "utf8");
const context = await request.newContext({ baseURL: BASE_URL });
try {
await signIn(context);
await ingest(context, [sourceA, sourceB]);
const indexedStatus = await waitForIndexed(context, [sourceA, sourceB]);
const scoped = await query(context, marker, [sourceA]);
const references = Array.isArray(scoped.references) ? scoped.references : [];
assert.equal(scoped.sourceScopeMode, "post_filter_mapped_references", `sourceScopeMode 不正确: ${JSON.stringify(scoped, null, 2).slice(0, 3000)}`);
assert.equal(scoped.rawScopeFiltered, false, `rawScopeFiltered 应为 false: ${JSON.stringify(scoped, null, 2).slice(0, 3000)}`);
assert(references.length > 0, `sourcePaths scope 应至少返回 alpha: ${JSON.stringify(scoped, null, 2).slice(0, 3000)}`);
assert(
references.every((reference) => reference.sourceRootRelativePath === sourceA),
`sourcePaths scope 不应返回非 alpha 来源: ${JSON.stringify(references, null, 2).slice(0, 3000)}`,
);
assert(scoped.raw, "HTTP API 仍应保留 raw 供调试调用方使用");
await deleteSource(context, sourceA);
assert(fs.existsSync(path.join(ROOT_PATH, sourceA)), "delete-source 不应删除用户原始 source 文件");
const afterDelete = await query(context, marker, [sourceA]);
const afterReferences = Array.isArray(afterDelete.references) ? afterDelete.references : [];
assert.equal(afterReferences.length, 0, `删除索引后 source-scoped query 不应继续返回 alpha: ${JSON.stringify(afterReferences, null, 2)}`);
const result = {
ok: true,
baseUrl: BASE_URL,
rootUri: ROOT_URI,
workspaceId: WORKSPACE_ID,
marker,
sourceA,
sourceB,
sourceScopeMode: scoped.sourceScopeMode,
rawScopeFiltered: scoped.rawScopeFiltered,
scopedReferenceCount: references.length,
alphaDocId: entryFor(indexedStatus, sourceA)?.lightRagDocId || null,
betaDocId: entryFor(indexedStatus, sourceB)?.lightRagDocId || null,
sourceAExistsAfterDelete: fs.existsSync(path.join(ROOT_PATH, sourceA)),
afterDeleteReferenceCount: afterReferences.length,
};
fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
console.log(JSON.stringify(result, null, 2));
} finally {
await context.dispose().catch(() => undefined);
}
}
main().catch((error) => {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
fs.writeFileSync(
path.join(OUTPUT_DIR, "failure.json"),
`${JSON.stringify({ ok: false, error: error.stack || error.message || String(error) }, null, 2)}\n`,
"utf8",
);
console.error(error.stack || error.message || String(error));
process.exit(1);
});