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.
Files changed (50) hide show
  1. package/README.md +72 -11
  2. package/bin/uitest.mjs +189 -11
  3. package/client.js +81 -11
  4. package/host/agent-bridge.mjs +9 -2
  5. package/host/agent-test.mjs +1 -1
  6. package/host/context-budget.mjs +1 -1
  7. package/index.js +14 -2
  8. package/lib/agent-session.mjs +81 -3
  9. package/lib/agent-tasks.mjs +212 -0
  10. package/lib/batch.mjs +204 -13
  11. package/lib/browser-ab.mjs +21 -6
  12. package/lib/browser.mjs +5 -5
  13. package/lib/config.mjs +1 -0
  14. package/lib/convert.mjs +178 -40
  15. package/lib/doc-structure.mjs +316 -0
  16. package/lib/flow.mjs +49 -14
  17. package/lib/knowledge-central-episodes.mjs +120 -0
  18. package/lib/knowledge-central-import.mjs +16 -1
  19. package/lib/knowledge-central.mjs +149 -22
  20. package/lib/knowledge-clean.mjs +749 -0
  21. package/lib/knowledge-consolidate.mjs +1271 -0
  22. package/lib/knowledge-coverage.mjs +150 -0
  23. package/lib/knowledge-docs.mjs +3 -3
  24. package/lib/knowledge-effect.mjs +148 -0
  25. package/lib/knowledge-facts.mjs +1008 -0
  26. package/lib/knowledge-maintain.mjs +185 -0
  27. package/lib/knowledge-permission.mjs +447 -0
  28. package/lib/knowledge-query.mjs +304 -26
  29. package/lib/knowledge-store.mjs +169 -14
  30. package/lib/knowledge-summarize.mjs +332 -0
  31. package/lib/knowledge.mjs +944 -47
  32. package/lib/learn-run.mjs +157 -51
  33. package/lib/run-learn.mjs +34 -0
  34. package/lib/run-observe.mjs +95 -27
  35. package/lib/run-stats.mjs +71 -0
  36. package/package.json +12 -2
  37. package/scripts/knowledge-central-purge.mjs +248 -0
  38. package/scripts/knowledge-central-sync.mjs +102 -20
  39. package/scripts/knowledge-consolidate.mjs +158 -0
  40. package/scripts/knowledge-coverage.mjs +94 -0
  41. package/scripts/knowledge-effect.mjs +82 -0
  42. package/scripts/knowledge-permission-probe.mjs +196 -0
  43. package/scripts/knowledge-permission-report.mjs +140 -0
  44. package/scripts/knowledge-report.mjs +492 -0
  45. package/scripts/knowledge-summarize.mjs +200 -0
  46. package/skills/uitest/SKILL.md +4 -2
  47. package/skills/uitest/references/convert-knowledge.md +66 -13
  48. package/studio/host.mjs +120 -3
  49. package/studio/knowledge.mjs +195 -45
  50. package/studio/snapshot.mjs +6 -1
@@ -0,0 +1,492 @@
1
+ #!/usr/bin/env node
2
+ // 知识体检:用例污染、重复、孤儿、维度覆盖与中心库污染基线。
3
+ import path from 'node:path';
4
+ import process from 'node:process';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ import { loadConfig } from '../lib/config.mjs';
8
+ import { loadKnowledge, readExperiences, readLearnings } from '../lib/knowledge.mjs';
9
+ import { loadFacts } from '../lib/knowledge-facts.mjs';
10
+ import { dialogBaseIdOf, isCaseReferenced, isDialogPageRecord, learningIdentity, normalizeKey, stubPageTitleKey } from '../lib/knowledge-clean.mjs';
11
+ import { centralBrowse, centralConfig, centralPipelineStatus, centralStats } from '../lib/knowledge-central.mjs';
12
+
13
+ export { isCaseReferenced, normalizeKey };
14
+
15
+ function ratio(part, total) {
16
+ return total ? Math.round((part / total) * 10000) / 10000 : 0;
17
+ }
18
+
19
+ function textOf(...values) {
20
+ return values
21
+ .flat()
22
+ .filter(Boolean)
23
+ .map((value) => (typeof value === 'object' ? JSON.stringify(value) : String(value)))
24
+ .join(' ');
25
+ }
26
+
27
+ function rulesOf(entry) {
28
+ if (Array.isArray(entry.rules)) return entry.rules;
29
+ if (entry.rules) return [entry.rules];
30
+ if (entry.text || entry.desc) return [entry.text || entry.desc];
31
+ return [];
32
+ }
33
+
34
+ /** 无 URL 的页面按「归一化标题 + 来源文档」识别:不同模块可以有同名页面,不能算重复。 */
35
+ function pageUnitKey(page) {
36
+ // 弹窗与基础页共享 URL(弹窗没有独立路由),按 URL 判重会把不同弹窗算成同一页。
37
+ if (isDialogPageRecord(page)) {
38
+ const title = normalizeKey(page.title || page.id);
39
+ const base = dialogBaseIdOf(page);
40
+ return 'dialog:' + title + (base ? '@' + base : '');
41
+ }
42
+ if (page.url) return 'url:' + page.url;
43
+ const title = stubPageTitleKey(page.title || page.id) || normalizeKey(page.title || page.id);
44
+ const documents = Array.isArray(page.provenance?.documents)
45
+ ? page.provenance.documents.map((doc) => normalizeKey(doc)).filter(Boolean).sort()
46
+ : [];
47
+ return 'page:' + title + (documents.length ? '@' + documents[0] : '');
48
+ }
49
+
50
+ export function knowledgeUnits(knowledge = {}, learnings = [], experiences = []) {
51
+ const units = [];
52
+ for (const page of knowledge.pages?.pages || []) {
53
+ const actionText = (page.actions || []).map((action) => textOf(
54
+ action.id,
55
+ action.title,
56
+ action.text,
57
+ action.keywords,
58
+ action.steps,
59
+ action.notes,
60
+ action.elementHints,
61
+ action.assertionHints,
62
+ ));
63
+ units.push({
64
+ kind: 'page',
65
+ layer: 'canonical',
66
+ id: page.id || page.title || '',
67
+ key: pageUnitKey(page),
68
+ text: textOf(
69
+ page.id,
70
+ page.title,
71
+ page.keywords,
72
+ page.texts,
73
+ page.notes,
74
+ page.feedbacks,
75
+ page.elementHints,
76
+ page.assertionHints,
77
+ page.observations,
78
+ actionText,
79
+ ),
80
+ supported: Boolean(page.url || (page.actions || []).length || (page.observations || []).length),
81
+ });
82
+ }
83
+ for (const process of knowledge.processes?.processes || []) {
84
+ units.push({
85
+ kind: 'process',
86
+ layer: 'canonical',
87
+ id: process.id || process.name || '',
88
+ key: 'process:' + normalizeKey(process.name || process.id),
89
+ text: textOf(process.id, process.name, process.keywords, process.steps, process.notes, process.corrections, process.reviews),
90
+ supported: Boolean((process.sources || []).length || (process.steps || []).length),
91
+ });
92
+ }
93
+ for (const entry of knowledge.business?.entries || []) {
94
+ for (const [index, rule] of rulesOf(entry).entries()) {
95
+ const text = typeof rule === 'string' ? rule : rule?.text || rule?.desc || '';
96
+ units.push({
97
+ kind: 'business',
98
+ layer: 'canonical',
99
+ id: (entry.id || entry.title || 'business') + '#' + (index + 1),
100
+ key: 'rule:' + normalizeKey(text),
101
+ text: textOf(entry.title, text),
102
+ supported: Boolean(entry.source),
103
+ });
104
+ }
105
+ }
106
+ for (const [index, item] of learnings.entries()) {
107
+ const identity = learningIdentity(item) || 'learning-' + index;
108
+ units.push({
109
+ kind: 'learning',
110
+ layer: 'evidence',
111
+ id: item.id || item.dedupeKey || identity,
112
+ key: 'learning:' + identity,
113
+ text: textOf(item.kind, item.detail),
114
+ supported: Boolean(item.runDir || item.pageId),
115
+ });
116
+ }
117
+ for (const item of experiences) {
118
+ const identity = item.id || [item.kind, item.batchId, item.caseId, item.at].filter(Boolean).join('|');
119
+ units.push({
120
+ kind: 'experience',
121
+ layer: 'evidence',
122
+ id: identity,
123
+ key: 'experience:' + identity,
124
+ text: textOf(item.kind, item.caseId, item.name, item.steps, item.notes, item.corrections, item.reviews),
125
+ supported: Boolean(item.caseId || item.id),
126
+ });
127
+ }
128
+ return units;
129
+ }
130
+
131
+ export function analyzeUnits(units = []) {
132
+ const total = units.length;
133
+ const caseUnits = units.filter((unit) => isCaseReferenced(unit.text));
134
+ const groups = new Map();
135
+ for (const unit of units) {
136
+ const key = unit.key || ('id:' + unit.id);
137
+ if (!groups.has(key)) groups.set(key, []);
138
+ groups.get(key).push(unit);
139
+ }
140
+ const duplicateGroups = [...groups.values()].filter((group) => group.length > 1);
141
+ const duplicateRecords = duplicateGroups.reduce((sum, group) => sum + group.length - 1, 0);
142
+ const orphans = units.filter((unit) => !unit.supported);
143
+ return {
144
+ total,
145
+ caseRefs: caseUnits.length,
146
+ caseRefRate: ratio(caseUnits.length, total),
147
+ duplicateGroups: duplicateGroups.length,
148
+ duplicateRecords,
149
+ dupRate: ratio(duplicateRecords, total),
150
+ orphans: orphans.length,
151
+ orphanRate: ratio(orphans.length, total),
152
+ examples: {
153
+ caseRefs: caseUnits.slice(0, 5).map((unit) => ({ kind: unit.kind, id: unit.id })),
154
+ duplicates: duplicateGroups.slice(0, 5).map((group) => group.map((unit) => unit.id)),
155
+ orphans: orphans.slice(0, 5).map((unit) => ({ kind: unit.kind, id: unit.id })),
156
+ },
157
+ };
158
+ }
159
+
160
+ function countDocs(knowledge, pattern) {
161
+ return (knowledge.documents?.documents || []).filter((doc) => pattern.test(String(doc.title || doc.id || ''))).length;
162
+ }
163
+
164
+ function countDocsWith(knowledge, field, pattern) {
165
+ return (knowledge.documents?.documents || []).filter(
166
+ (doc) => (doc[field] || []).length || pattern.test(String(doc.title || doc.id || '')),
167
+ ).length;
168
+ }
169
+
170
+ function factCoverage(facts = []) {
171
+ const byStatus = {};
172
+ const byKind = {};
173
+ let withEvidence = 0;
174
+ for (const fact of facts) {
175
+ const status = fact.status || 'candidate';
176
+ byStatus[status] = (byStatus[status] || 0) + 1;
177
+ const kind = String(fact.kind || 'unknown').split('.')[0];
178
+ byKind[kind] = (byKind[kind] || 0) + 1;
179
+ if (Array.isArray(fact.evidence) && fact.evidence.length) withEvidence += 1;
180
+ }
181
+ return {
182
+ total: facts.length,
183
+ byStatus,
184
+ byKind,
185
+ conflicts: facts.filter((fact) => (fact.conflicts || []).length).length,
186
+ withEvidence,
187
+ evidenceCoverage: ratio(withEvidence, facts.length),
188
+ };
189
+ }
190
+
191
+ export function dimensionCoverage(knowledge = {}, { experiences = [], facts = [] } = {}) {
192
+ const pages = knowledge.pages?.pages || [];
193
+ const documents = knowledge.documents?.documents || [];
194
+ const processes = knowledge.processes?.processes || [];
195
+ const entries = knowledge.business?.entries || [];
196
+ const rules = entries.reduce((sum, entry) => sum + rulesOf(entry).length, 0);
197
+ const learnings = knowledge.learningsCount || 0;
198
+ const experiencesCount = knowledge.experiencesCount || 0;
199
+ const corrections = processes.reduce((sum, process) => sum + (process.corrections || []).length, 0)
200
+ + (Array.isArray(experiences) ? experiences.reduce((sum, item) => sum + (Array.isArray(item.corrections) ? item.corrections.length : 0), 0) : 0);
201
+ const kinds = {};
202
+ for (const doc of documents) {
203
+ const kind = doc.kind || 'unclassified';
204
+ kinds[kind] = (kinds[kind] || 0) + 1;
205
+ }
206
+ return {
207
+ system: { menus: Object.keys(knowledge.system?.menus || {}).length, urls: Object.keys(knowledge.system?.urls || {}).length },
208
+ pages: {
209
+ total: pages.length,
210
+ withUrl: pages.filter((page) => page.url).length,
211
+ withActions: pages.filter((page) => (page.actions || []).length).length,
212
+ withTable: pages.filter((page) => (page.table?.headers || []).length).length,
213
+ canonical: pages.filter((page) => page.status !== 'stub').length,
214
+ stubs: pages.filter((page) => page.status === 'stub').length,
215
+ },
216
+ documents: {
217
+ total: documents.length,
218
+ kinds,
219
+ learnable: documents.filter((doc) => doc.learnable !== false).length,
220
+ withHeadings: documents.filter((doc) => (doc.headings || []).length).length,
221
+ withFields: documents.filter((doc) => Array.isArray(doc.fields) && doc.fields.length).length,
222
+ withStatuses: documents.filter((doc) => Array.isArray(doc.statuses) && doc.statuses.length).length,
223
+ withTransitions: documents.filter((doc) => Array.isArray(doc.transitions) && doc.transitions.length).length,
224
+ withRoles: documents.filter((doc) => Array.isArray(doc.roles) && doc.roles.length).length,
225
+ withPermissions: documents.filter((doc) => Array.isArray(doc.permissions) && doc.permissions.length).length,
226
+ withGlossary: documents.filter((doc) => Array.isArray(doc.glossary) && doc.glossary.length).length,
227
+ },
228
+ processes: { total: processes.length, withSteps: processes.filter((process) => (process.steps || []).length).length },
229
+ roles: {
230
+ total: Array.isArray(knowledge.system?.roles) ? knowledge.system.roles.length : 0,
231
+ documents: countDocsWith(knowledge, 'roles', /角色|role/i),
232
+ },
233
+ permissions: {
234
+ total: Array.isArray(knowledge.system?.permissions) ? knowledge.system.permissions.length : 0,
235
+ documents: countDocsWith(knowledge, 'permissions', /权限|按钮|permission/i),
236
+ },
237
+ rules: { entries: entries.length, total: rules },
238
+ glossary: {
239
+ total: Array.isArray(knowledge.system?.glossary) ? knowledge.system.glossary.length : 0,
240
+ documents: countDocsWith(knowledge, 'glossary', /术语|glossary/i),
241
+ },
242
+ environment: { recipes: (knowledge.recipes?.recipes || []).length, notes: (knowledge.system?.notes || []).length },
243
+ summaries: {
244
+ pages: pages.filter((page) => page.summaryHash).length,
245
+ processes: processes.filter((process) => process.summaryHash).length,
246
+ business: entries.filter((entry) => entry.summaryHash).length,
247
+ documents: documents.filter((doc) => doc.summaryHash).length,
248
+ system: knowledge.system?.summaryHash ? 1 : 0,
249
+ legacy: {
250
+ pages: pages.filter((page) => page.summary && !page.summaryHash).length,
251
+ processes: processes.filter((process) => process.summary && !process.summaryHash).length,
252
+ business: entries.filter((entry) => entry.summary && !entry.summaryHash).length,
253
+ documents: documents.filter((doc) => doc.summary && !doc.summaryHash).length,
254
+ system: knowledge.system?.summary && !knowledge.system?.summaryHash ? 1 : 0,
255
+ },
256
+ },
257
+ experience: { learnings, experiences: experiencesCount, corrections },
258
+ facts: factCoverage(facts),
259
+ };
260
+ }
261
+
262
+ export function analyzeKnowledge(knowledge = {}, { learnings = [], experiences = [], facts = [] } = {}) {
263
+ const units = knowledgeUnits(knowledge, learnings, experiences);
264
+ const canonical = units.filter((unit) => unit.layer !== 'evidence');
265
+ const evidenceUnits = units.filter((unit) => unit.layer === 'evidence');
266
+ return {
267
+ store: { dir: knowledge.dir || '', source: knowledge.source || '', libraryName: knowledge.libraryName || null },
268
+ counts: {
269
+ pages: (knowledge.pages?.pages || []).length,
270
+ processes: (knowledge.processes?.processes || []).length,
271
+ businessEntries: (knowledge.business?.entries || []).length,
272
+ businessRules: (knowledge.business?.entries || []).reduce((sum, entry) => sum + rulesOf(entry).length, 0),
273
+ documents: (knowledge.documents?.documents || []).length,
274
+ recipes: (knowledge.recipes?.recipes || []).length,
275
+ learnings: learnings.length,
276
+ experiences: experiences.length,
277
+ },
278
+ metrics: analyzeUnits(canonical),
279
+ evidence: analyzeUnits(evidenceUnits),
280
+ dimensions: dimensionCoverage(
281
+ { ...knowledge, learningsCount: learnings.length, experiencesCount: experiences.length },
282
+ { experiences, facts },
283
+ ),
284
+ };
285
+ }
286
+
287
+ export function centralSummary(groupId, pipeline, stats, facts, entities, episodes = []) {
288
+ const factItems = facts?.items || [];
289
+ const entityItems = entities?.items || [];
290
+ const factRefs = factItems.filter((item) => isCaseReferenced(textOf(item.name, item.fact)));
291
+ const entityRefs = entityItems.filter((item) => isCaseReferenced(textOf(item.name, item.summary)));
292
+ const relationNames = new Set(factItems.map((item) => item.name).filter(Boolean));
293
+ const legacyPrefixes = {};
294
+ for (const episode of episodes) {
295
+ const prefix = String(episode?.name || '').split(':')[0] + ':';
296
+ if (!['process:', 'case:', 'experience:'].includes(prefix)) continue;
297
+ legacyPrefixes[prefix] = (legacyPrefixes[prefix] || 0) + 1;
298
+ }
299
+ const legacyEpisodes = Object.values(legacyPrefixes).reduce((sum, count) => sum + count, 0);
300
+ return {
301
+ groupId,
302
+ pipeline: pipeline?.counts || null,
303
+ stats: { nodes: stats?.nodes || [], edges: stats?.edges || [] },
304
+ episodes: episodes.length,
305
+ legacyEpisodes,
306
+ legacyPrefixes,
307
+ sample: { facts: factItems.length, entities: entityItems.length },
308
+ factCaseRefs: factRefs.length,
309
+ factCaseRefRate: ratio(factRefs.length, factItems.length),
310
+ entityCaseRefs: entityRefs.length,
311
+ entityCaseRefRate: ratio(entityRefs.length, entityItems.length),
312
+ relationNames: relationNames.size,
313
+ examples: {
314
+ facts: factRefs.slice(0, 3).map((item) => item.fact),
315
+ entities: entityRefs.slice(0, 3).map((item) => item.name),
316
+ },
317
+ };
318
+ }
319
+
320
+ async function listEpisodes(config, groupId, { limit = 5000 } = {}) {
321
+ const items = [];
322
+ let offset = 0;
323
+ let hasMore = true;
324
+ while (hasMore && items.length < limit) {
325
+ const page = await centralBrowse(config, { kind: 'episodes', groupId, limit: 100, offset });
326
+ if (!page.ok) return { ok: false, items, error: page.error || '浏览中心 Episode 失败' };
327
+ items.push(...(page.items || []));
328
+ hasMore = page.hasMore === true && (page.items || []).length > 0;
329
+ offset += (page.items || []).length;
330
+ if (!page.items?.length) break;
331
+ }
332
+ return { ok: true, items: items.slice(0, limit) };
333
+ }
334
+
335
+ async function loadCentralSummary(config, { limit = 100 } = {}) {
336
+ const central = centralConfig(config);
337
+ if (!central.enabled) return { enabled: false, ok: false, error: '中心知识库未启用' };
338
+ try {
339
+ const [pipeline, stats, facts, entities, episodes] = await Promise.all([
340
+ centralPipelineStatus(config),
341
+ centralStats(config),
342
+ centralBrowse(config, { kind: 'facts', limit }),
343
+ centralBrowse(config, { kind: 'entities', limit }),
344
+ listEpisodes(config, central.groupId),
345
+ ]);
346
+ const errors = [pipeline, facts, entities, episodes]
347
+ .filter((result) => result && result.ok === false)
348
+ .map((result) => result.error || '中心知识库请求失败');
349
+ const report = {
350
+ enabled: true,
351
+ ok: errors.length === 0,
352
+ url: central.url,
353
+ groupId: central.groupId,
354
+ evidenceGroupId: central.evidenceGroupId,
355
+ error: errors[0] || '',
356
+ knowledge: centralSummary(central.groupId, pipeline, stats, facts, entities, episodes.items || []),
357
+ };
358
+ if (central.evidenceGroupId && central.evidenceGroupId !== central.groupId) {
359
+ const [evidencePipeline, evidenceStats, evidenceFacts, evidenceEntities, evidenceEpisodes] = await Promise.all([
360
+ centralPipelineStatus(config, { groupId: central.evidenceGroupId }),
361
+ centralStats(config, { groupId: central.evidenceGroupId }),
362
+ centralBrowse(config, { kind: 'facts', groupId: central.evidenceGroupId, limit }),
363
+ centralBrowse(config, { kind: 'entities', groupId: central.evidenceGroupId, limit }),
364
+ listEpisodes(config, central.evidenceGroupId),
365
+ ]);
366
+ report.evidence = centralSummary(
367
+ central.evidenceGroupId,
368
+ evidencePipeline,
369
+ evidenceStats,
370
+ evidenceFacts,
371
+ evidenceEntities,
372
+ evidenceEpisodes.items || [],
373
+ );
374
+ }
375
+ return report;
376
+ } catch (error) {
377
+ return {
378
+ enabled: true,
379
+ ok: false,
380
+ url: central.url,
381
+ groupId: central.groupId,
382
+ error: String(error.message || error),
383
+ knowledge: null,
384
+ };
385
+ }
386
+ }
387
+
388
+ function parseArgs(argv) {
389
+ const args = { project: process.cwd(), json: false, strict: false, central: false, limit: 100 };
390
+ for (let i = 0; i < argv.length; i += 1) {
391
+ const token = argv[i];
392
+ if (token === '--project') args.project = path.resolve(argv[++i] || '');
393
+ else if (token === '--json') args.json = true;
394
+ else if (token === '--strict') args.strict = true;
395
+ else if (token === '--central') args.central = true;
396
+ else if (token === '--limit') args.limit = Math.max(1, Math.min(100, Number(argv[++i]) || 100));
397
+ else if (token === '--help' || token === '-h') args.help = true;
398
+ }
399
+ return args;
400
+ }
401
+
402
+ function pct(value) {
403
+ return (Number(value || 0) * 100).toFixed(1) + '%';
404
+ }
405
+
406
+ function printReport(report) {
407
+ console.log('知识体检 ' + report.generatedAt);
408
+ console.log('项目 ' + report.projectDir);
409
+ console.log('知识库 ' + report.knowledge.store.dir + (report.knowledge.store.source ? ' (' + report.knowledge.store.source + ')' : ''));
410
+ console.log('计数 ' + JSON.stringify(report.knowledge.counts));
411
+ console.log('');
412
+ console.log('正典层(页面/流程/业务规则)');
413
+ console.log(' 用例污染 ' + report.knowledge.metrics.caseRefs + '/' + report.knowledge.metrics.total + ' ' + pct(report.knowledge.metrics.caseRefRate));
414
+ console.log(' 重复 ' + report.knowledge.metrics.duplicateGroups + ' 组 / ' + report.knowledge.metrics.duplicateRecords + ' 条 ' + pct(report.knowledge.metrics.dupRate));
415
+ console.log(' 孤儿 ' + report.knowledge.metrics.orphans + '/' + report.knowledge.metrics.total + ' ' + pct(report.knowledge.metrics.orphanRate));
416
+ console.log('证据层(run 学习/执行经验)');
417
+ console.log(' 条目 ' + report.knowledge.evidence.total);
418
+ console.log(' 用例引用 ' + report.knowledge.evidence.caseRefs + ' 重复 ' + report.knowledge.evidence.duplicateRecords);
419
+ console.log('');
420
+ console.log('维度覆盖');
421
+ for (const [name, value] of Object.entries(report.knowledge.dimensions)) {
422
+ console.log(' ' + name + ' ' + JSON.stringify(value));
423
+ }
424
+ if (report.central) {
425
+ console.log('');
426
+ if (!report.central.enabled) {
427
+ console.log('中心库 未启用');
428
+ } else if (!report.central.ok) {
429
+ console.log('中心库 不可用:' + (report.central.error || '未知错误'));
430
+ } else {
431
+ const central = report.central.knowledge;
432
+ console.log('中心库 ' + report.central.url + ' group=' + central.groupId);
433
+ console.log(' 管线 ' + JSON.stringify(central.pipeline));
434
+ console.log(' Episode ' + central.episodes + ',知识组旧证据前缀 ' + central.legacyEpisodes + ' ' + JSON.stringify(central.legacyPrefixes));
435
+ console.log(' 事实样本 ' + central.sample.facts + ',用例引用 ' + central.factCaseRefs + ' ' + pct(central.factCaseRefRate));
436
+ console.log(' 实体样本 ' + central.sample.entities + ',实例名 ' + central.entityCaseRefs + ' ' + pct(central.entityCaseRefRate));
437
+ console.log(' 关系名 ' + central.relationNames);
438
+ if (central.examples.facts.length) console.log(' 事实示例 ' + central.examples.facts.join(' | '));
439
+ if (central.examples.entities.length) console.log(' 实体示例 ' + central.examples.entities.join(' | '));
440
+ if (report.central.evidence) {
441
+ const evidence = report.central.evidence;
442
+ console.log('证据组 group=' + evidence.groupId);
443
+ console.log(' 管线 ' + JSON.stringify(evidence.pipeline));
444
+ console.log(' 事实样本 ' + evidence.sample.facts + ',用例引用 ' + evidence.factCaseRefs + ' ' + pct(evidence.factCaseRefRate));
445
+ console.log(' 实体样本 ' + evidence.sample.entities + ',实例名 ' + evidence.entityCaseRefs + ' ' + pct(evidence.entityCaseRefRate));
446
+ }
447
+ }
448
+ }
449
+ }
450
+
451
+ async function main() {
452
+ const args = parseArgs(process.argv.slice(2));
453
+ if (args.help) {
454
+ console.log([
455
+ '用法:node scripts/knowledge-report.mjs --project <dir> [--json] [--strict] [--central] [--limit 100]',
456
+ ' --central 同时抽样中心知识库的事实与实体',
457
+ ' --strict 正典层用例污染率大于 0,或知识组存在旧证据前缀/事实实体实例引用时以退出码 1 结束',
458
+ ].join('\n'));
459
+ return;
460
+ }
461
+ const config = loadConfig(args.project);
462
+ const knowledge = loadKnowledge(config);
463
+ const learnings = readLearnings(config, { limit: 100000 });
464
+ const experiences = readExperiences(config, { limit: 100000 });
465
+ const facts = loadFacts(config).facts;
466
+ const report = {
467
+ generatedAt: new Date().toISOString(),
468
+ projectDir: config.projectDir,
469
+ knowledge: analyzeKnowledge(knowledge, { learnings, experiences, facts }),
470
+ central: args.central ? await loadCentralSummary(config, { limit: args.limit }) : null,
471
+ };
472
+ if (args.json) console.log(JSON.stringify(report, null, 2));
473
+ else printReport(report);
474
+ const centralLeak = Boolean(
475
+ report.central?.enabled
476
+ && report.central.ok
477
+ && report.central.knowledge
478
+ && (
479
+ report.central.knowledge.legacyEpisodes > 0
480
+ || report.central.knowledge.factCaseRefs > 0
481
+ || report.central.knowledge.entityCaseRefs > 0
482
+ ),
483
+ );
484
+ if (args.strict && (report.knowledge.metrics.caseRefs > 0 || centralLeak)) process.exitCode = 1;
485
+ }
486
+
487
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
488
+ main().catch((error) => {
489
+ console.error('知识体检失败:' + (error.message || error));
490
+ process.exitCode = 1;
491
+ });
492
+ }