dsh-uitest 2.3.1 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -11
- package/bin/uitest.mjs +189 -11
- package/client.js +81 -11
- package/host/agent-bridge.mjs +9 -2
- package/host/agent-test.mjs +1 -1
- package/host/context-budget.mjs +1 -1
- package/index.js +14 -2
- package/lib/agent-session.mjs +81 -3
- package/lib/agent-tasks.mjs +212 -0
- package/lib/batch.mjs +204 -13
- package/lib/browser-ab.mjs +21 -6
- package/lib/browser.mjs +5 -5
- package/lib/config.mjs +1 -0
- package/lib/convert.mjs +178 -40
- package/lib/doc-structure.mjs +316 -0
- package/lib/flow.mjs +49 -14
- package/lib/knowledge-central-episodes.mjs +120 -0
- package/lib/knowledge-central-import.mjs +16 -1
- package/lib/knowledge-central.mjs +149 -22
- package/lib/knowledge-clean.mjs +749 -0
- package/lib/knowledge-consolidate.mjs +1271 -0
- package/lib/knowledge-coverage.mjs +150 -0
- package/lib/knowledge-docs.mjs +3 -3
- package/lib/knowledge-effect.mjs +148 -0
- package/lib/knowledge-facts.mjs +1008 -0
- package/lib/knowledge-maintain.mjs +185 -0
- package/lib/knowledge-permission.mjs +447 -0
- package/lib/knowledge-query.mjs +304 -26
- package/lib/knowledge-store.mjs +169 -14
- package/lib/knowledge-summarize.mjs +332 -0
- package/lib/knowledge.mjs +944 -47
- package/lib/learn-run.mjs +157 -51
- package/lib/run-learn.mjs +34 -0
- package/lib/run-observe.mjs +95 -27
- package/lib/run-stats.mjs +71 -0
- package/package.json +12 -2
- package/scripts/knowledge-central-purge.mjs +248 -0
- package/scripts/knowledge-central-sync.mjs +102 -20
- package/scripts/knowledge-consolidate.mjs +158 -0
- package/scripts/knowledge-coverage.mjs +94 -0
- package/scripts/knowledge-effect.mjs +82 -0
- package/scripts/knowledge-permission-probe.mjs +196 -0
- package/scripts/knowledge-permission-report.mjs +140 -0
- package/scripts/knowledge-report.mjs +492 -0
- package/scripts/knowledge-summarize.mjs +200 -0
- package/skills/uitest/SKILL.md +4 -2
- package/skills/uitest/references/convert-knowledge.md +66 -13
- package/studio/host.mjs +120 -3
- package/studio/knowledge.mjs +195 -45
- package/studio/snapshot.mjs +6 -1
package/lib/flow.mjs
CHANGED
|
@@ -23,12 +23,20 @@ import {
|
|
|
23
23
|
import * as pwDriver from './browser.mjs';
|
|
24
24
|
import * as abDriver from './browser-ab.mjs';
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
/** 显式配置 > 环境变量 > agent-browser;batch/studio/agent-session 都用同一个默认。 */
|
|
27
|
+
export function resolveDriverName(config = {}, env = process.env) {
|
|
28
|
+
return String((config.browser && config.browser.driver) || env.UITEST_DRIVER || 'agent-browser').toLowerCase();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const driverFor = (config) => (resolveDriverName(config) === 'playwright' ? pwDriver : abDriver);
|
|
27
32
|
|
|
28
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* agent 判断步骤:有宿主判断器时由它给 ok/note。
|
|
35
|
+
* CLI 没有判断器时标记 skipped,保留位置和说明,不把"没验证"伪造成通过。
|
|
36
|
+
*/
|
|
29
37
|
async function runAgentStep(actionCtx, step) {
|
|
30
38
|
if (typeof actionCtx.agentStep !== 'function') {
|
|
31
|
-
|
|
39
|
+
return { skipped: true, reason: 'agent 判断步骤没有宿主判断器,本次未验证' };
|
|
32
40
|
}
|
|
33
41
|
const result = await actionCtx.agentStep(step, actionCtx);
|
|
34
42
|
if (!result || typeof result !== 'object') {
|
|
@@ -45,7 +53,7 @@ async function runAgentStep(actionCtx, step) {
|
|
|
45
53
|
import { createLiveView } from './live-view.mjs';
|
|
46
54
|
import { validatePreconditionFlow } from './preconditions.mjs';
|
|
47
55
|
import { createPageObserver } from './run-observe.mjs';
|
|
48
|
-
import {
|
|
56
|
+
import { learnRun } from './run-learn.mjs';
|
|
49
57
|
|
|
50
58
|
/* ------------------------------------------------------------------ */
|
|
51
59
|
/* flow 定位与校验 */
|
|
@@ -458,6 +466,7 @@ export async function runFlow(options = {}) {
|
|
|
458
466
|
|
|
459
467
|
const steps = [];
|
|
460
468
|
const failedSteps = [];
|
|
469
|
+
const skippedSteps = [];
|
|
461
470
|
let aborted = false;
|
|
462
471
|
let loginReused = null;
|
|
463
472
|
let session = providedSession || null;
|
|
@@ -671,12 +680,17 @@ export async function runFlow(options = {}) {
|
|
|
671
680
|
const data = step.action === 'agent'
|
|
672
681
|
? await runAgentStep(actionCtx, step)
|
|
673
682
|
: await driver.performAction(session.page, step, actionCtx);
|
|
683
|
+
if (data && typeof data === 'object' && data.skipped === true) {
|
|
684
|
+
status = 'skipped';
|
|
685
|
+
skippedSteps.push({ id: stepId, action: stepAction, reason: String(data.reason || '') });
|
|
686
|
+
log.warn(`步骤 ${stepId} 跳过:${data.reason}`);
|
|
687
|
+
}
|
|
674
688
|
if (step.action === 'login' && data && typeof data.reused === 'boolean') {
|
|
675
689
|
loginReused = data.reused;
|
|
676
690
|
stepLoginReused = data.reused;
|
|
677
691
|
log.info(data.reused ? '复用已有登录态(storageState 有效)' : '已执行登录并更新 storageState');
|
|
678
692
|
}
|
|
679
|
-
if (step.store) {
|
|
693
|
+
if (step.store && !(data && typeof data === 'object' && data.skipped === true)) {
|
|
680
694
|
storedValue = pickStoredValue(data);
|
|
681
695
|
vars[step.store] = storedValue;
|
|
682
696
|
}
|
|
@@ -718,6 +732,7 @@ export async function runFlow(options = {}) {
|
|
|
718
732
|
action: stepAction,
|
|
719
733
|
message: truncate(lastError.message, 600),
|
|
720
734
|
screenshot: failedRel,
|
|
735
|
+
soft: Boolean(step.continueOnFail),
|
|
721
736
|
...(lastError.detail ? { detail: lastError.detail } : {}),
|
|
722
737
|
});
|
|
723
738
|
detail = safeDetail({
|
|
@@ -737,6 +752,7 @@ export async function runFlow(options = {}) {
|
|
|
737
752
|
durationMs: Date.now() - startMs,
|
|
738
753
|
detail,
|
|
739
754
|
screenshot,
|
|
755
|
+
...(step.continueOnFail ? { continueOnFail: true } : {}),
|
|
740
756
|
...(failureScreenshot ? { failureScreenshot } : {}),
|
|
741
757
|
vars: safeVarSnapshot(vars),
|
|
742
758
|
...(step.shot || stepAction === 'screenshot' || step.key || rawStep.key ? { keyShot: true } : {}),
|
|
@@ -779,7 +795,10 @@ export async function runFlow(options = {}) {
|
|
|
779
795
|
const endedAt = new Date();
|
|
780
796
|
const endedAtIso = nowIso(endedAt);
|
|
781
797
|
const failedCount = failedSteps.length;
|
|
782
|
-
|
|
798
|
+
// continueOnFail 的断言只记警告,不改变运行结论;硬失败才判定 failed。
|
|
799
|
+
const softFailedCount = failedSteps.filter((step) => step.soft).length;
|
|
800
|
+
const hardFailedCount = failedCount - softFailedCount;
|
|
801
|
+
const runStatus = hardFailedCount === 0 && !setupError ? 'passed' : 'failed';
|
|
783
802
|
const finalRecord = {
|
|
784
803
|
...runRecord,
|
|
785
804
|
flow: flow.name || runLabel,
|
|
@@ -810,6 +829,10 @@ export async function runFlow(options = {}) {
|
|
|
810
829
|
executed: steps.length,
|
|
811
830
|
passed: steps.filter((step) => step.status === 'passed').length,
|
|
812
831
|
failed: failedCount,
|
|
832
|
+
hardFailed: hardFailedCount,
|
|
833
|
+
softFailed: softFailedCount,
|
|
834
|
+
skipped: skippedSteps.length,
|
|
835
|
+
assertions: flow.steps.filter((step) => step.action === 'expect' || step.action === 'assert').length,
|
|
813
836
|
aborted,
|
|
814
837
|
},
|
|
815
838
|
};
|
|
@@ -819,25 +842,34 @@ export async function runFlow(options = {}) {
|
|
|
819
842
|
}
|
|
820
843
|
writeRunRecord(runJsonPath, finalRecord);
|
|
821
844
|
|
|
822
|
-
//
|
|
845
|
+
// 运行结束后自动沉淀页面观察、等待、失败建议与耗时;失败只写 learnError + warning,不阻塞/不改变运行结果
|
|
823
846
|
let learnResult = null;
|
|
824
847
|
let learnError = null;
|
|
825
848
|
if (learnAfterRun) {
|
|
826
849
|
try {
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
runDir:
|
|
830
|
-
pagesAdded:
|
|
831
|
-
pagesMerged:
|
|
832
|
-
actionsAdded:
|
|
833
|
-
observations:
|
|
850
|
+
const learned = learnRun(config, { runDir, logger: log });
|
|
851
|
+
learnResult = {
|
|
852
|
+
runDir: learned.observations?.runDir || learned.timing?.runDir || runDir,
|
|
853
|
+
pagesAdded: learned.observations?.pagesAdded || 0,
|
|
854
|
+
pagesMerged: learned.observations?.pagesMerged || 0,
|
|
855
|
+
actionsAdded: learned.observations?.actionsAdded || 0,
|
|
856
|
+
observations: learned.observations?.observations || 0,
|
|
857
|
+
waitsUpdated: learned.timing?.updatedPages?.length || 0,
|
|
858
|
+
suggestions: learned.timing?.suggestions?.length || 0,
|
|
859
|
+
learnings: learned.timing?.learnings?.length || 0,
|
|
834
860
|
at: nowIso(),
|
|
835
861
|
};
|
|
862
|
+
if (learned.errors.length) {
|
|
863
|
+
learnError = learned.errors.map((item) => `${item.stage}: ${item.message}`).join(';');
|
|
864
|
+
finalRecord.learnError = learnError;
|
|
865
|
+
log.warn(`自动学习部分失败(不影响运行结果):${learnError}`);
|
|
866
|
+
}
|
|
836
867
|
} catch (err) {
|
|
837
868
|
learnError = truncate(err.message, 500);
|
|
838
869
|
finalRecord.learnError = learnError;
|
|
839
870
|
log.warn(`自动学习失败(不影响运行结果):${learnError}`);
|
|
840
871
|
}
|
|
872
|
+
if (learnResult) finalRecord.learn = learnResult;
|
|
841
873
|
writeRunRecord(runJsonPath, finalRecord);
|
|
842
874
|
}
|
|
843
875
|
|
|
@@ -852,6 +884,8 @@ export async function runFlow(options = {}) {
|
|
|
852
884
|
runDir,
|
|
853
885
|
runJsonPath,
|
|
854
886
|
failedSteps,
|
|
887
|
+
skippedSteps,
|
|
888
|
+
skipped: skippedSteps.length,
|
|
855
889
|
live: finalRecord.live,
|
|
856
890
|
setup: finalRecord.setup || [],
|
|
857
891
|
setupFailed,
|
|
@@ -860,6 +894,7 @@ export async function runFlow(options = {}) {
|
|
|
860
894
|
vars,
|
|
861
895
|
loginReused,
|
|
862
896
|
pages: run.pages,
|
|
897
|
+
assertions: finalRecord.summary.assertions,
|
|
863
898
|
learn: finalRecord.learn || null,
|
|
864
899
|
learnError,
|
|
865
900
|
flow: run.flow,
|
|
@@ -4,6 +4,18 @@ import { categorySourceTag } from './knowledge-categories.mjs';
|
|
|
4
4
|
|
|
5
5
|
export const PAGE_EPISODE_SOURCE = 'uitest page knowledge · ' + categorySourceTag('page');
|
|
6
6
|
export const PROCESS_EPISODE_SOURCE = 'uitest process knowledge · ' + categorySourceTag('operation');
|
|
7
|
+
export const FLOW_EPISODE_SOURCE = 'uitest flow knowledge · ' + categorySourceTag('business-flow');
|
|
8
|
+
export const DOCUMENT_EPISODE_SOURCE = 'uitest document knowledge';
|
|
9
|
+
export const SYSTEM_EPISODE_SOURCE = 'uitest system knowledge · ' + categorySourceTag('business-flow');
|
|
10
|
+
export const EXPERIENCE_EPISODE_SOURCE = 'uitest experience evidence · ' + categorySourceTag('operation');
|
|
11
|
+
export const FACT_EPISODE_SOURCE = 'uitest canonical fact · ' + categorySourceTag('business-flow');
|
|
12
|
+
export const PERMISSION_FACT_EPISODE_SOURCE = 'uitest permission fact · ' + categorySourceTag('business-flow');
|
|
13
|
+
|
|
14
|
+
/** 文档结构 Episode 的来源描述:有状态/流转时归单据流转,否则归业务流程。 */
|
|
15
|
+
export function documentEpisodeSource(document) {
|
|
16
|
+
const category = (document?.statuses || []).length || (document?.transitions || []).length ? 'document-flow' : 'business-flow';
|
|
17
|
+
return DOCUMENT_EPISODE_SOURCE + ' · ' + categorySourceTag(category);
|
|
18
|
+
}
|
|
7
19
|
|
|
8
20
|
export function pageEpisodeBody(page) {
|
|
9
21
|
return {
|
|
@@ -11,6 +23,7 @@ export function pageEpisodeBody(page) {
|
|
|
11
23
|
category: 'page',
|
|
12
24
|
id: page?.id || '',
|
|
13
25
|
title: page?.title || '',
|
|
26
|
+
summary: page?.summary || '',
|
|
14
27
|
urlName: page?.urlName || '',
|
|
15
28
|
url: page?.url || '',
|
|
16
29
|
tableHeaders: (page?.table?.headers || []).slice(0, 30),
|
|
@@ -34,9 +47,116 @@ export function processEpisodeBody(process) {
|
|
|
34
47
|
id: process?.id || '',
|
|
35
48
|
caseId: process?.caseId || '',
|
|
36
49
|
name: process?.name || '',
|
|
50
|
+
summary: process?.summary || '',
|
|
37
51
|
steps: (process?.steps || []).slice(0, 40),
|
|
38
52
|
notes: (process?.notes || []).slice(-20),
|
|
39
53
|
corrections: (process?.corrections || []).slice(-20),
|
|
40
54
|
reviews: (process?.reviews || []).slice(-10),
|
|
41
55
|
};
|
|
42
56
|
}
|
|
57
|
+
|
|
58
|
+
/** 系统级知识:菜单、URL、角色、权限、术语,一页承载整个系统的稳定事实。 */
|
|
59
|
+
export function systemEpisodeBody(system) {
|
|
60
|
+
return {
|
|
61
|
+
type: 'system',
|
|
62
|
+
category: 'business-flow',
|
|
63
|
+
name: system?.system || system?.name || '系统',
|
|
64
|
+
summary: system?.summary || '',
|
|
65
|
+
baseUrl: system?.baseUrl || '',
|
|
66
|
+
menus: system?.menus || {},
|
|
67
|
+
urls: system?.urls || {},
|
|
68
|
+
notes: (system?.notes || []).slice(-20),
|
|
69
|
+
roles: (system?.roles || []).slice(0, 80),
|
|
70
|
+
permissions: (system?.permissions || []).slice(0, 120),
|
|
71
|
+
glossary: (system?.glossary || []).slice(0, 200),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 执行经验:页面备注/人工反馈/用例过程,只进证据组,供同用例/同页面查询。 */
|
|
76
|
+
export function experienceEpisodeBody(experience) {
|
|
77
|
+
return {
|
|
78
|
+
type: 'experience',
|
|
79
|
+
category: 'operation',
|
|
80
|
+
id: experience?.id || '',
|
|
81
|
+
kind: experience?.kind || '',
|
|
82
|
+
caseId: experience?.caseId || '',
|
|
83
|
+
batchId: experience?.batchId || '',
|
|
84
|
+
pageId: experience?.pageId || '',
|
|
85
|
+
name: experience?.name || experience?.title || '',
|
|
86
|
+
steps: (experience?.steps || []).slice(0, 40),
|
|
87
|
+
notes: (experience?.notes || []).slice(-20),
|
|
88
|
+
corrections: (experience?.corrections || []).slice(-20),
|
|
89
|
+
reviews: (experience?.reviews || []).slice(-10),
|
|
90
|
+
feedbacks: (experience?.feedbacks || []).slice(-20),
|
|
91
|
+
sources: (experience?.sources || []).slice(-20),
|
|
92
|
+
observations: (experience?.observations || []).slice(-20),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 正典业务流程:只含可复用步骤,不带 caseId/纠错/复盘。 */
|
|
97
|
+
export function flowEpisodeBody(process) {
|
|
98
|
+
return {
|
|
99
|
+
type: 'flow',
|
|
100
|
+
category: 'business-flow',
|
|
101
|
+
id: process?.id || '',
|
|
102
|
+
name: process?.name || '',
|
|
103
|
+
summary: process?.summary || '',
|
|
104
|
+
keywords: (process?.keywords || []).slice(0, 20),
|
|
105
|
+
steps: (process?.steps || []).slice(0, 40),
|
|
106
|
+
notes: (process?.notes || []).slice(-20),
|
|
107
|
+
confidence: process?.confidence ?? null,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 正典事实:状态/证据计数/冲突值随 Episode 一起同步,供中心按实体检索。 */
|
|
112
|
+
export function factEpisodeBody(fact) {
|
|
113
|
+
const conflicts = (fact?.conflicts || []).slice(0, 10).map((conflict) => ({
|
|
114
|
+
value: conflict?.value,
|
|
115
|
+
confidence: conflict?.confidence ?? null,
|
|
116
|
+
evidence: (conflict?.evidence || []).slice(0, 5),
|
|
117
|
+
}));
|
|
118
|
+
return {
|
|
119
|
+
type: 'fact',
|
|
120
|
+
category: 'business-flow',
|
|
121
|
+
id: fact?.id || '',
|
|
122
|
+
kind: fact?.kind || '',
|
|
123
|
+
subject: fact?.subject || '',
|
|
124
|
+
predicate: fact?.predicate || '',
|
|
125
|
+
value: fact?.value,
|
|
126
|
+
scope: fact?.scope || {},
|
|
127
|
+
status: fact?.status || '',
|
|
128
|
+
confidence: fact?.confidence ?? null,
|
|
129
|
+
revision: fact?.revision ?? 1,
|
|
130
|
+
validFrom: fact?.validFrom || '',
|
|
131
|
+
validTo: fact?.validTo || '',
|
|
132
|
+
deprecationReason: fact?.deprecationReason || '',
|
|
133
|
+
conflicts,
|
|
134
|
+
evidence: (fact?.evidence || []).slice(0, 20).map((item) => ({
|
|
135
|
+
type: item?.type || '',
|
|
136
|
+
ref: item?.ref || '',
|
|
137
|
+
at: item?.at || '',
|
|
138
|
+
note: item?.note || '',
|
|
139
|
+
})),
|
|
140
|
+
notes: (fact?.notes || []).slice(-10),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 文档结构:单据字段/状态/流转/角色/权限/术语,不发送全文。 */
|
|
145
|
+
export function documentEpisodeBody(document) {
|
|
146
|
+
const statuses = (document?.statuses || []).slice(0, 40);
|
|
147
|
+
const transitions = (document?.transitions || []).slice(0, 60);
|
|
148
|
+
return {
|
|
149
|
+
type: 'document',
|
|
150
|
+
category: statuses.length || transitions.length ? 'document-flow' : 'business-flow',
|
|
151
|
+
id: document?.id || '',
|
|
152
|
+
title: document?.title || '',
|
|
153
|
+
summary: document?.summary || '',
|
|
154
|
+
kind: document?.kind || '',
|
|
155
|
+
fields: (document?.fields || []).slice(0, 200),
|
|
156
|
+
statuses,
|
|
157
|
+
transitions,
|
|
158
|
+
roles: (document?.roles || []).slice(0, 60),
|
|
159
|
+
permissions: (document?.permissions || []).slice(0, 120),
|
|
160
|
+
glossary: (document?.glossary || []).slice(0, 120),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
@@ -5,6 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { centralConfig, centralIngest, centralIngestFast } from './knowledge-central.mjs';
|
|
6
6
|
import { listLocallyEditedDocumentNames } from './knowledge-docs.mjs';
|
|
7
7
|
import { categorySourceTag, inferKnowledgeCategory, isKnowledgeCategory, UNCATEGORIZED } from './knowledge-categories.mjs';
|
|
8
|
+
import { classifyDocumentKind, isLearnableDocument } from './knowledge-clean.mjs';
|
|
8
9
|
import { nowIso, slug } from './util.mjs';
|
|
9
10
|
|
|
10
11
|
export const KNOWLEDGE_SOURCE_EXTS = ['.md', '.markdown', '.txt', '.json'];
|
|
@@ -176,6 +177,7 @@ export function buildDocumentEpisodes(files = [], { maxFileBytes = SCAN_DEFAULTS
|
|
|
176
177
|
}
|
|
177
178
|
}
|
|
178
179
|
const resolvedCategory = fixedCategory || inferKnowledgeCategory(rel + '\n' + text.slice(0, 4000));
|
|
180
|
+
const documentKind = classifyDocumentKind({ title: rel, content: text });
|
|
179
181
|
episodes.push({
|
|
180
182
|
key: 'doc:' + slug(rel),
|
|
181
183
|
name: rel,
|
|
@@ -187,6 +189,8 @@ export function buildDocumentEpisodes(files = [], { maxFileBytes = SCAN_DEFAULTS
|
|
|
187
189
|
path: absPath,
|
|
188
190
|
format: ext.replace(/^\./, ''),
|
|
189
191
|
size: stat.size,
|
|
192
|
+
documentKind,
|
|
193
|
+
learnable: isLearnableDocument(documentKind),
|
|
190
194
|
});
|
|
191
195
|
}
|
|
192
196
|
return episodes;
|
|
@@ -210,6 +214,8 @@ function documentOf(file, episode) {
|
|
|
210
214
|
format: episode.format,
|
|
211
215
|
size: episode.size,
|
|
212
216
|
category: episode.category || UNCATEGORIZED,
|
|
217
|
+
kind: episode.documentKind || '',
|
|
218
|
+
learnable: episode.learnable !== false,
|
|
213
219
|
status: 'imported',
|
|
214
220
|
};
|
|
215
221
|
}
|
|
@@ -256,13 +262,21 @@ export async function importKnowledgeToCentral(config, { paths = [], files = [],
|
|
|
256
262
|
for (const episode of episodes) episode.source_description = episode.source_description + ' · ' + String(title).slice(0, 120);
|
|
257
263
|
}
|
|
258
264
|
// 本地编辑过的文档不能重新发送源文件:新版 /ingest 会先写后删同名 Episode,会把编辑版一起替换掉。
|
|
265
|
+
// 测试报告/会议纪要只作证据,不进知识组,避免实例数据被中心抽取成正典。
|
|
259
266
|
const editedNames = listLocallyEditedDocumentNames(config);
|
|
260
|
-
const
|
|
267
|
+
const evidenceSkipped = episodes.filter((episode) => episode.learnable === false).length;
|
|
268
|
+
const sendEpisodes = episodes.filter((episode) => episode.learnable !== false && !editedNames.has(episode.name));
|
|
261
269
|
const episodeByPath = new Map(episodes.map((episode) => [episode.path, episode]));
|
|
262
270
|
const documents = [];
|
|
263
271
|
for (const file of scan.files) {
|
|
264
272
|
const doc = documentOf(file, episodeByPath.get(file.path));
|
|
265
273
|
const episode = episodeByPath.get(file.path);
|
|
274
|
+
if (episode && episode.learnable === false) {
|
|
275
|
+
doc.status = 'skipped';
|
|
276
|
+
doc.error = '按文档类型仅作证据,不进入知识组:' + episode.documentKind;
|
|
277
|
+
documents.push(doc);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
266
280
|
if (episode && editedNames.has(episode.name)) {
|
|
267
281
|
doc.status = 'skipped';
|
|
268
282
|
doc.error = '本地已编辑,保留本地版本;如需用源文件覆盖,请先删除本地文档';
|
|
@@ -274,6 +288,7 @@ export async function importKnowledgeToCentral(config, { paths = [], files = [],
|
|
|
274
288
|
const totals = {
|
|
275
289
|
files: scan.files.length,
|
|
276
290
|
episodes: episodes.length,
|
|
291
|
+
evidenceSkipped,
|
|
277
292
|
ingested: 0,
|
|
278
293
|
skipped: documents.filter((item) => item.status === 'skipped').length,
|
|
279
294
|
failed: 0,
|
|
@@ -18,10 +18,18 @@ export function centralConfig(config) {
|
|
|
18
18
|
const raw = config?.knowledge?.central || {};
|
|
19
19
|
const url = String(process.env.UITEST_KNOWLEDGE_URL || raw.url || '').replace(/\/+$/, '');
|
|
20
20
|
const groupId = String(process.env.UITEST_KNOWLEDGE_GROUP || raw.groupId || 'oms-v2-test');
|
|
21
|
+
const groupFromEnv = Boolean(process.env.UITEST_KNOWLEDGE_GROUP);
|
|
22
|
+
const evidenceGroupId = String(
|
|
23
|
+
process.env.UITEST_KNOWLEDGE_EVIDENCE_GROUP
|
|
24
|
+
|| (groupFromEnv ? groupId + '-evidence' : '')
|
|
25
|
+
|| raw.evidenceGroupId
|
|
26
|
+
|| groupId + '-evidence',
|
|
27
|
+
);
|
|
21
28
|
return {
|
|
22
29
|
enabled: raw.enabled !== false && Boolean(url),
|
|
23
30
|
url,
|
|
24
31
|
groupId,
|
|
32
|
+
evidenceGroupId,
|
|
25
33
|
timeoutMs: Math.max(3000, Number(raw.timeoutMs) || 300000),
|
|
26
34
|
batchSize: Math.max(1, Number(raw.batchSize) || 2),
|
|
27
35
|
searchTimeoutMs: Math.max(1000, Number(raw.searchTimeoutMs) || 10000),
|
|
@@ -107,17 +115,36 @@ export async function centralHealth(config) {
|
|
|
107
115
|
return { enabled: true, ok: payload?.ok === true, service: payload?.service || '', url: central.url, groupId: central.groupId };
|
|
108
116
|
}
|
|
109
117
|
|
|
110
|
-
export async function centralStats(config) {
|
|
118
|
+
export async function centralStats(config, { groupId = '' } = {}) {
|
|
111
119
|
const central = centralConfig(config);
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
120
|
+
const group = String(groupId || central.groupId);
|
|
121
|
+
if (!central.enabled) return { enabled: false, ok: false, groupId: group, nodes: [], edges: [] };
|
|
122
|
+
const payload = await requestJson(config, '/stats?group_id=' + encodeURIComponent(group), { timeoutMs: 5000 });
|
|
123
|
+
return { enabled: true, ok: true, groupId: group, nodes: payload?.nodes || [], edges: payload?.edges || [] };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 中心检索结果的有效性:invalid_at 已过期(或无法解析)的边不再作为知识提示。 */
|
|
127
|
+
export function isCentralResultValid(result, { at = nowIso() } = {}) {
|
|
128
|
+
const invalidAt = result?.invalid_at;
|
|
129
|
+
if (!invalidAt) return true;
|
|
130
|
+
const invalidMs = Date.parse(String(invalidAt));
|
|
131
|
+
if (!Number.isFinite(invalidMs)) return false;
|
|
132
|
+
const nowMs = Date.parse(String(at));
|
|
133
|
+
if (!Number.isFinite(nowMs)) return true;
|
|
134
|
+
return invalidMs > nowMs;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function filterCentralResults(results, { at = nowIso() } = {}) {
|
|
138
|
+
const list = Array.isArray(results) ? results : [];
|
|
139
|
+
const valid = list.filter((result) => isCentralResultValid(result, { at }));
|
|
140
|
+
return { results: valid, filtered: list.length - valid.length };
|
|
115
141
|
}
|
|
116
142
|
|
|
117
143
|
export async function centralSearch(config, { query = '', limit = 10, groupIds = null } = {}) {
|
|
118
144
|
const central = centralConfig(config);
|
|
145
|
+
const group = Array.isArray(groupIds) && groupIds.length ? groupIds[0] : central.groupId;
|
|
119
146
|
if (!central.enabled || !String(query || '').trim()) {
|
|
120
|
-
return { enabled: central.enabled, ok: false, groupId:
|
|
147
|
+
return { enabled: central.enabled, ok: false, groupId: group, results: [] };
|
|
121
148
|
}
|
|
122
149
|
try {
|
|
123
150
|
const payload = await requestJson(config, '/search', {
|
|
@@ -129,9 +156,16 @@ export async function centralSearch(config, { query = '', limit = 10, groupIds =
|
|
|
129
156
|
num_results: Math.max(1, Math.min(50, Number(limit) || 10)),
|
|
130
157
|
},
|
|
131
158
|
});
|
|
132
|
-
|
|
159
|
+
const filtered = filterCentralResults(payload?.results || []);
|
|
160
|
+
return {
|
|
161
|
+
enabled: true,
|
|
162
|
+
ok: true,
|
|
163
|
+
groupId: group,
|
|
164
|
+
results: filtered.results,
|
|
165
|
+
invalidFiltered: filtered.filtered,
|
|
166
|
+
};
|
|
133
167
|
} catch (error) {
|
|
134
|
-
return { enabled: true, ok: false, groupId:
|
|
168
|
+
return { enabled: true, ok: false, groupId: group, results: [], error: String(error.message || error), code: error.code || '' };
|
|
135
169
|
}
|
|
136
170
|
}
|
|
137
171
|
|
|
@@ -211,6 +245,62 @@ export async function centralDeleteEpisode(config, { uuid = '', groupId = '' } =
|
|
|
211
245
|
}
|
|
212
246
|
}
|
|
213
247
|
|
|
248
|
+
/**
|
|
249
|
+
* 调用中心 LLM 生成知识摘要。items 为 [{id, kind, title, text}]。
|
|
250
|
+
* 失败时返回 ok:false,由调用方保留旧摘要;不会静默写入半成品。
|
|
251
|
+
*/
|
|
252
|
+
export async function centralSummarize(config, { items = [], maxChars = 160 } = {}) {
|
|
253
|
+
const central = centralConfig(config);
|
|
254
|
+
const base = { enabled: central.enabled, items: [], error: '' };
|
|
255
|
+
if (!central.enabled) return { ok: false, ...base, error: '中心知识库未启用', code: 'CENTRAL_DISABLED' };
|
|
256
|
+
if (!Array.isArray(items) || !items.length) return { ok: false, ...base, error: '没有待摘要条目' };
|
|
257
|
+
try {
|
|
258
|
+
const payload = await requestJson(config, '/summarize', {
|
|
259
|
+
method: 'POST',
|
|
260
|
+
body: {
|
|
261
|
+
max_chars: Math.max(80, Math.min(400, Number(maxChars) || 160)),
|
|
262
|
+
items: items.map((item) => ({
|
|
263
|
+
id: String(item.id || ''),
|
|
264
|
+
kind: String(item.kind || ''),
|
|
265
|
+
title: String(item.title || ''),
|
|
266
|
+
text: String(item.text || ''),
|
|
267
|
+
})),
|
|
268
|
+
},
|
|
269
|
+
timeoutMs: Math.max(central.timeoutMs, 120000),
|
|
270
|
+
});
|
|
271
|
+
return { ok: true, ...base, items: Array.isArray(payload?.items) ? payload.items : [], engine: payload?.engine || 'llm' };
|
|
272
|
+
} catch (error) {
|
|
273
|
+
return { ok: false, ...base, error: String(error.message || error), code: error.code || '' };
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* 整组重置中心知识库:删除该组全部节点与关系,用于净室重建。
|
|
279
|
+
* 破坏性操作,必须显式 confirm=true;由服务端负责暂停/恢复自动流水线。
|
|
280
|
+
*/
|
|
281
|
+
export async function centralResetGroup(config, { groupId = '', confirm = false } = {}) {
|
|
282
|
+
const central = centralConfig(config);
|
|
283
|
+
const group = String(groupId || central.groupId);
|
|
284
|
+
const base = { enabled: central.enabled, groupId: group, deleted: 0, remaining: null };
|
|
285
|
+
if (!central.enabled) return { ok: false, ...base, error: '中心知识库未启用' };
|
|
286
|
+
if (!confirm) return { ok: false, ...base, error: '整组重置需要 confirm=true', code: 'CENTRAL_CONFIRM_REQUIRED' };
|
|
287
|
+
try {
|
|
288
|
+
const payload = await requestJson(config, '/groups/' + encodeURIComponent(group) + '/reset', {
|
|
289
|
+
method: 'POST',
|
|
290
|
+
body: { confirm: true },
|
|
291
|
+
timeoutMs: Math.max(central.timeoutMs, 120000),
|
|
292
|
+
});
|
|
293
|
+
return {
|
|
294
|
+
ok: payload?.ok === true,
|
|
295
|
+
...base,
|
|
296
|
+
deleted: Number(payload?.deleted) || 0,
|
|
297
|
+
remaining: payload?.remaining === undefined ? null : Number(payload.remaining) || 0,
|
|
298
|
+
};
|
|
299
|
+
} catch (error) {
|
|
300
|
+
return { ok: false, ...base, error: String(error.message || error), code: error.code || '' };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
214
304
|
/** 给历史 episode 补分类标记;幂等,可重复调用。 */
|
|
215
305
|
export async function centralBackfillCategories(config, { groupId = '', force = false } = {}) {
|
|
216
306
|
const central = centralConfig(config);
|
|
@@ -350,27 +440,60 @@ export async function centralSemanticIndex(config, { limit = 5, groupId = '' } =
|
|
|
350
440
|
}
|
|
351
441
|
}
|
|
352
442
|
|
|
353
|
-
export async function centralStatus(config, { ttlMs = 30000 } = {}) {
|
|
354
|
-
|
|
443
|
+
export async function centralStatus(config, { ttlMs = 30000 } = {}) {
|
|
444
|
+
const central = centralConfig(config);
|
|
445
|
+
if (!central.enabled) {
|
|
446
|
+
return { enabled: false, ok: false, url: '', groupId: central.groupId, evidenceGroupId: central.evidenceGroupId, nodes: [], edges: [] };
|
|
447
|
+
}
|
|
355
448
|
const file = centralSyncFile(config).replace(/knowledge-central-ingested\.json$/, 'knowledge-central-status.json');
|
|
356
449
|
const cached = readJson(file, null);
|
|
357
|
-
if (cached && Date.now() - new Date(cached.at || 0).getTime() < ttlMs)
|
|
450
|
+
if (cached && Date.now() - new Date(cached.at || 0).getTime() < ttlMs) {
|
|
451
|
+
return { ...cached, evidenceGroupId: central.evidenceGroupId };
|
|
452
|
+
}
|
|
358
453
|
try {
|
|
359
454
|
const [health, stats] = await Promise.all([centralHealth(config), centralStats(config)]);
|
|
360
|
-
const value = { ...health, ...stats, at: nowIso() };
|
|
455
|
+
const value = { ...health, ...stats, evidenceGroupId: central.evidenceGroupId, at: nowIso() };
|
|
361
456
|
writeJson(file, value);
|
|
362
457
|
return value;
|
|
363
458
|
} catch (error) {
|
|
364
|
-
return { enabled: true, ok: false, url: central.url, groupId: central.groupId, nodes: [], edges: [], error: String(error.message || error), at: nowIso() };
|
|
459
|
+
return { enabled: true, ok: false, url: central.url, groupId: central.groupId, evidenceGroupId: central.evidenceGroupId, nodes: [], edges: [], error: String(error.message || error), at: nowIso() };
|
|
365
460
|
}
|
|
366
461
|
}
|
|
367
462
|
|
|
463
|
+
const CENTRAL_SYNC_STATE_VERSION = 2;
|
|
464
|
+
|
|
465
|
+
/** 同步去重键带 group:同一 Episode 可以同时存在于知识组与证据组。 */
|
|
466
|
+
export function centralSyncEntryKey(groupId, key) {
|
|
467
|
+
return String(groupId) + '\0' + String(key);
|
|
468
|
+
}
|
|
469
|
+
|
|
368
470
|
export function readCentralSyncState(config) {
|
|
369
|
-
|
|
471
|
+
const state = readJson(centralSyncFile(config), { version: CENTRAL_SYNC_STATE_VERSION, entries: {} });
|
|
472
|
+
if (Number(state?.version) < CENTRAL_SYNC_STATE_VERSION || !state.entries || typeof state.entries !== 'object') {
|
|
473
|
+
return { version: CENTRAL_SYNC_STATE_VERSION, entries: {} };
|
|
474
|
+
}
|
|
475
|
+
return state;
|
|
370
476
|
}
|
|
371
477
|
|
|
372
478
|
export function saveCentralSyncState(config, state) {
|
|
373
|
-
writeJson(centralSyncFile(config), state);
|
|
479
|
+
writeJson(centralSyncFile(config), { ...state, version: CENTRAL_SYNC_STATE_VERSION });
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** 清空某个 group 的本地同步去重记录,使清库后可以重新全量写入。 */
|
|
483
|
+
export function clearCentralSyncGroup(config, { groupId = '' } = {}) {
|
|
484
|
+
const group = String(groupId);
|
|
485
|
+
if (!group) return 0;
|
|
486
|
+
const state = readCentralSyncState(config);
|
|
487
|
+
const entries = state.entries && typeof state.entries === 'object' ? state.entries : {};
|
|
488
|
+
const prefix = group + '\0';
|
|
489
|
+
let removed = 0;
|
|
490
|
+
for (const key of Object.keys(entries)) {
|
|
491
|
+
if (!key.startsWith(prefix)) continue;
|
|
492
|
+
delete entries[key];
|
|
493
|
+
removed += 1;
|
|
494
|
+
}
|
|
495
|
+
if (removed) saveCentralSyncState(config, { ...state, entries });
|
|
496
|
+
return removed;
|
|
374
497
|
}
|
|
375
498
|
|
|
376
499
|
/**
|
|
@@ -382,15 +505,16 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
382
505
|
if (!central.enabled) {
|
|
383
506
|
return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [], mode: 'classic' };
|
|
384
507
|
}
|
|
508
|
+
const group = groupId || central.groupId;
|
|
385
509
|
const mode = fast && (await centralSupportsFastUpsert(config)) ? 'fast' : 'classic';
|
|
386
|
-
const state = dedupe ? readCentralSyncState(config) : { version:
|
|
510
|
+
const state = dedupe ? readCentralSyncState(config) : { version: CENTRAL_SYNC_STATE_VERSION, entries: {} };
|
|
387
511
|
const entries = state.entries && typeof state.entries === 'object' ? state.entries : {};
|
|
388
512
|
const pending = [];
|
|
389
513
|
const pendingKeys = new Set();
|
|
390
514
|
let skipped = 0;
|
|
391
515
|
for (const episode of episodes) {
|
|
392
516
|
if (!episode?.name) continue;
|
|
393
|
-
const key = episode.key || episode.name;
|
|
517
|
+
const key = centralSyncEntryKey(group, episode.key || episode.name);
|
|
394
518
|
const hash = stableHash({ body: episode.body, source: episode.source || 'json', sourceDescription: episode.source_description || '' });
|
|
395
519
|
if (pendingKeys.has(key) || (dedupe && entries[key] === hash)) { skipped += 1; continue; }
|
|
396
520
|
pendingKeys.add(key);
|
|
@@ -402,21 +526,24 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
402
526
|
const batchSize = mode === 'fast'
|
|
403
527
|
? Math.max(10, Number(central.batchSize || 2) * 5)
|
|
404
528
|
: Math.max(1, Number(central.batchSize) || 5);
|
|
405
|
-
|
|
529
|
+
// 已同步的 Episode 也计入进度,否则批次 stage 的 done 永远到不了 total。
|
|
530
|
+
const dedupeSkipped = skipped;
|
|
531
|
+
const progressTotal = pending.length + dedupeSkipped;
|
|
532
|
+
if (onProgress) await onProgress({ done: dedupeSkipped, total: progressTotal, mode });
|
|
406
533
|
for (let offset = 0; offset < pending.length; offset += batchSize) {
|
|
407
534
|
const chunk = pending.slice(offset, offset + batchSize);
|
|
408
535
|
try {
|
|
409
536
|
const payload = await requestJson(config, mode === 'fast' ? '/ingest-fast' : '/ingest', {
|
|
410
537
|
method: 'POST',
|
|
411
538
|
body: {
|
|
412
|
-
group_id:
|
|
539
|
+
group_id: group,
|
|
413
540
|
episodes: chunk.map((episode) => ({
|
|
414
541
|
name: episode.name,
|
|
415
542
|
body: typeof episode.body === 'string' ? episode.body : JSON.stringify(episode.body),
|
|
416
543
|
source_description: episode.source_description || 'uitest',
|
|
417
544
|
reference_time: episode.reference_time || nowIso(),
|
|
418
545
|
source: episode.source || 'json',
|
|
419
|
-
group_id:
|
|
546
|
+
group_id: group,
|
|
420
547
|
replace_prefix: episode.replace_prefix || null,
|
|
421
548
|
...(mode === 'fast' ? { upsert: true } : {}),
|
|
422
549
|
})),
|
|
@@ -437,9 +564,9 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
437
564
|
} catch (error) {
|
|
438
565
|
errors.push({ ok: false, error: String(error.message || error), count: chunk.length, names: chunk.map((entry) => entry.name) });
|
|
439
566
|
}
|
|
440
|
-
if (onProgress) await onProgress({ done: offset + chunk.length, total:
|
|
567
|
+
if (onProgress) await onProgress({ done: dedupeSkipped + offset + chunk.length, total: progressTotal, mode });
|
|
441
568
|
}
|
|
442
|
-
if (dedupe) saveCentralSyncState(config, {
|
|
569
|
+
if (dedupe) saveCentralSyncState(config, { updatedAt: nowIso(), entries });
|
|
443
570
|
const failed = errors.reduce((sum, item) => sum + (Number(item.count) || 1), 0);
|
|
444
571
|
return {
|
|
445
572
|
enabled: true,
|
|
@@ -450,7 +577,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
450
577
|
results,
|
|
451
578
|
errors,
|
|
452
579
|
mode,
|
|
453
|
-
groupId:
|
|
580
|
+
groupId: group,
|
|
454
581
|
url: central.url,
|
|
455
582
|
};
|
|
456
583
|
}
|