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
|
@@ -0,0 +1,1271 @@
|
|
|
1
|
+
// 知识合并与清洗:把文档噪声、用例执行记录与重复条目从正典层分离。
|
|
2
|
+
// planConsolidation 是纯函数,输出可审查的合并计划;applyConsolidation 负责备份后落盘。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { KNOWLEDGE_FILES, appendExperiences, knowledgeDir, loadKnowledge, saveKnowledge } from './knowledge.mjs';
|
|
7
|
+
import { extractDocumentStructure, mergeDocumentStructure } from './doc-structure.mjs';
|
|
8
|
+
import { invalidateStaleSummaries } from './knowledge-summarize.mjs';
|
|
9
|
+
import { applyFactConsolidation, buildCandidates, planFactConsolidation } from './knowledge-facts.mjs';
|
|
10
|
+
import {
|
|
11
|
+
canonicalPageUrl,
|
|
12
|
+
classifyDocumentKind,
|
|
13
|
+
cleanCanonicalText,
|
|
14
|
+
cleanRoleName,
|
|
15
|
+
compactLearnings,
|
|
16
|
+
documentSlugFromKnowledgeId,
|
|
17
|
+
isCaseReferenced,
|
|
18
|
+
isDialogPageRecord,
|
|
19
|
+
isEvidenceDocument,
|
|
20
|
+
isInstanceValueText,
|
|
21
|
+
isLearnableDocument,
|
|
22
|
+
isStructuredPage,
|
|
23
|
+
longNumericTokens,
|
|
24
|
+
looksLikeActionStep,
|
|
25
|
+
looksLikeEvidenceStatement,
|
|
26
|
+
looksLikeHeadingNoise,
|
|
27
|
+
looksLikeProcessHeading,
|
|
28
|
+
looksLikeRule,
|
|
29
|
+
looksLikeRunArtifact,
|
|
30
|
+
looksLikeStubTitleNoise,
|
|
31
|
+
looksLikeSystemLabel,
|
|
32
|
+
looksLikeUrlTitle,
|
|
33
|
+
normalizeKey,
|
|
34
|
+
pageTitleFromUrl,
|
|
35
|
+
pageUrlKey,
|
|
36
|
+
sharesLongNumericToken,
|
|
37
|
+
sourceDocumentTitles,
|
|
38
|
+
stripInstanceRefs,
|
|
39
|
+
stripPageCodePrefix,
|
|
40
|
+
stubPageTitleKey,
|
|
41
|
+
} from './knowledge-clean.mjs';
|
|
42
|
+
import { ensureDir, nowIso, slug, writeFileAtomic, writeJsonFile } from './util.mjs';
|
|
43
|
+
|
|
44
|
+
const MAX_NOTES = 30;
|
|
45
|
+
const MAX_HINTS = 40;
|
|
46
|
+
|
|
47
|
+
function asArray(value) {
|
|
48
|
+
return Array.isArray(value) ? value : value === undefined || value === null ? [] : [value];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function uniqueStrings(values) {
|
|
52
|
+
const out = [];
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
for (const value of values || []) {
|
|
55
|
+
const text = String(value ?? '').replace(/\s+/g, ' ').trim();
|
|
56
|
+
if (!text || seen.has(text)) continue;
|
|
57
|
+
seen.add(text);
|
|
58
|
+
out.push(text);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function stableJson(value) {
|
|
64
|
+
if (value === null || value === undefined) return 'null';
|
|
65
|
+
if (typeof value !== 'object') return JSON.stringify(value);
|
|
66
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
|
|
67
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function changed(before, after) {
|
|
71
|
+
return stableJson(before) !== stableJson(after);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function stepText(step) {
|
|
75
|
+
if (typeof step === 'string') return step;
|
|
76
|
+
return step?.text || step?.desc || step?.action || '';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalizeUrl(url) {
|
|
80
|
+
return pageUrlKey(url);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function documentIndex(knowledge) {
|
|
84
|
+
const byId = new Map();
|
|
85
|
+
const bySlug = new Map();
|
|
86
|
+
const byTitle = new Map();
|
|
87
|
+
for (const doc of knowledge?.documents?.documents || []) {
|
|
88
|
+
if (!doc?.id) continue;
|
|
89
|
+
byId.set(String(doc.id), doc);
|
|
90
|
+
const slugKey = documentSlugFromKnowledgeId('doc-' + doc.id + '-rules-1') || slug(String(doc.title || doc.id));
|
|
91
|
+
bySlug.set(slugKey, doc);
|
|
92
|
+
bySlug.set(slug(String(doc.title || doc.id)), doc);
|
|
93
|
+
if (doc.title) byTitle.set(normalizeKey(doc.title), doc);
|
|
94
|
+
}
|
|
95
|
+
return { byId, bySlug, byTitle };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function documentsForRecord(record, index) {
|
|
99
|
+
const found = [];
|
|
100
|
+
const idSlug = documentSlugFromKnowledgeId(record?.id);
|
|
101
|
+
if (idSlug && index.bySlug.has(idSlug)) found.push(index.bySlug.get(idSlug));
|
|
102
|
+
for (const title of sourceDocumentTitles(record)) {
|
|
103
|
+
const doc = index.byTitle.get(normalizeKey(title));
|
|
104
|
+
if (doc) found.push(doc);
|
|
105
|
+
}
|
|
106
|
+
return [...new Set(found)];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const isDialogPage = isDialogPageRecord;
|
|
110
|
+
|
|
111
|
+
function pageUrlOf(page, systemUrls = {}) {
|
|
112
|
+
// 弹窗没有独立路由(url 与基础页相同),urlName 只是打开它的入口页;
|
|
113
|
+
// 按 URL/urlName 归并会把弹窗内容并进基础页,弹窗一律按标题分组。
|
|
114
|
+
if (isDialogPage(page)) return '';
|
|
115
|
+
if (page?.url) return page.url;
|
|
116
|
+
const name = page?.urlName;
|
|
117
|
+
return name && systemUrls?.[name] ? systemUrls[name] : '';
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 稳定页面 id:不是 URL/路径转写,合并时优先保留。 */
|
|
121
|
+
function stablePageId(page) {
|
|
122
|
+
const id = String(page?.id || '');
|
|
123
|
+
return Boolean(id) && !id.startsWith('/') && !looksLikeUrlTitle(id);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function pageKey(page, systemUrls = {}) {
|
|
127
|
+
const url = pageUrlOf(page, systemUrls);
|
|
128
|
+
if (url) return 'url:' + normalizeUrl(url);
|
|
129
|
+
if (page?.urlName) return 'urlName:' + page.urlName + '|' + normalizeKey(page.title || page.id);
|
|
130
|
+
return 'title:' + normalizeKey(page.title || page.id);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 无入口、无结构的标题型占位页,且标题/别名没有可用页面名时归档。 */
|
|
134
|
+
function isNoisyStubPage(page) {
|
|
135
|
+
if (page?.status !== 'stub' || page?.url || page?.urlName) return false;
|
|
136
|
+
if (!looksLikeStubTitleNoise(page?.title || page?.id)) return false;
|
|
137
|
+
return !(page?.aliases || []).some((alias) => alias && !looksLikeStubTitleNoise(alias));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function pageScore(page) { let score = Number(page?.confidence) || 0;
|
|
141
|
+
if (page?.url) score += 3;
|
|
142
|
+
if (page?.urlName) score += 1;
|
|
143
|
+
if ((page?.actions || []).length) score += 2;
|
|
144
|
+
if ((page?.table?.headers || []).length) score += 1;
|
|
145
|
+
if ((page?.observations || []).length) score += 1;
|
|
146
|
+
if (page?.updatedAt) score += 0.001;
|
|
147
|
+
return score;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 合并占位页时优先保留干净的页面名与 id(不带布局说明、不带编号前缀、更短)。 */
|
|
151
|
+
function stubTitleScore(page) {
|
|
152
|
+
const title = String(page?.title || '');
|
|
153
|
+
const id = String(page?.id || '');
|
|
154
|
+
let score = title.length;
|
|
155
|
+
if (/[((]/.test(title)) score += 50;
|
|
156
|
+
if (/(?:列表页|详情页|页面|页)$/u.test(title)) score += 20;
|
|
157
|
+
// 标题被去前缀后相同时,优先让「采购单列表」这种可读 id 做基页。
|
|
158
|
+
if (/^[A-Za-z]/.test(id) || /[-—]/.test(id)) score += 10;
|
|
159
|
+
return score;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function provenanceKeys(page) {
|
|
163
|
+
return new Set((page?.provenance?.documents || []).map((doc) => normalizeKey(doc)).filter(Boolean));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 两个存根是否来自同一文档/模块。编号前缀不同的同名页面(如履约 P1a 与采购 EXE-P001)
|
|
168
|
+
* 可能只是不同模块的同名页;来源文档无交集时不合并,避免把两个页面混成一个。
|
|
169
|
+
* 双方都没有来源时按归一化页面标题判断同名;只有一侧有来源时无法证明同源,不合并。
|
|
170
|
+
*/
|
|
171
|
+
function sameStubSource(a, b) {
|
|
172
|
+
const left = provenanceKeys(a);
|
|
173
|
+
const right = provenanceKeys(b);
|
|
174
|
+
if (left.size && right.size) {
|
|
175
|
+
for (const key of left) if (right.has(key)) return true;
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (left.size || right.size) return false;
|
|
179
|
+
const leftKey = stubPageTitleKey(a?.title);
|
|
180
|
+
return Boolean(leftKey) && leftKey === stubPageTitleKey(b?.title);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 双方都有来源文档但没有任何交集:跨模块同名页,不能合并。 */
|
|
184
|
+
function sourceConflict(a, b) {
|
|
185
|
+
const left = provenanceKeys(a);
|
|
186
|
+
const right = provenanceKeys(b);
|
|
187
|
+
if (!left.size || !right.size) return false;
|
|
188
|
+
for (const key of left) if (right.has(key)) return false;
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 一组存根是否都来自同一个来源组(所有存根至少共享一个文档);任一缺来源即无法证明。 */
|
|
193
|
+
function sameSourceGroup(pages) {
|
|
194
|
+
if (!pages.length) return true;
|
|
195
|
+
const sources = pages.map(provenanceKeys);
|
|
196
|
+
if (sources.some((set) => !set.size)) return false;
|
|
197
|
+
const common = [...sources[0]].filter((key) => sources.slice(1).every((set) => set.has(key)));
|
|
198
|
+
return common.length > 0;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 正典页没有来源文档时,同键存根可能来自不同模块。此时只有存根都在同一来源组
|
|
203
|
+
* 才能一起认领;否则不做顺序猜测,保留为独立页面。
|
|
204
|
+
*/
|
|
205
|
+
function ambiguousStubClaim(base, stubs) {
|
|
206
|
+
if (provenanceKeys(base).size) return false;
|
|
207
|
+
if (stubs.length < 2) return false;
|
|
208
|
+
return !sameSourceGroup(stubs);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 把与唯一正典页同键的 URL-less 存根并入正典。歧义时整组跳过;
|
|
213
|
+
* 在存根互相合并前后各跑一次,保证一次整理就到不动点。
|
|
214
|
+
*/
|
|
215
|
+
function claimStubsIntoCanonical(pages, { stats, actions }) {
|
|
216
|
+
const canonicalByStubKey = new Map();
|
|
217
|
+
pages.forEach((page, pageIndex) => {
|
|
218
|
+
if (page.status === 'stub') return;
|
|
219
|
+
const key = stubPageTitleKey(page.title);
|
|
220
|
+
if (!key) return;
|
|
221
|
+
if (!canonicalByStubKey.has(key)) canonicalByStubKey.set(key, []);
|
|
222
|
+
canonicalByStubKey.get(key).push(pageIndex);
|
|
223
|
+
});
|
|
224
|
+
const stubsByKey = new Map();
|
|
225
|
+
pages.forEach((page, pageIndex) => {
|
|
226
|
+
if (page.status !== 'stub' || page.url || page.urlName) return;
|
|
227
|
+
const key = stubPageTitleKey(page.title);
|
|
228
|
+
if (!key) return;
|
|
229
|
+
if (!stubsByKey.has(key)) stubsByKey.set(key, []);
|
|
230
|
+
stubsByKey.get(key).push(pageIndex);
|
|
231
|
+
});
|
|
232
|
+
const merged = new Set();
|
|
233
|
+
for (const [key, candidates] of canonicalByStubKey) {
|
|
234
|
+
if (candidates.length !== 1) continue;
|
|
235
|
+
const baseIndex = candidates[0];
|
|
236
|
+
const stubIndices = stubsByKey.get(key) || [];
|
|
237
|
+
if (!stubIndices.length) continue;
|
|
238
|
+
if (ambiguousStubClaim(pages[baseIndex], stubIndices.map((index) => pages[index]))) continue;
|
|
239
|
+
for (const stubIndex of stubIndices) {
|
|
240
|
+
// 双方都有来源但无交集时不合并;单侧有来源时按标题身份认领。
|
|
241
|
+
if (sourceConflict(pages[baseIndex], pages[stubIndex])) continue;
|
|
242
|
+
pages[baseIndex] = mergePageRecords(pages[baseIndex], pages[stubIndex]);
|
|
243
|
+
merged.add(stubIndex);
|
|
244
|
+
stats.pages.merged += 1;
|
|
245
|
+
if (actions.length < 200) actions.push(`页面 ${pages[stubIndex].id} 合并到 ${pages[baseIndex].id}(存根同名)`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return pages.filter((_, index) => !merged.has(index));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const PAGE_TYPE_TERMS = [
|
|
252
|
+
{ suffix: 'details', zh: '详情' },
|
|
253
|
+
{ suffix: 'detail', zh: '详情' },
|
|
254
|
+
{ suffix: 'lists', zh: '列表' },
|
|
255
|
+
{ suffix: 'list', zh: '列表' },
|
|
256
|
+
{ suffix: 'dialogs', zh: '弹窗' },
|
|
257
|
+
{ suffix: 'dialog', zh: '弹窗' },
|
|
258
|
+
{ suffix: 'popups', zh: '弹窗' },
|
|
259
|
+
{ suffix: 'popup', zh: '弹窗' },
|
|
260
|
+
{ suffix: 'modal', zh: '弹窗' },
|
|
261
|
+
{ suffix: 'edit', zh: '编辑' },
|
|
262
|
+
{ suffix: 'form', zh: '表单' },
|
|
263
|
+
{ suffix: 'page', zh: '' },
|
|
264
|
+
];
|
|
265
|
+
|
|
266
|
+
// 这些词单独作为术语映射没有区分度,不能拿来把英文机械标题对回中文页面名。
|
|
267
|
+
const GENERIC_GLOSSARY_ENGLISH = new Set([
|
|
268
|
+
'page', 'pages', 'list', 'lists', 'detail', 'details', 'dialog', 'modal',
|
|
269
|
+
'form', 'view', 'edit', 'home', 'login', 'search', 'data', 'system',
|
|
270
|
+
'module', 'button', 'field', 'fields', 'status', 'rule', 'rules',
|
|
271
|
+
]);
|
|
272
|
+
|
|
273
|
+
function normalizeEnglishKey(value) {
|
|
274
|
+
return String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 从系统术语表建立「英文词 → 中文术语」索引;同一英文对应多个术语时视为歧义,不参与匹配。 */
|
|
278
|
+
function glossaryEnglishIndex(system) {
|
|
279
|
+
const index = new Map();
|
|
280
|
+
for (const entry of asArray(system?.glossary)) {
|
|
281
|
+
const term = String(entry?.term || '').trim();
|
|
282
|
+
const definition = String(entry?.definition || '').trim();
|
|
283
|
+
if (!term || !/[一-鿿]/.test(term) || !definition) continue;
|
|
284
|
+
for (const part of definition.match(/[A-Za-z][A-Za-z0-9]*(?:[ \-][A-Za-z][A-Za-z0-9]*)*/g) || []) {
|
|
285
|
+
const key = normalizeEnglishKey(part);
|
|
286
|
+
if (key.length < 5 || GENERIC_GLOSSARY_ENGLISH.has(key)) continue;
|
|
287
|
+
if (!index.has(key)) index.set(key, new Set());
|
|
288
|
+
index.get(key).add(term);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
for (const [key, terms] of index) {
|
|
292
|
+
if (terms.size !== 1 || key.length < 5) index.delete(key);
|
|
293
|
+
}
|
|
294
|
+
return index;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 机械英文标题(purchaseTaskList)借助术语表还原中文页面名(采购任务 + 列表)。
|
|
299
|
+
* 只接受「具体英文词 + 页面类型后缀」,且标题必须是非中文的机械名,避免猜测。
|
|
300
|
+
*/
|
|
301
|
+
function crossLanguagePageHint(page, glossaryIndex) {
|
|
302
|
+
if (!page || page.status === 'stub') return null;
|
|
303
|
+
const title = String(page.title || '').trim();
|
|
304
|
+
if (!title || /[一-鿿]/.test(title) || looksLikeUrlTitle(title)) return null;
|
|
305
|
+
const names = uniqueStrings([title, page.id, page.urlName]).filter(Boolean);
|
|
306
|
+
for (const name of names) {
|
|
307
|
+
const key = normalizeEnglishKey(name);
|
|
308
|
+
for (const { suffix, zh } of PAGE_TYPE_TERMS) {
|
|
309
|
+
if (key.length <= suffix.length + 4 || !key.endsWith(suffix)) continue;
|
|
310
|
+
const stem = key.slice(0, -suffix.length);
|
|
311
|
+
const terms = glossaryIndex.get(stem);
|
|
312
|
+
if (!terms || terms.size !== 1) continue;
|
|
313
|
+
const term = [...terms][0];
|
|
314
|
+
return { key: normalizeKey(term + zh), term };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function cleanTextList(values, { max = Infinity } = {}) {
|
|
321
|
+
const out = [];
|
|
322
|
+
const seen = new Set();
|
|
323
|
+
for (const value of values || []) {
|
|
324
|
+
const text = cleanCanonicalText(value);
|
|
325
|
+
if (!text || text.length < 2 || seen.has(text)) continue;
|
|
326
|
+
if (isInstanceValueText(text)) continue;
|
|
327
|
+
seen.add(text);
|
|
328
|
+
out.push(text);
|
|
329
|
+
}
|
|
330
|
+
return out.slice(0, max);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function uniqueByStable(values) {
|
|
334
|
+
const out = [];
|
|
335
|
+
const seen = new Set();
|
|
336
|
+
for (const value of values || []) {
|
|
337
|
+
if (value === null || value === undefined) continue;
|
|
338
|
+
const key = stableJson(value);
|
|
339
|
+
if (seen.has(key)) continue;
|
|
340
|
+
seen.add(key);
|
|
341
|
+
out.push(value);
|
|
342
|
+
}
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function cleanActionStep(step) {
|
|
347
|
+
if (typeof step === 'string') return cleanCanonicalText(step);
|
|
348
|
+
if (!step || typeof step !== 'object') return null;
|
|
349
|
+
const next = { ...step };
|
|
350
|
+
for (const field of ['text', 'label', 'placeholder', 'value', 'option', 'desc', 'title', 'selector']) {
|
|
351
|
+
if (typeof next[field] !== 'string') continue;
|
|
352
|
+
next[field] = cleanCanonicalText(next[field]);
|
|
353
|
+
}
|
|
354
|
+
if (!Object.values(next).some((value) => typeof value === 'string' && value.trim())) return null;
|
|
355
|
+
return next;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function cleanAction(action) {
|
|
359
|
+
if (!action || typeof action !== 'object') return null;
|
|
360
|
+
const originalId = String(action.id || '');
|
|
361
|
+
const next = { ...action };
|
|
362
|
+
for (const field of ['title', 'text', 'desc']) {
|
|
363
|
+
if (typeof next[field] !== 'string') continue;
|
|
364
|
+
next[field] = cleanCanonicalText(next[field]);
|
|
365
|
+
}
|
|
366
|
+
next.id = cleanCanonicalText(originalId);
|
|
367
|
+
if (!next.id) next.id = slug(next.title || next.text || next.action || 'action').toLowerCase();
|
|
368
|
+
const aliases = uniqueStrings(
|
|
369
|
+
[...(action.aliases || []), ...(originalId && originalId !== next.id ? [originalId] : [])]
|
|
370
|
+
.map(cleanCanonicalText)
|
|
371
|
+
.filter((value) => value && !isCaseReferenced(value)),
|
|
372
|
+
);
|
|
373
|
+
if (aliases.length) next.aliases = aliases;
|
|
374
|
+
else delete next.aliases;
|
|
375
|
+
next.keywords = cleanTextList(next.keywords);
|
|
376
|
+
next.steps = uniqueByStable(asArray(next.steps).map(cleanActionStep).filter(Boolean));
|
|
377
|
+
if (Array.isArray(next.notes)) next.notes = cleanTextList(next.notes);
|
|
378
|
+
if (!next.title && !next.text && !next.id) return null;
|
|
379
|
+
return next;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function dedupeActions(actions) {
|
|
383
|
+
const map = new Map();
|
|
384
|
+
for (const action of actions || []) {
|
|
385
|
+
if (!action) continue;
|
|
386
|
+
const key = action.id || stableJson(action);
|
|
387
|
+
const prev = map.get(key);
|
|
388
|
+
if (!prev) {
|
|
389
|
+
map.set(key, action);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
map.set(key, {
|
|
393
|
+
...prev,
|
|
394
|
+
...action,
|
|
395
|
+
title: prev.title || action.title,
|
|
396
|
+
keywords: cleanTextList([...(prev.keywords || []), ...(action.keywords || [])]),
|
|
397
|
+
steps: uniqueByStable([...(prev.steps || []), ...(action.steps || [])]),
|
|
398
|
+
aliases: uniqueStrings([...(prev.aliases || []), ...(action.aliases || [])]),
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
return [...map.values()];
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function cleanPage(page, { documents, at }) {
|
|
405
|
+
const notes = asArray(page.notes);
|
|
406
|
+
const provenanceDocs = new Set(asArray(page.provenance?.documents));
|
|
407
|
+
const evidenceNotes = [];
|
|
408
|
+
const canonicalNotes = [];
|
|
409
|
+
for (const note of notes) {
|
|
410
|
+
const text = String(note ?? '').trim();
|
|
411
|
+
if (!text) continue;
|
|
412
|
+
const source = /^来源文档[::]\s*(.+)$/.exec(text);
|
|
413
|
+
if (source) {
|
|
414
|
+
provenanceDocs.add(source[1].trim());
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (isCaseReferenced(text) || looksLikeEvidenceStatement(text)) evidenceNotes.push(text);
|
|
418
|
+
else canonicalNotes.push(text);
|
|
419
|
+
}
|
|
420
|
+
for (const doc of documents) {
|
|
421
|
+
if (doc?.title) provenanceDocs.add(doc.title);
|
|
422
|
+
}
|
|
423
|
+
const feedbacks = asArray(page.feedbacks);
|
|
424
|
+
const sources = asArray(page.sources);
|
|
425
|
+
const observations = asArray(page.observations);
|
|
426
|
+
const next = { ...page };
|
|
427
|
+
delete next.feedbacks;
|
|
428
|
+
delete next.sources;
|
|
429
|
+
delete next.observations;
|
|
430
|
+
next.title = cleanCanonicalText(page.title || '');
|
|
431
|
+
if (!next.title || looksLikeUrlTitle(page.title)) {
|
|
432
|
+
const fromUrl = pageTitleFromUrl(page.url) ||
|
|
433
|
+
pageTitleFromUrl(observations.find((item) => item?.url)?.url);
|
|
434
|
+
if (fromUrl) next.title = fromUrl;
|
|
435
|
+
}
|
|
436
|
+
if (!next.title && page.title) next.title = String(page.title).trim();
|
|
437
|
+
if (next.title) {
|
|
438
|
+
const cleanedTitle = stripPageCodePrefix(next.title) || next.title;
|
|
439
|
+
// 去编号后仍保留原始写法,文档里按「P1a执行记录列表」引用的地方还能命中;
|
|
440
|
+
// 去编号后只剩「列表/详情」的噪声页不补别名,否则会挡住 stub-noise 归档。
|
|
441
|
+
if (cleanedTitle !== next.title && !looksLikeStubTitleNoise(cleanedTitle)) {
|
|
442
|
+
next.aliases = uniqueStrings([...(next.aliases || []), next.title]);
|
|
443
|
+
}
|
|
444
|
+
next.title = cleanedTitle;
|
|
445
|
+
}
|
|
446
|
+
next.url = canonicalPageUrl(page.url);
|
|
447
|
+
next.notes = cleanTextList(canonicalNotes, { max: MAX_NOTES });
|
|
448
|
+
next.keywords = cleanTextList(page.keywords);
|
|
449
|
+
next.texts = cleanTextList(page.texts);
|
|
450
|
+
next.menu = cleanTextList(page.menu);
|
|
451
|
+
next.elementHints = cleanTextList(page.elementHints, { max: MAX_HINTS });
|
|
452
|
+
next.assertionHints = cleanTextList(page.assertionHints, { max: MAX_HINTS });
|
|
453
|
+
next.actions = dedupeActions(asArray(page.actions).map(cleanAction).filter(Boolean));
|
|
454
|
+
if (next.table && Array.isArray(next.table.headers)) {
|
|
455
|
+
next.table = { ...next.table, headers: cleanTextList(next.table.headers) };
|
|
456
|
+
}
|
|
457
|
+
if (provenanceDocs.size) next.provenance = { ...(page.provenance || {}), documents: [...provenanceDocs] };
|
|
458
|
+
const observationEvent =
|
|
459
|
+
sources.length || observations.length
|
|
460
|
+
? {
|
|
461
|
+
id: 'page-observation:' + (page.id || normalizeKey(page.title)),
|
|
462
|
+
kind: 'page-observation',
|
|
463
|
+
at,
|
|
464
|
+
pageId: page.id || '',
|
|
465
|
+
title: next.title || '',
|
|
466
|
+
sources: sources.slice(-50),
|
|
467
|
+
observations: observations.slice(-50),
|
|
468
|
+
}
|
|
469
|
+
: null;
|
|
470
|
+
return { page: next, evidenceNotes, feedbacks, observationEvent };
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function mergePageRecords(base, duplicate) {
|
|
474
|
+
const merged = { ...base };
|
|
475
|
+
merged.url = canonicalPageUrl(base.url || duplicate.url);
|
|
476
|
+
merged.urlName = base.urlName || duplicate.urlName;
|
|
477
|
+
const titles = [base.title, duplicate.title].filter(Boolean);
|
|
478
|
+
// 优先人类可读标题:不取 URL 转写,避免与 urlName 同名的机械标题,并去掉叠写的「详情页详情」。
|
|
479
|
+
const titleRank = (title) => {
|
|
480
|
+
let score = 0;
|
|
481
|
+
if (looksLikeUrlTitle(title)) score += 100;
|
|
482
|
+
if (merged.urlName && normalizeKey(title) === normalizeKey(merged.urlName)) score += 50;
|
|
483
|
+
if (/(?:列表页列表|详情页详情|页面列表|页面详情|页列表|页详情)$/u.test(title)) score += 30;
|
|
484
|
+
if (/[((]/.test(title)) score += 10;
|
|
485
|
+
return score;
|
|
486
|
+
};
|
|
487
|
+
const mergedTitle = [...titles].sort((a, b) => titleRank(a) - titleRank(b) || a.length - b.length)[0] || '';
|
|
488
|
+
merged.title = mergedTitle;
|
|
489
|
+
merged.aliases = uniqueStrings([
|
|
490
|
+
...(base.aliases || []),
|
|
491
|
+
...(duplicate.aliases || []),
|
|
492
|
+
...(duplicate.id && duplicate.id !== base.id ? [duplicate.id] : []),
|
|
493
|
+
// 合并后没被选中的标题也保留为别名,机械英文名与中文页面名都能再查到。
|
|
494
|
+
...(base.title && base.title !== mergedTitle ? [base.title] : []),
|
|
495
|
+
...(duplicate.title && duplicate.title !== mergedTitle ? [duplicate.title] : []),
|
|
496
|
+
]);
|
|
497
|
+
if (!merged.aliases.length) delete merged.aliases;
|
|
498
|
+
merged.keywords = cleanTextList([...(base.keywords || []), ...(duplicate.keywords || [])]);
|
|
499
|
+
merged.texts = cleanTextList([...(base.texts || []), ...(duplicate.texts || [])]);
|
|
500
|
+
merged.menu = cleanTextList([...(base.menu || []), ...(duplicate.menu || [])]);
|
|
501
|
+
merged.notes = cleanTextList([...(base.notes || []), ...(duplicate.notes || [])], { max: MAX_NOTES });
|
|
502
|
+
merged.elementHints = cleanTextList([...(base.elementHints || []), ...(duplicate.elementHints || [])], { max: MAX_HINTS });
|
|
503
|
+
merged.assertionHints = cleanTextList([...(base.assertionHints || []), ...(duplicate.assertionHints || [])], { max: MAX_HINTS });
|
|
504
|
+
merged.regions = { ...(duplicate.regions || {}), ...(base.regions || {}) };
|
|
505
|
+
merged.table = { ...(duplicate.table || {}), ...(base.table || {}) };
|
|
506
|
+
merged.table.headers = cleanTextList([...(base.table?.headers || []), ...(duplicate.table?.headers || [])]);
|
|
507
|
+
merged.waits = {
|
|
508
|
+
...(duplicate.waits || {}),
|
|
509
|
+
...(base.waits || {}),
|
|
510
|
+
loadMs: Math.max(Number(base.waits?.loadMs) || 0, Number(duplicate.waits?.loadMs) || 0) || undefined,
|
|
511
|
+
settleMs: Math.max(Number(base.waits?.settleMs) || 0, Number(duplicate.waits?.settleMs) || 0) || undefined,
|
|
512
|
+
};
|
|
513
|
+
const actions = [...(base.actions || [])];
|
|
514
|
+
for (const action of duplicate.actions || []) {
|
|
515
|
+
const index = actions.findIndex((item) => item.id && item.id === action.id);
|
|
516
|
+
if (index < 0) actions.push(action);
|
|
517
|
+
else {
|
|
518
|
+
actions[index] = { ...action, ...actions[index] };
|
|
519
|
+
actions[index].keywords = cleanTextList([...(actions[index].keywords || []), ...(action.keywords || [])]);
|
|
520
|
+
actions[index].steps = uniqueByStable([...(actions[index].steps || []), ...(action.steps || [])]);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
merged.actions = dedupeActions(actions);
|
|
524
|
+
merged.confidence = Math.max(Number(base.confidence) || 0, Number(duplicate.confidence) || 0);
|
|
525
|
+
merged.provenance = {
|
|
526
|
+
...(base.provenance || {}),
|
|
527
|
+
documents: uniqueStrings([...(base.provenance?.documents || []), ...(duplicate.provenance?.documents || [])]),
|
|
528
|
+
};
|
|
529
|
+
merged.source = uniqueStrings([...(asArray(base.source)), ...(asArray(duplicate.source))]);
|
|
530
|
+
return merged;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function mergeProcessRecords(base, duplicate) {
|
|
534
|
+
const merged = { ...base };
|
|
535
|
+
merged.name = base.name || duplicate.name;
|
|
536
|
+
merged.keywords = uniqueStrings([...(base.keywords || []), ...(duplicate.keywords || [])]);
|
|
537
|
+
merged.steps = uniqueStrings([...(base.steps || []).map(stepText), ...(duplicate.steps || []).map(stepText)]);
|
|
538
|
+
merged.notes = uniqueStrings([...(base.notes || []), ...(duplicate.notes || [])]).slice(-MAX_NOTES);
|
|
539
|
+
merged.confidence = Math.max(Number(base.confidence) || 0, Number(duplicate.confidence) || 0);
|
|
540
|
+
merged.source = uniqueStrings([...(asArray(base.source)), ...(asArray(duplicate.source))]);
|
|
541
|
+
return merged;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function processKind(record, documents) {
|
|
545
|
+
const steps = asArray(record.steps).map(stepText).map((step) => String(step || '').trim()).filter(Boolean);
|
|
546
|
+
if (record.caseId) return { kind: 'experience' };
|
|
547
|
+
if (/^studio-/i.test(String(record.id || ''))) return { kind: 'experience' };
|
|
548
|
+
if (asArray(record.sources).some((item) => item && (item.runDir || item.caseId))) return { kind: 'experience' };
|
|
549
|
+
if (record.source && typeof record.source === 'object' && (record.source.caseId || record.source.kind === 'studio-batch')) {
|
|
550
|
+
return { kind: 'experience' };
|
|
551
|
+
}
|
|
552
|
+
if (documents.length && documents.every((doc) => isEvidenceDocument(doc.kind))) return { kind: 'archive', reason: 'evidence-document' };
|
|
553
|
+
const ruleSteps = steps.filter((step) => looksLikeRule(step) && !looksLikeActionStep(step));
|
|
554
|
+
const actionSteps = steps.filter((step) => looksLikeActionStep(step));
|
|
555
|
+
if (looksLikeProcessHeading(record.name) || looksLikeRunArtifact({ id: record.id, title: record.name })) {
|
|
556
|
+
if (ruleSteps.length) return { kind: 'rules', rules: steps.filter((step) => !looksLikeActionStep(step)) };
|
|
557
|
+
return {
|
|
558
|
+
kind: 'archive',
|
|
559
|
+
reason: looksLikeRunArtifact({ id: record.id, title: record.name }) ? 'run-artifact' : 'heading-noise',
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
if (steps.length < 2) return { kind: 'archive', reason: 'too-few-steps' };
|
|
563
|
+
if (actionSteps.length >= 2 && actionSteps.length >= ruleSteps.length) return { kind: 'canonical' };
|
|
564
|
+
if (ruleSteps.length) return { kind: 'rules', rules: steps.filter((step) => !looksLikeActionStep(step)) };
|
|
565
|
+
return { kind: 'archive', reason: 'not-executable' };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function experienceFromProcess(record, now) {
|
|
569
|
+
return {
|
|
570
|
+
id: 'process-experience:' + (record.id || record.caseId || record.name),
|
|
571
|
+
kind: 'case-experience',
|
|
572
|
+
at: now,
|
|
573
|
+
caseId: record.caseId || '',
|
|
574
|
+
name: record.name || record.id || '',
|
|
575
|
+
steps: asArray(record.steps).map(stepText).filter(Boolean),
|
|
576
|
+
corrections: asArray(record.corrections),
|
|
577
|
+
reviews: asArray(record.reviews),
|
|
578
|
+
notes: asArray(record.notes),
|
|
579
|
+
sources: asArray(record.sources),
|
|
580
|
+
confidence: record.confidence ?? null,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function cleanRule(raw, { evidenceSource = false } = {}) {
|
|
585
|
+
const text = String(raw ?? '').replace(/\s+/g, ' ').trim();
|
|
586
|
+
if (!text) return { drop: true };
|
|
587
|
+
if (!isCaseReferenced(text)) {
|
|
588
|
+
if (evidenceSource && looksLikeEvidenceStatement(text)) return { drop: true, reason: 'evidence-statement' };
|
|
589
|
+
return { text };
|
|
590
|
+
}
|
|
591
|
+
const cleaned = stripInstanceRefs(text);
|
|
592
|
+
if (!cleaned || isCaseReferenced(cleaned) || cleaned.length < 10) return { drop: true };
|
|
593
|
+
if (looksLikeEvidenceStatement(cleaned)) return { drop: true, reason: 'evidence-statement' };
|
|
594
|
+
return { text: cleaned, changed: true };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function rulesEntryForDocument(doc) {
|
|
598
|
+
const documentTitle = doc?.title || '业务规则';
|
|
599
|
+
const docSlug = slug(documentTitle) || 'business';
|
|
600
|
+
return {
|
|
601
|
+
id: 'doc-' + docSlug + '-rules-1',
|
|
602
|
+
title: doc ? documentTitle + ' 业务规则' : '业务规则',
|
|
603
|
+
rules: [],
|
|
604
|
+
source: ['doc-learn', 'consolidate'],
|
|
605
|
+
confidence: 0.55,
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function normalizeRoleEntry(entry) {
|
|
610
|
+
if (typeof entry === 'string') return entry.trim() ? { name: entry.trim(), source: '' } : null;
|
|
611
|
+
if (entry && typeof entry === 'object' && entry.name) return { ...entry, name: String(entry.name).trim() };
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function normalizeGlossaryEntry(entry) {
|
|
616
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
617
|
+
const term = String(entry.term || entry.name || '').trim();
|
|
618
|
+
const definition = String(entry.definition || entry.desc || '').trim();
|
|
619
|
+
return term && definition ? { term, definition, source: entry.source || '' } : null;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
function mergeNamedList(list, entry, keyOf, mergeItem) {
|
|
623
|
+
const key = keyOf(entry);
|
|
624
|
+
if (!key) return;
|
|
625
|
+
const index = list.findIndex((item) => keyOf(item) === key);
|
|
626
|
+
if (index < 0) list.push(entry);
|
|
627
|
+
else list[index] = mergeItem ? mergeItem(list[index], entry) : { ...list[index], ...entry };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function collectSystem(system, documents) {
|
|
631
|
+
const evidenceSources = new Set(
|
|
632
|
+
documents
|
|
633
|
+
.filter((doc) => doc.learnable === false || isEvidenceDocument(doc.kind))
|
|
634
|
+
.map((doc) => normalizeKey(doc.title || doc.id))
|
|
635
|
+
.filter(Boolean),
|
|
636
|
+
);
|
|
637
|
+
const sourceKeys = (source) =>
|
|
638
|
+
asArray(source)
|
|
639
|
+
.flatMap((item) => (typeof item === 'string' ? item.split(/[,,、;;]/) : []))
|
|
640
|
+
.map(normalizeKey)
|
|
641
|
+
.filter(Boolean);
|
|
642
|
+
const fromEvidenceDoc = (source) => {
|
|
643
|
+
const keys = sourceKeys(source);
|
|
644
|
+
return keys.some((key) =>
|
|
645
|
+
[...evidenceSources].some((title) => title === key || (title.length >= 2 && key.includes(title))),
|
|
646
|
+
);
|
|
647
|
+
};
|
|
648
|
+
const roles = [];
|
|
649
|
+
for (const raw of asArray(system.roles)) {
|
|
650
|
+
const entry = normalizeRoleEntry(raw);
|
|
651
|
+
if (!entry) continue;
|
|
652
|
+
entry.name = cleanRoleName(entry.name);
|
|
653
|
+
if (!entry.name || looksLikeSystemLabel(entry.name) || fromEvidenceDoc(entry.source)) continue;
|
|
654
|
+
mergeNamedList(
|
|
655
|
+
roles,
|
|
656
|
+
entry,
|
|
657
|
+
(item) => normalizeKey(item.name),
|
|
658
|
+
(a, b) => ({ ...a, note: a.note || b.note, source: a.source || b.source }),
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
const glossary = asArray(system.glossary)
|
|
662
|
+
.map(normalizeGlossaryEntry)
|
|
663
|
+
.filter(
|
|
664
|
+
(entry) =>
|
|
665
|
+
entry &&
|
|
666
|
+
!looksLikeSystemLabel(entry.term) &&
|
|
667
|
+
entry.definition.length >= 4 &&
|
|
668
|
+
!fromEvidenceDoc(entry.source),
|
|
669
|
+
);
|
|
670
|
+
const permissions = asArray(system.permissions)
|
|
671
|
+
.map((item) => {
|
|
672
|
+
if (!item || typeof item !== 'object') return null;
|
|
673
|
+
const rawRole = String(item.role || '').trim();
|
|
674
|
+
const role = cleanRoleName(rawRole);
|
|
675
|
+
const action = String(item.action || item.note || '').trim();
|
|
676
|
+
if (!action || (rawRole && !role) || (role && looksLikeSystemLabel(role)) || looksLikeSystemLabel(action, { max: 60 })) return null;
|
|
677
|
+
return { ...item, role, action, source: item.source || '' };
|
|
678
|
+
})
|
|
679
|
+
.filter((item) => item && !fromEvidenceDoc(item.source));
|
|
680
|
+
for (const doc of documents) {
|
|
681
|
+
if (doc.learnable === false || isEvidenceDocument(doc.kind)) continue;
|
|
682
|
+
for (const role of asArray(doc.roles)) {
|
|
683
|
+
const normalized = normalizeRoleEntry(role);
|
|
684
|
+
if (!normalized) continue;
|
|
685
|
+
normalized.name = cleanRoleName(normalized.name);
|
|
686
|
+
if (!normalized.name || looksLikeSystemLabel(normalized.name)) continue;
|
|
687
|
+
mergeNamedList(
|
|
688
|
+
roles,
|
|
689
|
+
{ ...normalized, source: normalized.source || doc.title || '' },
|
|
690
|
+
(item) => normalizeKey(item.name),
|
|
691
|
+
(a, b) => ({ ...a, note: a.note || b.note, source: a.source || b.source }),
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
for (const term of asArray(doc.glossary)) {
|
|
695
|
+
const normalized = normalizeGlossaryEntry(term);
|
|
696
|
+
if (!normalized || looksLikeSystemLabel(normalized.term) || normalized.definition.length < 4) continue;
|
|
697
|
+
mergeNamedList(
|
|
698
|
+
glossary,
|
|
699
|
+
{ ...normalized, source: normalized.source || doc.title || '' },
|
|
700
|
+
(item) => normalizeKey(item.term),
|
|
701
|
+
(a, b) => ({ ...a, definition: a.definition || b.definition, source: a.source || b.source }),
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
for (const permission of asArray(doc.permissions)) {
|
|
705
|
+
if (!permission || typeof permission !== 'object') continue;
|
|
706
|
+
const rawRole = String(permission.role || '').trim();
|
|
707
|
+
const role = cleanRoleName(rawRole);
|
|
708
|
+
if (rawRole && !role) continue;
|
|
709
|
+
const entry = {
|
|
710
|
+
role,
|
|
711
|
+
action: String(permission.action || permission.note || '').trim(),
|
|
712
|
+
allowed: permission.allowed === undefined ? null : permission.allowed,
|
|
713
|
+
source: doc.title || '',
|
|
714
|
+
};
|
|
715
|
+
if (!entry.action || (entry.role && looksLikeSystemLabel(entry.role)) || looksLikeSystemLabel(entry.action, { max: 60 })) continue;
|
|
716
|
+
mergeNamedList(
|
|
717
|
+
permissions,
|
|
718
|
+
entry,
|
|
719
|
+
(item) => normalizeKey(`${item.role}|${item.action}|${item.allowed}`),
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
const notes = uniqueStrings(
|
|
724
|
+
asArray(system.notes)
|
|
725
|
+
.map((note) => (isCaseReferenced(note) ? stripInstanceRefs(note) : String(note ?? '')).trim())
|
|
726
|
+
.filter((note) => note && !looksLikeEvidenceStatement(note)),
|
|
727
|
+
);
|
|
728
|
+
return { ...system, roles, permissions, glossary, notes };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function updateDocuments(knowledge, { documentTexts = {} } = {}) {
|
|
732
|
+
const documents = asArray(knowledge?.documents?.documents).map((doc) => {
|
|
733
|
+
const text = documentTexts[doc.id];
|
|
734
|
+
const kind = doc.kind || classifyDocumentKind({ title: doc.title, content: text || '' });
|
|
735
|
+
const learnable = isLearnableDocument(kind);
|
|
736
|
+
const next = { ...doc, kind, learnable };
|
|
737
|
+
if (!learnable) {
|
|
738
|
+
// 测试报告/会议纪要只能作为证据:不在正典文档里保留字段、状态、角色等结构。
|
|
739
|
+
for (const field of ['fields', 'statuses', 'transitions', 'roles', 'permissions', 'glossary', 'summary']) {
|
|
740
|
+
delete next[field];
|
|
741
|
+
}
|
|
742
|
+
return next;
|
|
743
|
+
}
|
|
744
|
+
if (text) {
|
|
745
|
+
const structure = extractDocumentStructure(text, { title: doc.title });
|
|
746
|
+
const merged = mergeDocumentStructure(next, structure);
|
|
747
|
+
for (const field of ['fields', 'statuses', 'transitions', 'roles', 'permissions', 'glossary']) {
|
|
748
|
+
if (merged[field].length) next[field] = merged[field];
|
|
749
|
+
else delete next[field];
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
return next;
|
|
753
|
+
});
|
|
754
|
+
return { ...knowledge.documents, documents };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* 执行一遍页面归并(同名分组、入口补并、存根认领、术语映射、存根互并)。
|
|
759
|
+
* 归并会让来源变宽或结构补齐,使上一遍被挡下的页面在下一遍变得合法;
|
|
760
|
+
* 调用方反复执行到整遍零合并,即可保证一次整理到达不动点。
|
|
761
|
+
*/
|
|
762
|
+
function mergePagesOnce(pages, { stats, actions, systemUrls, glossaryIndex }) {
|
|
763
|
+
for (const page of pages) page.status = isStructuredPage(page) ? 'canonical' : 'stub';
|
|
764
|
+
const mergedAtStart = stats.pages.merged;
|
|
765
|
+
|
|
766
|
+
const pageGroups = new Map();
|
|
767
|
+
for (const page of pages) {
|
|
768
|
+
const key = pageKey(page, systemUrls);
|
|
769
|
+
if (!pageGroups.has(key)) pageGroups.set(key, []);
|
|
770
|
+
pageGroups.get(key).push(page);
|
|
771
|
+
}
|
|
772
|
+
pages = [];
|
|
773
|
+
for (const group of pageGroups.values()) {
|
|
774
|
+
const sorted = [...group].sort((a, b) => {
|
|
775
|
+
if (a.status === 'stub' && b.status === 'stub') return stubTitleScore(a) - stubTitleScore(b);
|
|
776
|
+
return Number(stablePageId(b)) - Number(stablePageId(a)) || pageScore(b) - pageScore(a);
|
|
777
|
+
});
|
|
778
|
+
let base = sorted[0];
|
|
779
|
+
const unmerged = [];
|
|
780
|
+
const stubDuplicates = sorted.slice(1).filter((page) => page.status === 'stub');
|
|
781
|
+
const skipAmbiguousStubs = base.status !== 'stub' && ambiguousStubClaim(base, stubDuplicates);
|
|
782
|
+
for (const duplicate of sorted.slice(1)) {
|
|
783
|
+
if (duplicate.status === 'stub' && skipAmbiguousStubs) {
|
|
784
|
+
unmerged.push(duplicate);
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
if (base.status === 'stub' && duplicate.status === 'stub' && !sameStubSource(base, duplicate)) {
|
|
788
|
+
unmerged.push(duplicate);
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
// 同名不代表同页;双方都有来源文档却没有交集时不合并(不同模块会有同名页面)。
|
|
792
|
+
if (sourceConflict(base, duplicate)) {
|
|
793
|
+
unmerged.push(duplicate);
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
base = mergePageRecords(base, duplicate);
|
|
797
|
+
stats.pages.merged += 1;
|
|
798
|
+
if (actions.length < 200) actions.push(`页面 ${duplicate.id} 合并到 ${base.id}`);
|
|
799
|
+
}
|
|
800
|
+
pages.push(base, ...unmerged);
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// 同一页面可能从相对/绝对路由或不同入口分别观察;标题相同且共享长页面 ID 时再合并一次。
|
|
804
|
+
const titleGroups = new Map();
|
|
805
|
+
const mergedAway = new Set();
|
|
806
|
+
for (let index = 0; index < pages.length; index += 1) {
|
|
807
|
+
const page = pages[index];
|
|
808
|
+
const key = normalizeKey(page.title);
|
|
809
|
+
if (!key || key.length < 3) continue;
|
|
810
|
+
const tokens = longNumericTokens(page.url);
|
|
811
|
+
if (!tokens.size) continue;
|
|
812
|
+
const existing = titleGroups.get(key);
|
|
813
|
+
if (!existing) {
|
|
814
|
+
titleGroups.set(key, { index, tokens, page });
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
if (!sharesLongNumericToken(existing.tokens, tokens)) continue;
|
|
818
|
+
const merged = mergePageRecords(existing.page, page);
|
|
819
|
+
pages[existing.index] = merged;
|
|
820
|
+
existing.page = merged;
|
|
821
|
+
existing.tokens = new Set([...existing.tokens, ...tokens]);
|
|
822
|
+
mergedAway.add(index);
|
|
823
|
+
stats.pages.merged += 1;
|
|
824
|
+
if (actions.length < 200) actions.push(`页面 ${page.id} 合并到 ${existing.page.id}`);
|
|
825
|
+
}
|
|
826
|
+
pages = pages.filter((_, index) => !mergedAway.has(index));
|
|
827
|
+
// 占位页标题若与唯一正典页面归一化相同,并入正典补别名;结构以正典为准。
|
|
828
|
+
pages = claimStubsIntoCanonical(pages, { stats, actions });
|
|
829
|
+
// 正典页标题有时是系统生成的英文机械名(purchaseTaskList),文档存根却是中文页面名。
|
|
830
|
+
// 用系统术语表(采购任务 → Purchase Task)建立对应,只在唯一正典页、唯一存根时合并。
|
|
831
|
+
if (glossaryIndex.size) {
|
|
832
|
+
const canonicalByCrossKey = new Map();
|
|
833
|
+
pages.forEach((page, pageIndex) => {
|
|
834
|
+
const hint = crossLanguagePageHint(page, glossaryIndex);
|
|
835
|
+
if (!hint) return;
|
|
836
|
+
if (!canonicalByCrossKey.has(hint.key)) canonicalByCrossKey.set(hint.key, []);
|
|
837
|
+
canonicalByCrossKey.get(hint.key).push({ index: pageIndex, hint });
|
|
838
|
+
});
|
|
839
|
+
const stubByCrossKey = new Map();
|
|
840
|
+
pages.forEach((page, pageIndex) => {
|
|
841
|
+
if (page.status !== 'stub' || page.url || page.urlName) return;
|
|
842
|
+
const key = stubPageTitleKey(page.title);
|
|
843
|
+
if (!key) return;
|
|
844
|
+
if (!stubByCrossKey.has(key)) stubByCrossKey.set(key, []);
|
|
845
|
+
stubByCrossKey.get(key).push(pageIndex);
|
|
846
|
+
});
|
|
847
|
+
const mergedCrossLanguage = new Set();
|
|
848
|
+
for (const [key, candidates] of canonicalByCrossKey) {
|
|
849
|
+
const stubs = stubByCrossKey.get(key) || [];
|
|
850
|
+
if (candidates.length !== 1 || stubs.length !== 1) continue;
|
|
851
|
+
const baseIndex = candidates[0].index;
|
|
852
|
+
const duplicateIndex = stubs[0];
|
|
853
|
+
// 术语只能证明名称对应;双方都有来源文档但无交集时仍视为不同模块页面。
|
|
854
|
+
if (sourceConflict(pages[baseIndex], pages[duplicateIndex])) continue;
|
|
855
|
+
pages[baseIndex] = mergePageRecords(pages[baseIndex], pages[duplicateIndex]);
|
|
856
|
+
mergedCrossLanguage.add(duplicateIndex);
|
|
857
|
+
stats.pages.merged += 1;
|
|
858
|
+
if (actions.length < 200) {
|
|
859
|
+
actions.push(`页面 ${pages[duplicateIndex].id} 合并到 ${pages[baseIndex].id}(术语 ${candidates[0].hint.term})`);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
pages = pages.filter((_, index) => !mergedCrossLanguage.has(index));
|
|
863
|
+
}
|
|
864
|
+
// 文档派生的占位页常同时写成「P1-服务定义列表页(列表页)」和「服务定义列表」。
|
|
865
|
+
// 两者都还没有 URL/结构时按归一化标题合并,保留干净名字与编码 id 作为别名。
|
|
866
|
+
const stubGroups = new Map();
|
|
867
|
+
pages.forEach((page, pageIndex) => {
|
|
868
|
+
if (page.status !== 'stub' || page.url || page.urlName) return;
|
|
869
|
+
const key = stubPageTitleKey(page.title);
|
|
870
|
+
if (!key) return;
|
|
871
|
+
if (!stubGroups.has(key)) stubGroups.set(key, []);
|
|
872
|
+
stubGroups.get(key).push(pageIndex);
|
|
873
|
+
});
|
|
874
|
+
const mergedStubs = new Set();
|
|
875
|
+
for (const group of stubGroups.values()) {
|
|
876
|
+
if (group.length < 2) continue;
|
|
877
|
+
group.sort((a, b) => stubTitleScore(pages[a]) - stubTitleScore(pages[b]) || a - b);
|
|
878
|
+
for (let i = 0; i < group.length; i += 1) {
|
|
879
|
+
const baseIndex = group[i];
|
|
880
|
+
if (mergedStubs.has(baseIndex)) continue;
|
|
881
|
+
for (let j = i + 1; j < group.length; j += 1) {
|
|
882
|
+
const duplicateIndex = group[j];
|
|
883
|
+
if (mergedStubs.has(duplicateIndex)) continue;
|
|
884
|
+
if (!sameStubSource(pages[baseIndex], pages[duplicateIndex])) continue;
|
|
885
|
+
pages[baseIndex] = mergePageRecords(pages[baseIndex], pages[duplicateIndex]);
|
|
886
|
+
mergedStubs.add(duplicateIndex);
|
|
887
|
+
stats.pages.merged += 1;
|
|
888
|
+
if (actions.length < 200) actions.push(`页面 ${pages[duplicateIndex].id} 合并到 ${pages[baseIndex].id}(存根同名)`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
pages = pages.filter((_, index) => !mergedStubs.has(index));
|
|
893
|
+
// 存根合到一起后可能出现唯一组,此时正典方能确认认领。
|
|
894
|
+
pages = claimStubsIntoCanonical(pages, { stats, actions });
|
|
895
|
+
return { pages, merged: stats.pages.merged - mergedAtStart };
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* 生成合并计划(纯函数)。`documentTexts` 以文档 id 为键,用于类型判定与结构抽取;
|
|
900
|
+
* `learnings` 传入证据学习事件时,计划会一并给出重复学习去重结果;
|
|
901
|
+
* `existingFacts` 传入正典事实时,计划会按稳定键归并候选事实并给出冲突/废弃结果。
|
|
902
|
+
*/
|
|
903
|
+
export function planConsolidation(knowledge = {}, { documentTexts = {}, learnings = null, existingFacts = [], now = '' } = {}) {
|
|
904
|
+
const at = now || nowIso();
|
|
905
|
+
const index = documentIndex(knowledge);
|
|
906
|
+
const nextDocumentsDoc = updateDocuments(knowledge, { documentTexts });
|
|
907
|
+
const documents = nextDocumentsDoc.documents;
|
|
908
|
+
for (const doc of documents) {
|
|
909
|
+
index.byId.set(String(doc.id), doc);
|
|
910
|
+
index.byTitle.set(normalizeKey(doc.title), doc);
|
|
911
|
+
index.bySlug.set(slug(String(doc.title || doc.id)), doc);
|
|
912
|
+
}
|
|
913
|
+
// 页面合并与最终系统维度共用同一份清洗结果;术语表用于英文机械标题与中文存根的对应。
|
|
914
|
+
const system = collectSystem(knowledge?.system || {}, documents);
|
|
915
|
+
|
|
916
|
+
const archive = { pages: [], processes: [], business: [], rules: [], notes: [], feedbacks: [], observations: [] };
|
|
917
|
+
const experiences = [];
|
|
918
|
+
const actions = [];
|
|
919
|
+
const stats = {
|
|
920
|
+
documents: { total: documents.length, kinds: {}, withStructure: 0, fields: 0, statuses: 0, roles: 0, permissions: 0, glossary: 0 },
|
|
921
|
+
pages: { before: 0, after: 0, merged: 0, archived: 0, notesToEvidence: 0, feedbacksToEvidence: 0, observationsToEvidence: 0, stubs: 0 },
|
|
922
|
+
processes: { before: 0, after: 0, merged: 0, archived: 0, reclassifiedRules: 0, experiences: 0 },
|
|
923
|
+
business: { before: 0, after: 0, rulesBefore: 0, rulesAfter: 0, rulesCleaned: 0, rulesDropped: 0, entriesDropped: 0, reclassifiedRules: 0 },
|
|
924
|
+
system: { roles: 0, permissions: 0, glossary: 0 },
|
|
925
|
+
experiences: 0,
|
|
926
|
+
learnings: { before: 0, after: 0, duplicates: 0, keyed: 0 },
|
|
927
|
+
};
|
|
928
|
+
for (const doc of documents) {
|
|
929
|
+
stats.documents.kinds[doc.kind] = (stats.documents.kinds[doc.kind] || 0) + 1;
|
|
930
|
+
if ((doc.fields || []).length || (doc.statuses || []).length) stats.documents.withStructure += 1;
|
|
931
|
+
stats.documents.fields += (doc.fields || []).length;
|
|
932
|
+
stats.documents.statuses += (doc.statuses || []).length;
|
|
933
|
+
stats.documents.roles += (doc.roles || []).length;
|
|
934
|
+
stats.documents.permissions += (doc.permissions || []).length;
|
|
935
|
+
stats.documents.glossary += (doc.glossary || []).length;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// 页面:分流运行产物/标题噪声,清理实例引用与反馈,再按 URL/标题合并。
|
|
939
|
+
const pageRecords = [];
|
|
940
|
+
for (const page of asArray(knowledge?.pages?.pages)) {
|
|
941
|
+
stats.pages.before += 1;
|
|
942
|
+
const docs = documentsForRecord(page, index);
|
|
943
|
+
const cleaned = cleanPage(page, { documents: docs, at });
|
|
944
|
+
if (cleaned.evidenceNotes.length) {
|
|
945
|
+
stats.pages.notesToEvidence += cleaned.evidenceNotes.length;
|
|
946
|
+
archive.notes.push({ pageId: page.id, notes: cleaned.evidenceNotes });
|
|
947
|
+
experiences.push({
|
|
948
|
+
id: 'page-notes:' + (page.id || normalizeKey(page.title)),
|
|
949
|
+
kind: 'page-note',
|
|
950
|
+
at,
|
|
951
|
+
pageId: page.id || '',
|
|
952
|
+
notes: cleaned.evidenceNotes,
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
if (cleaned.feedbacks.length) {
|
|
956
|
+
stats.pages.feedbacksToEvidence += cleaned.feedbacks.length;
|
|
957
|
+
archive.feedbacks.push({ pageId: page.id, feedbacks: cleaned.feedbacks });
|
|
958
|
+
experiences.push({
|
|
959
|
+
id: 'page-feedback:' + (page.id || normalizeKey(page.title)),
|
|
960
|
+
kind: 'page-feedback',
|
|
961
|
+
at,
|
|
962
|
+
pageId: page.id || '',
|
|
963
|
+
feedbacks: cleaned.feedbacks,
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
if (cleaned.observationEvent) {
|
|
967
|
+
stats.pages.observationsToEvidence += 1;
|
|
968
|
+
archive.observations.push({
|
|
969
|
+
pageId: page.id,
|
|
970
|
+
sources: cleaned.observationEvent.sources,
|
|
971
|
+
observations: cleaned.observationEvent.observations,
|
|
972
|
+
});
|
|
973
|
+
experiences.push(cleaned.observationEvent);
|
|
974
|
+
}
|
|
975
|
+
const next = cleaned.page;
|
|
976
|
+
next.status = isStructuredPage(next) ? 'canonical' : 'stub';
|
|
977
|
+
const reason = looksLikeRunArtifact(next)
|
|
978
|
+
? 'run-artifact'
|
|
979
|
+
: isNoisyStubPage(next)
|
|
980
|
+
? 'stub-noise'
|
|
981
|
+
: !isStructuredPage(next) && looksLikeHeadingNoise(next.title || next.id)
|
|
982
|
+
? 'heading-noise'
|
|
983
|
+
: !isStructuredPage(next) && docs.length && docs.every((doc) => isEvidenceDocument(doc.kind))
|
|
984
|
+
? 'evidence-document'
|
|
985
|
+
: '';
|
|
986
|
+
if (reason) {
|
|
987
|
+
stats.pages.archived += 1;
|
|
988
|
+
archive.pages.push({ ...next, archiveReason: reason });
|
|
989
|
+
if (actions.length < 200) actions.push(`页面 ${next.id} → 归档(${reason})`);
|
|
990
|
+
continue;
|
|
991
|
+
}
|
|
992
|
+
pageRecords.push(next);
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
const systemUrls = knowledge?.system?.urls || {};
|
|
996
|
+
const glossaryIndex = glossaryEnglishIndex(system);
|
|
997
|
+
let pages = pageRecords;
|
|
998
|
+
// 归并会互相让路:来源合并变宽、结构补齐后,上一遍被冲突或歧义挡下的页面可能变得合法。
|
|
999
|
+
// 重复执行到整遍零合并,保证一次整理到达不动点,与二次运行结果一致。
|
|
1000
|
+
for (;;) {
|
|
1001
|
+
const pass = mergePagesOnce(pages, { stats, actions, systemUrls, glossaryIndex });
|
|
1002
|
+
pages = pass.pages;
|
|
1003
|
+
if (!pass.merged) break;
|
|
1004
|
+
}
|
|
1005
|
+
// 合并后结构可能从重复页面补齐,占位页应转正典;存根数按最终页面统计。
|
|
1006
|
+
stats.pages.stubs = 0;
|
|
1007
|
+
for (const page of pages) {
|
|
1008
|
+
page.status = isStructuredPage(page) ? 'canonical' : 'stub';
|
|
1009
|
+
if (page.status === 'stub') stats.pages.stubs += 1;
|
|
1010
|
+
}
|
|
1011
|
+
stats.pages.after = pages.length;
|
|
1012
|
+
|
|
1013
|
+
// 流程:用例执行记录进证据;章节噪声按步骤性质转为业务规则或归档;其余合并。
|
|
1014
|
+
const processRecords = [];
|
|
1015
|
+
const businessFromProcesses = [];
|
|
1016
|
+
for (const process of asArray(knowledge?.processes?.processes)) {
|
|
1017
|
+
stats.processes.before += 1;
|
|
1018
|
+
const docs = documentsForRecord(process, index);
|
|
1019
|
+
const classified = processKind(process, docs);
|
|
1020
|
+
if (classified.kind === 'experience') {
|
|
1021
|
+
stats.processes.experiences += 1;
|
|
1022
|
+
experiences.push(experienceFromProcess(process, at));
|
|
1023
|
+
if (actions.length < 200) actions.push(`流程 ${process.id} → 执行经验`);
|
|
1024
|
+
continue;
|
|
1025
|
+
}
|
|
1026
|
+
if (classified.kind === 'archive') {
|
|
1027
|
+
stats.processes.archived += 1;
|
|
1028
|
+
archive.processes.push({ ...process, archiveReason: classified.reason });
|
|
1029
|
+
if (actions.length < 200) actions.push(`流程 ${process.id} → 归档(${classified.reason})`);
|
|
1030
|
+
continue;
|
|
1031
|
+
}
|
|
1032
|
+
if (classified.kind === 'rules') {
|
|
1033
|
+
const kept = [];
|
|
1034
|
+
for (const raw of classified.rules) {
|
|
1035
|
+
const result = cleanRule(raw);
|
|
1036
|
+
if (result.drop) stats.business.rulesDropped += 1;
|
|
1037
|
+
else kept.push(result.text);
|
|
1038
|
+
}
|
|
1039
|
+
if (kept.length) {
|
|
1040
|
+
businessFromProcesses.push({ doc: docs[0] || null, rules: kept });
|
|
1041
|
+
stats.processes.reclassifiedRules += kept.length;
|
|
1042
|
+
stats.business.reclassifiedRules += kept.length;
|
|
1043
|
+
if (actions.length < 200) actions.push(`流程 ${process.id} → 业务规则 ${kept.length} 条`);
|
|
1044
|
+
}
|
|
1045
|
+
stats.processes.archived += 1;
|
|
1046
|
+
archive.processes.push({ ...process, archiveReason: 'reclassified-rules' });
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
1049
|
+
const cleaned = {
|
|
1050
|
+
...process,
|
|
1051
|
+
name: isCaseReferenced(process.name) ? stripInstanceRefs(process.name) : process.name,
|
|
1052
|
+
steps: uniqueStrings(asArray(process.steps).map(stepText).map((step) => (isCaseReferenced(step) ? stripInstanceRefs(step) : step)).filter(Boolean)),
|
|
1053
|
+
notes: uniqueStrings(asArray(process.notes).map((note) => (isCaseReferenced(note) ? stripInstanceRefs(note) : note)).filter(Boolean)).slice(-MAX_NOTES),
|
|
1054
|
+
keywords: uniqueStrings(asArray(process.keywords)),
|
|
1055
|
+
};
|
|
1056
|
+
delete cleaned.caseId;
|
|
1057
|
+
delete cleaned.corrections;
|
|
1058
|
+
delete cleaned.reviews;
|
|
1059
|
+
delete cleaned.sources;
|
|
1060
|
+
delete cleaned.sourceDetails;
|
|
1061
|
+
if (!cleaned.name) {
|
|
1062
|
+
stats.processes.archived += 1;
|
|
1063
|
+
archive.processes.push({ ...process, archiveReason: 'empty-name' });
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
processRecords.push(cleaned);
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// 业务规则:去掉实例引用,跨条目去重;无法清洗的规则进证据。
|
|
1070
|
+
const businessEntries = asArray(knowledge?.business?.entries).map((entry) => ({ ...entry, rules: [...asArray(entry.rules)] }));
|
|
1071
|
+
const entryByDoc = new Map();
|
|
1072
|
+
for (const entry of businessEntries) {
|
|
1073
|
+
const doc = documentsForRecord(entry, index)[0];
|
|
1074
|
+
if (doc) entryByDoc.set(String(doc.id), entry);
|
|
1075
|
+
}
|
|
1076
|
+
for (const item of businessFromProcesses) {
|
|
1077
|
+
const doc = item.doc;
|
|
1078
|
+
const key = doc ? String(doc.id) : '__general__';
|
|
1079
|
+
let entry = entryByDoc.get(key);
|
|
1080
|
+
if (!entry) {
|
|
1081
|
+
entry = rulesEntryForDocument(doc);
|
|
1082
|
+
entryByDoc.set(key, entry);
|
|
1083
|
+
businessEntries.push(entry);
|
|
1084
|
+
}
|
|
1085
|
+
entry.rules.push(...item.rules);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
const seenRules = new Set();
|
|
1089
|
+
const business = [];
|
|
1090
|
+
for (const entry of businessEntries) {
|
|
1091
|
+
const entryDocs = documentsForRecord(entry, index);
|
|
1092
|
+
const evidenceSource = entryDocs.length > 0 && entryDocs.every((doc) => isEvidenceDocument(doc.kind));
|
|
1093
|
+
stats.business.before += 1;
|
|
1094
|
+
stats.business.rulesBefore += asArray(entry.rules).length;
|
|
1095
|
+
const kept = [];
|
|
1096
|
+
for (const raw of asArray(entry.rules)) {
|
|
1097
|
+
const result = cleanRule(raw, { evidenceSource });
|
|
1098
|
+
if (result.drop) {
|
|
1099
|
+
stats.business.rulesDropped += 1;
|
|
1100
|
+
archive.rules.push({ entryId: entry.id, rule: raw, reason: result.reason || 'instance-reference' });
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
if (result.changed) {
|
|
1104
|
+
stats.business.rulesCleaned += 1;
|
|
1105
|
+
archive.rules.push({ entryId: entry.id, rule: raw, cleaned: result.text });
|
|
1106
|
+
}
|
|
1107
|
+
const key = normalizeKey(result.text);
|
|
1108
|
+
if (!key || seenRules.has(key)) {
|
|
1109
|
+
stats.business.rulesDropped += 1;
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
seenRules.add(key);
|
|
1113
|
+
kept.push(result.text);
|
|
1114
|
+
}
|
|
1115
|
+
const cleanedEntry = {
|
|
1116
|
+
...entry,
|
|
1117
|
+
rules: kept,
|
|
1118
|
+
...(entry.source === undefined ? { source: 'consolidate' } : {}),
|
|
1119
|
+
};
|
|
1120
|
+
if (!kept.length) {
|
|
1121
|
+
stats.business.entriesDropped += 1;
|
|
1122
|
+
archive.business.push({ ...entry, archiveReason: 'no-rules' });
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
business.push(cleanedEntry);
|
|
1126
|
+
}
|
|
1127
|
+
stats.business.after = business.length;
|
|
1128
|
+
stats.business.rulesAfter = business.reduce((sum, entry) => sum + entry.rules.length, 0);
|
|
1129
|
+
|
|
1130
|
+
// 流程去重。
|
|
1131
|
+
const processGroups = new Map();
|
|
1132
|
+
for (const process of processRecords) {
|
|
1133
|
+
const key = normalizeKey(process.name) || String(process.id);
|
|
1134
|
+
if (!processGroups.has(key)) processGroups.set(key, []);
|
|
1135
|
+
processGroups.get(key).push(process);
|
|
1136
|
+
}
|
|
1137
|
+
const processes = [];
|
|
1138
|
+
for (const group of processGroups.values()) {
|
|
1139
|
+
const sorted = [...group].sort((a, b) => (Number(b.confidence) || 0) - (Number(a.confidence) || 0));
|
|
1140
|
+
let base = sorted[0];
|
|
1141
|
+
for (const duplicate of sorted.slice(1)) {
|
|
1142
|
+
base = mergeProcessRecords(base, duplicate);
|
|
1143
|
+
stats.processes.merged += 1;
|
|
1144
|
+
if (actions.length < 200) actions.push(`流程 ${duplicate.id} 合并到 ${base.id}`);
|
|
1145
|
+
}
|
|
1146
|
+
processes.push(base);
|
|
1147
|
+
}
|
|
1148
|
+
stats.processes.after = processes.length;
|
|
1149
|
+
|
|
1150
|
+
stats.system.roles = system.roles.length;
|
|
1151
|
+
stats.system.permissions = system.permissions.length;
|
|
1152
|
+
stats.system.glossary = system.glossary.length;
|
|
1153
|
+
stats.experiences = experiences.length;
|
|
1154
|
+
|
|
1155
|
+
const learningPlan = Array.isArray(learnings) ? compactLearnings(learnings) : null;
|
|
1156
|
+
if (learningPlan) {
|
|
1157
|
+
stats.learnings = learningPlan.stats;
|
|
1158
|
+
if (stats.learnings.duplicates && actions.length < 200) {
|
|
1159
|
+
actions.push(`证据学习去重 ${stats.learnings.duplicates} 条(保留同 run 同步骤最新一条)`);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
const next = {
|
|
1164
|
+
...knowledge,
|
|
1165
|
+
system,
|
|
1166
|
+
pages: { ...(knowledge.pages || {}), pages, updatedAt: changed(knowledge?.pages?.pages, pages) ? at : knowledge?.pages?.updatedAt || null },
|
|
1167
|
+
processes: { ...(knowledge.processes || {}), processes, updatedAt: changed(knowledge?.processes?.processes, processes) ? at : knowledge?.processes?.updatedAt || null },
|
|
1168
|
+
business: { ...(knowledge.business || {}), entries: business, updatedAt: changed(knowledge?.business?.entries, business) ? at : knowledge?.business?.updatedAt || null },
|
|
1169
|
+
documents: {
|
|
1170
|
+
...nextDocumentsDoc,
|
|
1171
|
+
updatedAt: changed(knowledge?.documents?.documents, documents) ? at : knowledge?.documents?.updatedAt || null,
|
|
1172
|
+
},
|
|
1173
|
+
};
|
|
1174
|
+
stats.summariesInvalidated = invalidateStaleSummaries(next);
|
|
1175
|
+
if (stats.summariesInvalidated && actions.length < 200) {
|
|
1176
|
+
actions.push(`清理过期摘要 ${stats.summariesInvalidated} 条,需重新运行 knowledge-summarize`);
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// 事实层:从清洗后的知识投影候选,按稳定键归并到正典事实(候选/已验证/冲突/废弃)。
|
|
1180
|
+
const factPlan = planFactConsolidation({ candidates: buildCandidates(next), existingFacts, now: at });
|
|
1181
|
+
stats.facts = factPlan.stats;
|
|
1182
|
+
if (factPlan.errors.length) {
|
|
1183
|
+
stats.facts.errors = factPlan.errors;
|
|
1184
|
+
if (actions.length < 200) actions.push(`事实候选丢弃 ${factPlan.errors.length} 条(实例引用或缺少证据)`);
|
|
1185
|
+
}
|
|
1186
|
+
if (factPlan.stats.created && actions.length < 200) actions.push(`新增正典事实 ${factPlan.stats.created} 条`);
|
|
1187
|
+
if (factPlan.stats.conflicted && actions.length < 200) actions.push(`事实冲突待裁决 ${factPlan.stats.conflicted} 组`);
|
|
1188
|
+
if (factPlan.stats.deprecated && actions.length < 200) actions.push(`事实连续未观察到,标记废弃 ${factPlan.stats.deprecated} 条`);
|
|
1189
|
+
|
|
1190
|
+
return {
|
|
1191
|
+
next,
|
|
1192
|
+
experiences,
|
|
1193
|
+
archive,
|
|
1194
|
+
stats,
|
|
1195
|
+
actions,
|
|
1196
|
+
learnings: learningPlan ? learningPlan.records : null,
|
|
1197
|
+
facts: factPlan,
|
|
1198
|
+
};
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
const ARCHIVE_FILES = [
|
|
1202
|
+
['system', 'system.json'],
|
|
1203
|
+
['pages', 'pages.json'],
|
|
1204
|
+
['recipes', 'recipes.json'],
|
|
1205
|
+
['business', 'business.json'],
|
|
1206
|
+
['processes', 'processes.json'],
|
|
1207
|
+
['documents', 'documents.json'],
|
|
1208
|
+
];
|
|
1209
|
+
|
|
1210
|
+
/**
|
|
1211
|
+
* 备份原始知识后落盘合并结果,并把证据追加到 experiences.jsonl。
|
|
1212
|
+
*/
|
|
1213
|
+
export function applyConsolidation(config, plan, { now = '' } = {}) {
|
|
1214
|
+
if (!plan?.next) throw new Error('合并计划缺少 next');
|
|
1215
|
+
const at = now || nowIso();
|
|
1216
|
+
const dir = knowledgeDir(config);
|
|
1217
|
+
const stamp = at.replace(/[:.]/g, '-');
|
|
1218
|
+
const archiveDir = path.join(dir, '.archive', 'consolidate-' + stamp);
|
|
1219
|
+
ensureDir(archiveDir);
|
|
1220
|
+
|
|
1221
|
+
const before = loadKnowledge(config);
|
|
1222
|
+
const beforePayload = {};
|
|
1223
|
+
for (const [kind, name] of ARCHIVE_FILES) beforePayload[kind] = before?.[kind] || null;
|
|
1224
|
+
writeJsonFile(path.join(archiveDir, 'before.json'), beforePayload);
|
|
1225
|
+
writeJsonFile(path.join(archiveDir, 'plan.json'), {
|
|
1226
|
+
at,
|
|
1227
|
+
stats: plan.stats,
|
|
1228
|
+
actions: plan.actions,
|
|
1229
|
+
archive: plan.archive,
|
|
1230
|
+
});
|
|
1231
|
+
writeJsonFile(path.join(archiveDir, 'experiences.json'), plan.experiences);
|
|
1232
|
+
|
|
1233
|
+
saveKnowledge(config, plan.next);
|
|
1234
|
+
const experiencesAdded = appendExperiences(config, plan.experiences);
|
|
1235
|
+
|
|
1236
|
+
let facts = null;
|
|
1237
|
+
if (plan.facts) {
|
|
1238
|
+
facts = applyFactConsolidation(config, plan.facts);
|
|
1239
|
+
writeJsonFile(path.join(archiveDir, 'facts-plan.json'), {
|
|
1240
|
+
stats: plan.facts.stats,
|
|
1241
|
+
errors: plan.facts.errors,
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
let learningsCompacted = 0;
|
|
1246
|
+
let learningsKeyed = 0;
|
|
1247
|
+
const learningStats = plan.stats?.learnings || {};
|
|
1248
|
+
if (Array.isArray(plan.learnings) && ((learningStats.duplicates || 0) > 0 || (learningStats.keyed || 0) > 0)) {
|
|
1249
|
+
const learningsFile = path.join(dir, KNOWLEDGE_FILES.learnings);
|
|
1250
|
+
if (fs.existsSync(learningsFile)) {
|
|
1251
|
+
fs.copyFileSync(learningsFile, path.join(archiveDir, KNOWLEDGE_FILES.learnings));
|
|
1252
|
+
}
|
|
1253
|
+
const body = plan.learnings.map((record) => JSON.stringify(record)).join('\n');
|
|
1254
|
+
writeFileAtomic(learningsFile, body ? body + '\n' : '');
|
|
1255
|
+
learningsCompacted = learningStats.duplicates || 0;
|
|
1256
|
+
learningsKeyed = learningStats.keyed || 0;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
return {
|
|
1260
|
+
archiveDir,
|
|
1261
|
+
experiencesAdded,
|
|
1262
|
+
dir,
|
|
1263
|
+
stats: plan.stats,
|
|
1264
|
+
learningsCompacted,
|
|
1265
|
+
learningsKeyed,
|
|
1266
|
+
factsArchiveDir: facts?.archiveDir || '',
|
|
1267
|
+
factsStats: facts?.stats || null,
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
export { isLearnableDocument, isEvidenceDocument };
|