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
@@ -1,10 +1,13 @@
1
1
  // 按用例查询知识库:中心优先,本地 knowledge/ 作为缓存与离线兜底。
2
2
  import { caseText, scorePageForCase } from './convert.mjs';
3
3
  import { loadProjectCases } from './cases-import.mjs';
4
- import { centralBrowse, centralSearch } from './knowledge-central.mjs';
5
- import { loadKnowledge, readLearnings } from './knowledge.mjs';
4
+ import { centralBrowse, centralConfig, centralSearch } from './knowledge-central.mjs';
5
+ import { loadFacts, pageButtonNames, queryFacts } from './knowledge-facts.mjs';
6
+ import { loadKnowledge, readExperiences, readLearnings } from './knowledge.mjs';
7
+ import { cleanRoleName, isDialogPageRecord, isExperienceKind, isLoginPageRecord } from './knowledge-clean.mjs';
8
+ import { inferRolesFromText } from '../studio/accounts.mjs';
6
9
  import { readRunFeedbacks } from './run-feedback.mjs';
7
- import { nowIso, slug, truncate } from './util.mjs';
10
+ import { nowIso, truncate } from './util.mjs';
8
11
  import { findCase } from './xlsx.mjs';
9
12
 
10
13
  function clean(value, max = 400) {
@@ -38,9 +41,12 @@ function matchesText(item, query) {
38
41
  item?.id,
39
42
  item?.name,
40
43
  item?.title,
44
+ item?.summary,
41
45
  item?.caseId,
46
+ item?.pageId,
42
47
  ...(asArray(item?.keywords)),
43
48
  ...(asArray(item?.notes)),
49
+ ...(asArray(item?.feedbacks).map((feedback) => [feedback?.note, feedback?.action, feedback?.desc].filter(Boolean).join(' '))),
44
50
  ...(asArray(item?.corrections).map((correction) => correction?.summary || correction?.failed?.desc || '')),
45
51
  ...(asArray(item?.reviews).map((review) => [review?.summary, ...(asArray(review?.lessons))].filter(Boolean).join(' '))),
46
52
  ]
@@ -55,10 +61,22 @@ function matchesText(item, query) {
55
61
  return terms.some((term) => haystack.includes(term));
56
62
  }
57
63
 
64
+ function matchesPageQuery(page, query) {
65
+ if (matchesText(page, query)) return true;
66
+ const lower = String(query || '').toLowerCase();
67
+ if (!lower) return false;
68
+ const title = String(page?.title || '').toLowerCase();
69
+ if (title.length >= 2 && lower.includes(title)) return true;
70
+ const id = String(page?.id || '').toLowerCase();
71
+ return id.length >= 3 && lower.includes(id);
72
+ }
73
+
58
74
  function compactPage(page) {
59
75
  return {
60
76
  id: page.id || '',
61
77
  title: page.title || '',
78
+ status: page.status || '',
79
+ summary: clean(page.summary, 600),
62
80
  urlName: page.urlName || '',
63
81
  url: page.url || '',
64
82
  keywords: uniqueStrings(page.keywords, { max: 12 }),
@@ -83,6 +101,7 @@ function compactProcess(process) {
83
101
  id: process.id || '',
84
102
  caseId: process.caseId || '',
85
103
  name: process.name || process.title || process.id || '',
104
+ summary: clean(process.summary, 600),
86
105
  steps: asArray(process.steps).slice(0, 20).map((step) => (typeof step === 'string' ? clean(step, 220) : clean(step?.text || step?.desc || step, 220))).filter(Boolean),
87
106
  notes: uniqueStrings(process.notes, { max: 8, maxLength: 400 }),
88
107
  corrections: asArray(process.corrections).slice(0, 8).map((correction) => ({
@@ -104,10 +123,45 @@ function compactProcess(process) {
104
123
  };
105
124
  }
106
125
 
126
+ function compactExperience(item) {
127
+ return {
128
+ ...compactProcess(item),
129
+ kind: item.kind || '',
130
+ pageId: item.pageId || '',
131
+ batchId: item.batchId || '',
132
+ title: item.title || '',
133
+ sources: asArray(item.sources).slice(-3).map((source) => ({
134
+ runDir: source?.runDir || '',
135
+ stepId: source?.stepId || '',
136
+ at: source?.at || '',
137
+ })),
138
+ observations: asArray(item.observations).slice(-3).map((observation) => ({
139
+ runDir: observation?.runDir || '',
140
+ stepId: observation?.stepId || '',
141
+ url: clean(observation?.url, 400),
142
+ at: observation?.at || '',
143
+ dialog: observation?.dialog || null,
144
+ })),
145
+ feedbacks: asArray(item.feedbacks).slice(-5).map((feedback) => ({
146
+ at: feedback.at || '',
147
+ stepId: feedback.stepId || '',
148
+ verdict: feedback.verdict || '',
149
+ action: feedback.action || '',
150
+ desc: feedback.desc || '',
151
+ note: clean(feedback.note, 600),
152
+ })),
153
+ evidence: true,
154
+ };
155
+ }
156
+
157
+ const EXECUTION_LEARNING_KINDS = ['agent-correction', 'agent-success', 'run-failure', 'agent-review'];
158
+
107
159
  function compactLearning(item) {
108
160
  return {
109
161
  kind: item.kind || '',
110
162
  at: item.at || '',
163
+ caseId: item.caseId || null,
164
+ runDir: item.runDir || null,
111
165
  pageId: item.pageId || null,
112
166
  detail: item.detail || null,
113
167
  confidence: item.confidence ?? null,
@@ -118,12 +172,135 @@ function feedbackQueryText(caseItem, query) {
118
172
  return [textOfCase(caseItem), String(query || '').toLowerCase()].filter(Boolean).join(' ');
119
173
  }
120
174
 
175
+ function roleEquals(a, b) {
176
+ const left = String(a || '').replace(/^OMS/i, '').trim();
177
+ const right = String(b || '').replace(/^OMS/i, '').trim();
178
+ if (!left || !right) return false;
179
+ return left === right || left.includes(right) || right.includes(left);
180
+ }
181
+
182
+ /**
183
+ * 从用例文本里识别检索实体:命中的页面、明确提到的文档、角色与术语。
184
+ * 实体只用于召回事实,不影响页面评分。
185
+ */
186
+ export function factEntityTerms({ fullQuery, pageList, documents, knowledge, facts }) {
187
+ const lower = String(fullQuery || '').toLowerCase();
188
+ const terms = [];
189
+ for (const page of pageList) {
190
+ if (page.title) terms.push(page.title);
191
+ if (page.id) terms.push(page.id);
192
+ }
193
+ const matchedDocuments = documents.filter((doc) => {
194
+ const title = String(doc?.title || '').trim();
195
+ return title.length >= 2 && lower.includes(title.toLowerCase());
196
+ });
197
+ for (const doc of matchedDocuments) {
198
+ if (doc.title) terms.push(doc.title);
199
+ }
200
+ const knownRoles = [
201
+ ...asArray(knowledge?.system?.roles).map((role) => role?.name || role),
202
+ ...asArray(knowledge?.documents?.documents).flatMap((doc) => asArray(doc?.roles).map((role) => role?.name || role)),
203
+ ...asArray(facts).map((fact) => fact?.value?.role || fact?.scope?.role),
204
+ ]
205
+ .map((role) => cleanRoleName(role))
206
+ .filter((role) => role.length >= 2 && lower.includes(role.toLowerCase()));
207
+ const roles = uniqueStrings([...inferRolesFromText(fullQuery), ...knownRoles], { max: 12 });
208
+ for (const role of roles) {
209
+ terms.push(role);
210
+ terms.push(role.replace(/^OMS/i, ''));
211
+ }
212
+ const glossaryTerms = asArray(knowledge?.system?.glossary)
213
+ .map((term) => String(term?.term || term?.name || term || '').trim())
214
+ .filter((term) => term.length >= 2 && lower.includes(term.toLowerCase()));
215
+ terms.push(...glossaryTerms);
216
+ return {
217
+ terms: uniqueStrings(terms, { max: 40 }),
218
+ documents: matchedDocuments,
219
+ roles,
220
+ glossaryTerms: uniqueStrings(glossaryTerms, { max: 10 }),
221
+ };
222
+ }
223
+
224
+ export function buildFactGaps({ pageList, pagesById, documents, roles, facts }) {
225
+ const gaps = [];
226
+ const push = (type, detail, ref = '') => {
227
+ if (gaps.some((gap) => gap.type === type && gap.ref === ref)) return;
228
+ gaps.push({ type, detail, ref });
229
+ };
230
+ if (!pageList.length) push('page-missing', '用例没有命中任何页面知识');
231
+ for (const page of pageList) {
232
+ const original = pagesById.get(String(page.id));
233
+ if (!original || original.status !== 'canonical') {
234
+ push('page-stub', '页面只有存根,尚无结构知识', page.id);
235
+ continue;
236
+ }
237
+ const hasActions = facts.some((fact) => (
238
+ (fact.kind === 'page.action' || fact.kind === 'page.button')
239
+ && fact.subject === 'page:' + page.id
240
+ && !['deprecated', 'rejected'].includes(fact.status)
241
+ ));
242
+ if (!hasActions) push('page-action-missing', '页面没有动作知识,执行时只能靠观察', page.id);
243
+ }
244
+ for (const doc of documents) {
245
+ const id = String(doc.id || doc.title || '');
246
+ const subject = id ? 'document:' + id : '';
247
+ const hasStructure = facts.some((fact) => subject
248
+ && subject === String(fact.subject || '')
249
+ && ['document.field', 'document.status', 'document.transition'].includes(fact.kind));
250
+ if (doc.learnable === false) push('document-not-learnable', '命中的文档不参与结构学习', id);
251
+ else if (!hasStructure) push('document-structure-missing', '命中的文档没有字段/状态结构', id);
252
+ }
253
+ for (const role of roles) {
254
+ const hasKnowledge = facts.some((fact) => (
255
+ ['system.role', 'document.role'].includes(fact.kind) && roleEquals(fact.value?.name, role)
256
+ ) || (
257
+ ['role.permission', 'document.permission', 'system.permission'].includes(fact.kind)
258
+ && (roleEquals(fact.value?.role, role) || roleEquals(fact.scope?.role, role))
259
+ ));
260
+ if (!hasKnowledge) push('role-knowledge-missing', '用例角色在知识库里没有角色或权限事实', role);
261
+ }
262
+ for (const page of pageList) {
263
+ if (!roles.length) break;
264
+ const original = pagesById.get(String(page.id));
265
+ if (!original || original.status !== 'canonical') continue;
266
+ if (isLoginPageRecord(original)) continue;
267
+ // 探测计划同样跳过弹窗页与没有 URL 的页面;这里保持一致,否则缺口永远无法补上。
268
+ if (isDialogPageRecord(original)) continue;
269
+ if (!String(original.url || '').trim()) continue;
270
+ // 没有按钮的页面不存在可探测的页面权限,不报“权限未探测”。
271
+ if (!pageButtonNames(original).length) continue;
272
+ for (const role of roles) {
273
+ // 只有仍然有效的探测事实才算“已探测”;deprecated/rejected 不能掩盖缺口。
274
+ const probed = facts.some((fact) => fact.kind === 'role.permission'
275
+ && ['verified', 'candidate', 'conflicted'].includes(fact.status)
276
+ && String(fact.value?.page || '') === String(page.id)
277
+ && roleEquals(fact.value?.role, role));
278
+ if (!probed) push('permission-unprobed', '页面还没有该角色的按钮权限探测', page.id + '@' + role);
279
+ }
280
+ }
281
+ return gaps;
282
+ }
283
+
284
+ function compactFact(fact) {
285
+ return {
286
+ id: fact.id || '',
287
+ kind: fact.kind || '',
288
+ subject: fact.subject || '',
289
+ predicate: fact.predicate || '',
290
+ value: fact.value,
291
+ scope: fact.scope || {},
292
+ status: fact.status || '',
293
+ confidence: fact.confidence ?? null,
294
+ evidenceCount: asArray(fact.evidence).length,
295
+ };
296
+ }
297
+
121
298
  /**
122
299
  * 读取与用例相关的知识。
123
300
  * @param {object} config 已加载配置
124
301
  * @param {{caseId?:string, query?:string, limits?:object, central?:object[]}} options
125
302
  */
126
- export function knowledgeContextForCase(config, { caseId = '', query = '', limits = {}, central = [] } = {}) {
303
+ export function knowledgeContextForCase(config, { caseId = '', query = '', limits = {}, central = [], caseItem: providedCase = null } = {}) {
127
304
  const limitsValue = {
128
305
  pages: Number(limits.pages) || 6,
129
306
  processes: Number(limits.processes) || 6,
@@ -131,8 +308,8 @@ export function knowledgeContextForCase(config, { caseId = '', query = '', limit
131
308
  learnings: Number(limits.learnings) || 10,
132
309
  feedback: Number(limits.feedback) || 5,
133
310
  };
134
- let caseItem = null;
135
- if (caseId) {
311
+ let caseItem = providedCase || null;
312
+ if (!caseItem && caseId) {
136
313
  try {
137
314
  const cases = loadProjectCases(config).cases;
138
315
  caseItem = findCase(cases, caseId)?.case || null;
@@ -146,24 +323,43 @@ export function knowledgeContextForCase(config, { caseId = '', query = '', limit
146
323
  const business = asArray(knowledge?.business?.entries);
147
324
  const fullQuery = feedbackQueryText(caseItem, query);
148
325
  const lookupQuery = fullQuery.toLowerCase();
149
- const processId = caseId ? 'studio-' + slug(caseId) : '';
150
326
 
151
327
  const scoredPages = pages
152
328
  .map((page) => ({ page, score: scorePageForCase(page, caseItem || {}).score }))
153
- .filter((item) => (caseItem ? item.score > 0 : lookupQuery ? matchesText(item.page, lookupQuery) : true))
329
+ .filter((item) => (caseItem ? item.score > 0 : lookupQuery ? matchesPageQuery(item.page, lookupQuery) : true))
154
330
  .sort((a, b) => b.score - a.score || String(b.page.updatedAt || '').localeCompare(String(a.page.updatedAt || '')));
155
- const pageList = (scoredPages.length ? scoredPages : pages.map((page) => ({ page, score: 0 })))
331
+ // 用例命不中任何页面时不再塞无关页面;返回空列表并让 gaps 说明原因。
332
+ const pageList = scoredPages
156
333
  .slice(0, limitsValue.pages)
157
334
  .map((item) => compactPage(item.page));
158
335
 
159
336
  const processList = processes
160
337
  .filter((process) => {
161
- if (caseId && (String(process.caseId || '') === String(caseId) || String(process.id || '') === processId)) return true;
338
+ if (caseId && String(process.caseId || '') === String(caseId)) return true;
162
339
  return lookupQuery ? matchesText(process, lookupQuery) : false;
163
340
  })
164
341
  .slice(0, limitsValue.processes)
165
342
  .map(compactProcess);
166
343
 
344
+ // 用例执行经验是证据而非正典,但对同一用例的下一次执行最有参考价值;
345
+ // 页面备注/人工反馈按本次命中的页面关联,避免把别的页面证据带进来。
346
+ const selectedPageIds = new Set(pageList.map((page) => page.id).filter(Boolean));
347
+ const experienceList = readExperiences(config, { limit: 2000 })
348
+ .filter((experience) => isExperienceKind(experience.kind))
349
+ .filter((experience) => {
350
+ if (caseId && String(experience.caseId || '') === String(caseId)) return true;
351
+ if (
352
+ caseId &&
353
+ ['page-note', 'page-feedback'].includes(experience.kind) &&
354
+ selectedPageIds.has(experience.pageId)
355
+ ) {
356
+ return true;
357
+ }
358
+ return lookupQuery ? matchesText(experience, lookupQuery) : false;
359
+ })
360
+ .slice(-limitsValue.processes)
361
+ .map(compactExperience);
362
+
167
363
  const businessList = business
168
364
  .filter((item) => (lookupQuery ? matchesText(item, lookupQuery) : false))
169
365
  .slice(0, limitsValue.business)
@@ -175,12 +371,11 @@ export function knowledgeContextForCase(config, { caseId = '', query = '', limit
175
371
 
176
372
  const lessons = readLearnings(config, { limit: 500 })
177
373
  .filter((item) => {
178
- if (!lookupQuery) return ['agent-correction', 'agent-success', 'run-failure'].includes(item.kind);
179
- const detail = JSON.stringify(item.detail || {});
180
- return (
181
- ['agent-correction', 'agent-success', 'run-failure'].includes(item.kind) &&
182
- (detail.includes(caseId) || detail.toLowerCase().includes(lookupQuery))
183
- );
374
+ if (!EXECUTION_LEARNING_KINDS.includes(item.kind)) return false;
375
+ if (caseId && String(item.caseId || '') === String(caseId)) return true;
376
+ const detail = JSON.stringify(item.detail || {}).toLowerCase();
377
+ if (!lookupQuery) return !caseId;
378
+ return detail.includes(lookupQuery) || (caseId ? detail.includes(String(caseId).toLowerCase()) : false);
184
379
  })
185
380
  .slice(-limitsValue.learnings)
186
381
  .map(compactLearning);
@@ -194,6 +389,51 @@ export function knowledgeContextForCase(config, { caseId = '', query = '', limit
194
389
  note: clean(entry.note, 1200),
195
390
  }));
196
391
 
392
+ // 同用例执行经验优先占用配额,正典流程补足剩余位置,避免经验被长流程全部挤掉。
393
+ const experienceBudget = Math.min(experienceList.length, Math.max(1, Math.ceil(limitsValue.processes / 2)));
394
+ const processBudget = Math.max(0, limitsValue.processes - experienceBudget);
395
+ const combinedProcesses = [...experienceList.slice(0, experienceBudget), ...processList.slice(0, processBudget)];
396
+
397
+ let allFacts = [];
398
+ let factsError = '';
399
+ try {
400
+ allFacts = asArray(loadFacts(config).facts);
401
+ } catch (error) {
402
+ factsError = String(error?.message || error);
403
+ }
404
+ const entityInfo = factEntityTerms({
405
+ fullQuery,
406
+ pageList,
407
+ documents: asArray(knowledge?.documents?.documents),
408
+ knowledge,
409
+ facts: allFacts,
410
+ });
411
+ const matchedFacts = entityInfo.terms.length
412
+ ? queryFacts(allFacts, { entities: entityInfo.terms, statuses: ['verified', 'candidate', 'conflicted'], limit: 30 })
413
+ : [];
414
+ const staleFacts = entityInfo.terms.length
415
+ ? queryFacts(allFacts, { entities: entityInfo.terms, statuses: ['deprecated'], limit: 10 })
416
+ : [];
417
+ const pagesById = new Map(pages.map((page) => [String(page.id || ''), page]));
418
+ const gaps = buildFactGaps({
419
+ pageList,
420
+ pagesById,
421
+ documents: entityInfo.documents,
422
+ roles: entityInfo.roles,
423
+ facts: allFacts,
424
+ });
425
+ if (!entityInfo.terms.length) gaps.push({ type: 'entities-empty', detail: '用例没有识别出页面/单据/角色实体', ref: '' });
426
+ if (matchedFacts.some((fact) => fact.status === 'conflicted')) {
427
+ gaps.push({ type: 'fact-conflict', detail: '命中事实存在未裁决冲突,执行前需以真实页面为准', ref: '' });
428
+ }
429
+ if (staleFacts.length) {
430
+ gaps.push({ type: 'fact-stale', detail: '命中事实已连续多轮未观察到,可能过期', ref: String(staleFacts.length) });
431
+ }
432
+ if (factsError) gaps.push({ type: 'facts-read-failed', detail: '事实库读取失败:' + factsError, ref: '' });
433
+ if (!pageList.length) {
434
+ gaps.push({ type: 'page-no-match', detail: '用例没有命中任何页面知识;先 learn page 或用 --query 指定页面', ref: caseId || '' });
435
+ }
436
+
197
437
  return {
198
438
  ok: true,
199
439
  generatedAt: nowIso(),
@@ -202,22 +442,33 @@ export function knowledgeContextForCase(config, { caseId = '', query = '', limit
202
442
  caseTitle: caseItem?.functionPoint || caseItem?.title || '',
203
443
  instruction:
204
444
  '先读本结果的页面动作、流程步骤、纠错经验与执行复盘,再决定动作;动作失败、截图评估 issue 或页面与知识不符时重新查询。' +
205
- '知识只作提示,冲突时以 snapshot 的真实页面为准,并用 comment 说明取舍。',
445
+ '事实只作提示,冲突时以 snapshot 的真实页面为准,并用 comment 说明取舍;gaps 列出知识缺口,不代表页面一定有问题。',
206
446
  summary: {
207
447
  pages: pageList.length,
208
- processes: processList.length,
448
+ processes: combinedProcesses.length,
449
+ experiences: experienceList.length,
209
450
  business: businessList.length,
210
451
  learnings: lessons.length,
211
452
  feedback: feedback.length,
212
- corrections: processList.reduce((sum, item) => sum + item.corrections.length, 0),
213
- reviews: processList.reduce((sum, item) => sum + item.reviews.length, 0),
453
+ corrections: combinedProcesses.reduce((sum, item) => sum + item.corrections.length, 0),
454
+ reviews: combinedProcesses.reduce((sum, item) => sum + item.reviews.length, 0),
455
+ facts: matchedFacts.length,
456
+ gaps: gaps.length,
214
457
  central: Array.isArray(central) ? central.length : 0,
215
458
  },
216
459
  pages: pageList,
217
- processes: processList,
460
+ processes: combinedProcesses,
218
461
  business: businessList,
219
462
  learnings: lessons,
220
463
  feedback,
464
+ retrieval: {
465
+ entities: entityInfo.terms,
466
+ roles: entityInfo.roles,
467
+ documents: entityInfo.documents.map((doc) => ({ id: doc.id || '', title: doc.title || '' })),
468
+ glossaryTerms: entityInfo.glossaryTerms,
469
+ },
470
+ facts: matchedFacts.map(compactFact),
471
+ gaps,
221
472
  central: Array.isArray(central) ? central : [],
222
473
  };
223
474
  }
@@ -235,12 +486,15 @@ function fallbackKnowledgeContext({ caseId, query, central, centralStatus, error
235
486
  query: String(query || ''),
236
487
  caseTitle: '',
237
488
  instruction: '知识库读取失败;先用 snapshot 读真实页面,再决定动作。',
238
- summary: { pages: 0, processes: 0, business: 0, learnings: 0, feedback: 0, corrections: 0, reviews: 0, central: central.length },
489
+ summary: { pages: 0, processes: 0, business: 0, learnings: 0, feedback: 0, corrections: 0, reviews: 0, facts: 0, gaps: 1, central: central.length },
239
490
  pages: [],
240
491
  processes: [],
241
492
  business: [],
242
493
  learnings: [],
243
494
  feedback: [],
495
+ retrieval: { entities: [], roles: [], documents: [], glossaryTerms: [] },
496
+ facts: [],
497
+ gaps: [{ type: 'knowledge-read-failed', detail: '知识库读取失败:' + String(error?.message || error || ''), ref: '' }],
244
498
  central,
245
499
  authority: centralAuthority(centralStatus),
246
500
  centralStatus: { ...centralStatus, error: centralStatus.error || String(error?.message || error || '') },
@@ -252,12 +506,14 @@ function fallbackKnowledgeContext({ caseId, query, central, centralStatus, error
252
506
  */
253
507
  export async function loadKnowledgeContext(config, { caseId = '', query = '', limits = {}, forceCreateData = false } = {}) {
254
508
  let caseQuery = '';
509
+ let caseItem = null;
255
510
  if (caseId) {
256
511
  try {
257
- const found = findCase(loadProjectCases(config).cases, caseId)?.case;
258
- caseQuery = [found?.functionPoint, found?.precondition, found?.steps].filter(Boolean).join(' ').slice(0, 800);
512
+ caseItem = findCase(loadProjectCases(config).cases, caseId)?.case || null;
513
+ caseQuery = [caseItem?.functionPoint, caseItem?.precondition, caseItem?.steps].filter(Boolean).join(' ').slice(0, 800);
259
514
  } catch {
260
515
  caseQuery = '';
516
+ caseItem = null;
261
517
  }
262
518
  }
263
519
  const searchQuery = [query, caseQuery, caseId].filter(Boolean).join(' ').trim();
@@ -267,11 +523,29 @@ export async function loadKnowledgeContext(config, { caseId = '', query = '', li
267
523
  } catch (error) {
268
524
  central = { enabled: true, ok: false, results: [], error: String(error?.message || error) };
269
525
  }
270
- const results = Array.isArray(central.results) ? central.results : [];
526
+ let results = Array.isArray(central.results) ? central.results : [];
527
+ let evidenceFallback = false;
528
+ // 知识组没有命中时再查证据组;证据组保存的是同用例历史执行叙事,平时只写不读。
529
+ if (caseId && results.length === 0 && central.enabled === true && central.ok === true) {
530
+ try {
531
+ const evidence = await centralSearch(config, {
532
+ query: searchQuery,
533
+ limit: 5,
534
+ groupIds: [centralConfig(config).evidenceGroupId],
535
+ });
536
+ if (evidence.ok === true && Array.isArray(evidence.results) && evidence.results.length) {
537
+ results = evidence.results.map((item) => ({ ...item, source: 'evidence' }));
538
+ evidenceFallback = true;
539
+ }
540
+ } catch {
541
+ /* 证据组回读失败不影响本地知识 */
542
+ }
543
+ }
271
544
  const centralStatus = {
272
545
  enabled: central.enabled === true,
273
546
  ok: central.ok === true,
274
547
  count: results.length,
548
+ evidenceFallback,
275
549
  error: String(central.error || ''),
276
550
  };
277
551
  let playbooks = [];
@@ -300,7 +574,11 @@ export async function loadKnowledgeContext(config, { caseId = '', query = '', li
300
574
  }
301
575
  }
302
576
  try {
303
- const local = knowledgeContextForCase(config, { caseId, query, limits, central: results });
577
+ const local = knowledgeContextForCase(config, { caseId, query, limits, central: results, caseItem });
578
+ if (centralStatus.enabled && centralStatus.ok && !results.length) {
579
+ local.gaps = [...asArray(local.gaps), { type: 'central-no-hits', detail: '中心知识库没有命中,当前只有本地知识', ref: '' }];
580
+ local.summary = { ...local.summary, gaps: local.gaps.length };
581
+ }
304
582
  return { ...local, playbooks, authority: centralAuthority(centralStatus), centralStatus };
305
583
  } catch (error) {
306
584
  return { ...fallbackKnowledgeContext({ caseId, query, central: results, centralStatus, error }), playbooks };