dsh-uitest 2.3.0 → 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 +76 -11
  2. package/bin/uitest.mjs +189 -11
  3. package/client.js +222 -25
  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 +176 -25
  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 +143 -6
  49. package/studio/knowledge.mjs +279 -42
  50. package/studio/snapshot.mjs +6 -1
@@ -18,10 +18,18 @@ export function centralConfig(config) {
18
18
  const raw = config?.knowledge?.central || {};
19
19
  const url = String(process.env.UITEST_KNOWLEDGE_URL || raw.url || '').replace(/\/+$/, '');
20
20
  const groupId = String(process.env.UITEST_KNOWLEDGE_GROUP || raw.groupId || 'oms-v2-test');
21
+ const groupFromEnv = Boolean(process.env.UITEST_KNOWLEDGE_GROUP);
22
+ const evidenceGroupId = String(
23
+ process.env.UITEST_KNOWLEDGE_EVIDENCE_GROUP
24
+ || (groupFromEnv ? groupId + '-evidence' : '')
25
+ || raw.evidenceGroupId
26
+ || groupId + '-evidence',
27
+ );
21
28
  return {
22
29
  enabled: raw.enabled !== false && Boolean(url),
23
30
  url,
24
31
  groupId,
32
+ evidenceGroupId,
25
33
  timeoutMs: Math.max(3000, Number(raw.timeoutMs) || 300000),
26
34
  batchSize: Math.max(1, Number(raw.batchSize) || 2),
27
35
  searchTimeoutMs: Math.max(1000, Number(raw.searchTimeoutMs) || 10000),
@@ -47,6 +55,23 @@ export function stableHash(value) {
47
55
  return crypto.createHash('sha1').update(text).digest('hex');
48
56
  }
49
57
 
58
+ const fastUpsertCache = new Map();
59
+
60
+ async function centralSupportsFastUpsert(config) {
61
+ const central = centralConfig(config);
62
+ const cached = fastUpsertCache.get(central.url);
63
+ if (cached && Date.now() - cached.at < 60000) return cached.value;
64
+ let value = false;
65
+ try {
66
+ const payload = await requestJson(config, '/health', { timeoutMs: 5000 });
67
+ value = payload?.fast_upsert === true;
68
+ } catch {
69
+ value = false;
70
+ }
71
+ fastUpsertCache.set(central.url, { at: Date.now(), value });
72
+ return value;
73
+ }
74
+
50
75
  async function requestJson(config, pathname, { method = 'GET', body, timeoutMs } = {}) {
51
76
  const central = centralConfig(config);
52
77
  if (!central.enabled) throw new CentralKnowledgeError('中心知识库未启用', { code: 'CENTRAL_DISABLED' });
@@ -90,17 +115,36 @@ export async function centralHealth(config) {
90
115
  return { enabled: true, ok: payload?.ok === true, service: payload?.service || '', url: central.url, groupId: central.groupId };
91
116
  }
92
117
 
93
- export async function centralStats(config) {
118
+ export async function centralStats(config, { groupId = '' } = {}) {
94
119
  const central = centralConfig(config);
95
- if (!central.enabled) return { enabled: false, ok: false, groupId: central.groupId, nodes: [], edges: [] };
96
- const payload = await requestJson(config, '/stats?group_id=' + encodeURIComponent(central.groupId), { timeoutMs: 5000 });
97
- return { enabled: true, ok: true, groupId: central.groupId, nodes: payload?.nodes || [], edges: payload?.edges || [] };
120
+ const group = String(groupId || central.groupId);
121
+ if (!central.enabled) return { enabled: false, ok: false, groupId: group, nodes: [], edges: [] };
122
+ const payload = await requestJson(config, '/stats?group_id=' + encodeURIComponent(group), { timeoutMs: 5000 });
123
+ return { enabled: true, ok: true, groupId: group, nodes: payload?.nodes || [], edges: payload?.edges || [] };
124
+ }
125
+
126
+ /** 中心检索结果的有效性:invalid_at 已过期(或无法解析)的边不再作为知识提示。 */
127
+ export function isCentralResultValid(result, { at = nowIso() } = {}) {
128
+ const invalidAt = result?.invalid_at;
129
+ if (!invalidAt) return true;
130
+ const invalidMs = Date.parse(String(invalidAt));
131
+ if (!Number.isFinite(invalidMs)) return false;
132
+ const nowMs = Date.parse(String(at));
133
+ if (!Number.isFinite(nowMs)) return true;
134
+ return invalidMs > nowMs;
135
+ }
136
+
137
+ export function filterCentralResults(results, { at = nowIso() } = {}) {
138
+ const list = Array.isArray(results) ? results : [];
139
+ const valid = list.filter((result) => isCentralResultValid(result, { at }));
140
+ return { results: valid, filtered: list.length - valid.length };
98
141
  }
99
142
 
100
143
  export async function centralSearch(config, { query = '', limit = 10, groupIds = null } = {}) {
101
144
  const central = centralConfig(config);
145
+ const group = Array.isArray(groupIds) && groupIds.length ? groupIds[0] : central.groupId;
102
146
  if (!central.enabled || !String(query || '').trim()) {
103
- return { enabled: central.enabled, ok: false, groupId: central.groupId, results: [] };
147
+ return { enabled: central.enabled, ok: false, groupId: group, results: [] };
104
148
  }
105
149
  try {
106
150
  const payload = await requestJson(config, '/search', {
@@ -112,9 +156,16 @@ export async function centralSearch(config, { query = '', limit = 10, groupIds =
112
156
  num_results: Math.max(1, Math.min(50, Number(limit) || 10)),
113
157
  },
114
158
  });
115
- return { enabled: true, ok: true, groupId: central.groupId, results: payload?.results || [] };
159
+ const filtered = filterCentralResults(payload?.results || []);
160
+ return {
161
+ enabled: true,
162
+ ok: true,
163
+ groupId: group,
164
+ results: filtered.results,
165
+ invalidFiltered: filtered.filtered,
166
+ };
116
167
  } catch (error) {
117
- return { enabled: true, ok: false, groupId: central.groupId, results: [], error: String(error.message || error), code: error.code || '' };
168
+ return { enabled: true, ok: false, groupId: group, results: [], error: String(error.message || error), code: error.code || '' };
118
169
  }
119
170
  }
120
171
 
@@ -194,6 +245,62 @@ export async function centralDeleteEpisode(config, { uuid = '', groupId = '' } =
194
245
  }
195
246
  }
196
247
 
248
+ /**
249
+ * 调用中心 LLM 生成知识摘要。items 为 [{id, kind, title, text}]。
250
+ * 失败时返回 ok:false,由调用方保留旧摘要;不会静默写入半成品。
251
+ */
252
+ export async function centralSummarize(config, { items = [], maxChars = 160 } = {}) {
253
+ const central = centralConfig(config);
254
+ const base = { enabled: central.enabled, items: [], error: '' };
255
+ if (!central.enabled) return { ok: false, ...base, error: '中心知识库未启用', code: 'CENTRAL_DISABLED' };
256
+ if (!Array.isArray(items) || !items.length) return { ok: false, ...base, error: '没有待摘要条目' };
257
+ try {
258
+ const payload = await requestJson(config, '/summarize', {
259
+ method: 'POST',
260
+ body: {
261
+ max_chars: Math.max(80, Math.min(400, Number(maxChars) || 160)),
262
+ items: items.map((item) => ({
263
+ id: String(item.id || ''),
264
+ kind: String(item.kind || ''),
265
+ title: String(item.title || ''),
266
+ text: String(item.text || ''),
267
+ })),
268
+ },
269
+ timeoutMs: Math.max(central.timeoutMs, 120000),
270
+ });
271
+ return { ok: true, ...base, items: Array.isArray(payload?.items) ? payload.items : [], engine: payload?.engine || 'llm' };
272
+ } catch (error) {
273
+ return { ok: false, ...base, error: String(error.message || error), code: error.code || '' };
274
+ }
275
+ }
276
+
277
+ /**
278
+ * 整组重置中心知识库:删除该组全部节点与关系,用于净室重建。
279
+ * 破坏性操作,必须显式 confirm=true;由服务端负责暂停/恢复自动流水线。
280
+ */
281
+ export async function centralResetGroup(config, { groupId = '', confirm = false } = {}) {
282
+ const central = centralConfig(config);
283
+ const group = String(groupId || central.groupId);
284
+ const base = { enabled: central.enabled, groupId: group, deleted: 0, remaining: null };
285
+ if (!central.enabled) return { ok: false, ...base, error: '中心知识库未启用' };
286
+ if (!confirm) return { ok: false, ...base, error: '整组重置需要 confirm=true', code: 'CENTRAL_CONFIRM_REQUIRED' };
287
+ try {
288
+ const payload = await requestJson(config, '/groups/' + encodeURIComponent(group) + '/reset', {
289
+ method: 'POST',
290
+ body: { confirm: true },
291
+ timeoutMs: Math.max(central.timeoutMs, 120000),
292
+ });
293
+ return {
294
+ ok: payload?.ok === true,
295
+ ...base,
296
+ deleted: Number(payload?.deleted) || 0,
297
+ remaining: payload?.remaining === undefined ? null : Number(payload.remaining) || 0,
298
+ };
299
+ } catch (error) {
300
+ return { ok: false, ...base, error: String(error.message || error), code: error.code || '' };
301
+ }
302
+ }
303
+
197
304
  /** 给历史 episode 补分类标记;幂等,可重复调用。 */
198
305
  export async function centralBackfillCategories(config, { groupId = '', force = false } = {}) {
199
306
  const central = centralConfig(config);
@@ -333,46 +440,81 @@ export async function centralSemanticIndex(config, { limit = 5, groupId = '' } =
333
440
  }
334
441
  }
335
442
 
336
- export async function centralStatus(config, { ttlMs = 30000 } = {}) { const central = centralConfig(config);
337
- if (!central.enabled) return { enabled: false, ok: false, url: '', groupId: central.groupId, nodes: [], edges: [] };
443
+ export async function centralStatus(config, { ttlMs = 30000 } = {}) {
444
+ const central = centralConfig(config);
445
+ if (!central.enabled) {
446
+ return { enabled: false, ok: false, url: '', groupId: central.groupId, evidenceGroupId: central.evidenceGroupId, nodes: [], edges: [] };
447
+ }
338
448
  const file = centralSyncFile(config).replace(/knowledge-central-ingested\.json$/, 'knowledge-central-status.json');
339
449
  const cached = readJson(file, null);
340
- if (cached && Date.now() - new Date(cached.at || 0).getTime() < ttlMs) return cached;
450
+ if (cached && Date.now() - new Date(cached.at || 0).getTime() < ttlMs) {
451
+ return { ...cached, evidenceGroupId: central.evidenceGroupId };
452
+ }
341
453
  try {
342
454
  const [health, stats] = await Promise.all([centralHealth(config), centralStats(config)]);
343
- const value = { ...health, ...stats, at: nowIso() };
455
+ const value = { ...health, ...stats, evidenceGroupId: central.evidenceGroupId, at: nowIso() };
344
456
  writeJson(file, value);
345
457
  return value;
346
458
  } catch (error) {
347
- return { enabled: true, ok: false, url: central.url, groupId: central.groupId, nodes: [], edges: [], error: String(error.message || error), at: nowIso() };
459
+ return { enabled: true, ok: false, url: central.url, groupId: central.groupId, evidenceGroupId: central.evidenceGroupId, nodes: [], edges: [], error: String(error.message || error), at: nowIso() };
348
460
  }
349
461
  }
350
462
 
463
+ const CENTRAL_SYNC_STATE_VERSION = 2;
464
+
465
+ /** 同步去重键带 group:同一 Episode 可以同时存在于知识组与证据组。 */
466
+ export function centralSyncEntryKey(groupId, key) {
467
+ return String(groupId) + '\0' + String(key);
468
+ }
469
+
351
470
  export function readCentralSyncState(config) {
352
- return readJson(centralSyncFile(config), { version: 1, entries: {} });
471
+ const state = readJson(centralSyncFile(config), { version: CENTRAL_SYNC_STATE_VERSION, entries: {} });
472
+ if (Number(state?.version) < CENTRAL_SYNC_STATE_VERSION || !state.entries || typeof state.entries !== 'object') {
473
+ return { version: CENTRAL_SYNC_STATE_VERSION, entries: {} };
474
+ }
475
+ return state;
353
476
  }
354
477
 
355
478
  export function saveCentralSyncState(config, state) {
356
- writeJson(centralSyncFile(config), state);
479
+ writeJson(centralSyncFile(config), { ...state, version: CENTRAL_SYNC_STATE_VERSION });
480
+ }
481
+
482
+ /** 清空某个 group 的本地同步去重记录,使清库后可以重新全量写入。 */
483
+ export function clearCentralSyncGroup(config, { groupId = '' } = {}) {
484
+ const group = String(groupId);
485
+ if (!group) return 0;
486
+ const state = readCentralSyncState(config);
487
+ const entries = state.entries && typeof state.entries === 'object' ? state.entries : {};
488
+ const prefix = group + '\0';
489
+ let removed = 0;
490
+ for (const key of Object.keys(entries)) {
491
+ if (!key.startsWith(prefix)) continue;
492
+ delete entries[key];
493
+ removed += 1;
494
+ }
495
+ if (removed) saveCentralSyncState(config, { ...state, entries });
496
+ return removed;
357
497
  }
358
498
 
359
499
  /**
360
500
  * 增量写入中心库。相同 key + 相同内容的 Episode 默认跳过,避免重复导入。
361
- * @returns {Promise<{enabled:boolean, total:number, ingested:number, skipped:number, failed:number, results:object[], errors:object[]}>}
501
+ * @returns {Promise<{enabled:boolean, total:number, ingested:number, skipped:number, failed:number, results:object[], errors:object[], mode:string}>}
362
502
  */
363
- export async function centralIngest(config, { episodes = [], groupId = '', dedupe = true } = {}) {
503
+ export async function centralIngest(config, { episodes = [], groupId = '', dedupe = true, fast = false, onProgress = null } = {}) {
364
504
  const central = centralConfig(config);
365
505
  if (!central.enabled) {
366
- return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [] };
506
+ return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [], mode: 'classic' };
367
507
  }
368
- const state = dedupe ? readCentralSyncState(config) : { version: 1, entries: {} };
508
+ const group = groupId || central.groupId;
509
+ const mode = fast && (await centralSupportsFastUpsert(config)) ? 'fast' : 'classic';
510
+ const state = dedupe ? readCentralSyncState(config) : { version: CENTRAL_SYNC_STATE_VERSION, entries: {} };
369
511
  const entries = state.entries && typeof state.entries === 'object' ? state.entries : {};
370
512
  const pending = [];
371
513
  const pendingKeys = new Set();
372
514
  let skipped = 0;
373
515
  for (const episode of episodes) {
374
516
  if (!episode?.name) continue;
375
- const key = episode.key || episode.name;
517
+ const key = centralSyncEntryKey(group, episode.key || episode.name);
376
518
  const hash = stableHash({ body: episode.body, source: episode.source || 'json', sourceDescription: episode.source_description || '' });
377
519
  if (pendingKeys.has(key) || (dedupe && entries[key] === hash)) { skipped += 1; continue; }
378
520
  pendingKeys.add(key);
@@ -381,22 +523,29 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
381
523
  const results = [];
382
524
  const errors = [];
383
525
  let ingested = 0;
384
- const batchSize = Math.max(1, Number(central.batchSize) || 5);
526
+ const batchSize = mode === 'fast'
527
+ ? Math.max(10, Number(central.batchSize || 2) * 5)
528
+ : Math.max(1, Number(central.batchSize) || 5);
529
+ // 已同步的 Episode 也计入进度,否则批次 stage 的 done 永远到不了 total。
530
+ const dedupeSkipped = skipped;
531
+ const progressTotal = pending.length + dedupeSkipped;
532
+ if (onProgress) await onProgress({ done: dedupeSkipped, total: progressTotal, mode });
385
533
  for (let offset = 0; offset < pending.length; offset += batchSize) {
386
534
  const chunk = pending.slice(offset, offset + batchSize);
387
535
  try {
388
- const payload = await requestJson(config, '/ingest', {
536
+ const payload = await requestJson(config, mode === 'fast' ? '/ingest-fast' : '/ingest', {
389
537
  method: 'POST',
390
538
  body: {
391
- group_id: groupId || central.groupId,
539
+ group_id: group,
392
540
  episodes: chunk.map((episode) => ({
393
541
  name: episode.name,
394
542
  body: typeof episode.body === 'string' ? episode.body : JSON.stringify(episode.body),
395
543
  source_description: episode.source_description || 'uitest',
396
544
  reference_time: episode.reference_time || nowIso(),
397
545
  source: episode.source || 'json',
398
- group_id: episode.group_id || groupId || central.groupId,
546
+ group_id: group,
399
547
  replace_prefix: episode.replace_prefix || null,
548
+ ...(mode === 'fast' ? { upsert: true } : {}),
400
549
  })),
401
550
  },
402
551
  timeoutMs: central.timeoutMs,
@@ -415,8 +564,9 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
415
564
  } catch (error) {
416
565
  errors.push({ ok: false, error: String(error.message || error), count: chunk.length, names: chunk.map((entry) => entry.name) });
417
566
  }
567
+ if (onProgress) await onProgress({ done: dedupeSkipped + offset + chunk.length, total: progressTotal, mode });
418
568
  }
419
- if (dedupe) saveCentralSyncState(config, { version: 1, updatedAt: nowIso(), entries });
569
+ if (dedupe) saveCentralSyncState(config, { updatedAt: nowIso(), entries });
420
570
  const failed = errors.reduce((sum, item) => sum + (Number(item.count) || 1), 0);
421
571
  return {
422
572
  enabled: true,
@@ -426,7 +576,8 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
426
576
  failed,
427
577
  results,
428
578
  errors,
429
- groupId: groupId || central.groupId,
579
+ mode,
580
+ groupId: group,
430
581
  url: central.url,
431
582
  };
432
583
  }