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
package/lib/learn-run.mjs CHANGED
@@ -8,8 +8,10 @@ import crypto from 'node:crypto';
8
8
  import { resolveUrl } from './config.mjs';
9
9
  import {
10
10
  KnowledgeError,
11
+ appendExperiences,
11
12
  appendLearning,
12
13
  isGenericSystemTitle,
14
+ isPortalShellLearnObservation,
13
15
  loadFlowForRun,
14
16
  loadKnowledge,
15
17
  mergePage,
@@ -17,6 +19,7 @@ import {
17
19
  resolveRunDir,
18
20
  saveKnowledge,
19
21
  } from './knowledge.mjs';
22
+ import { canonicalPageUrl, dialogBaseMatches, dialogPageTitle, dialogTitleMatches, findDialogPageForLearn, findPageForTitleAndUrlToken, findStubPageForTitle, isCaseReferenced, isDialogPageRecord, isInstanceValueText, isStructuredPage, pageTitleFromUrl, pageUrlKey } from './knowledge-clean.mjs';
20
23
  import { readPageObservations } from './run-observe.mjs';
21
24
  import { createLogger, hasTemplate, nowIso, slug } from './util.mjs';
22
25
 
@@ -84,7 +87,7 @@ function pageContentKey(page) {
84
87
  }
85
88
 
86
89
  function sameUrl(a, b) {
87
- return String(a || '').replace(/\/+$/, '') === String(b || '').replace(/\/+$/, '');
90
+ return pageUrlKey(a) === pageUrlKey(b);
88
91
  }
89
92
 
90
93
  function shortUrlHash(url) {
@@ -136,22 +139,28 @@ function readRunJson(runDir) {
136
139
  }
137
140
  }
138
141
 
139
- /** 把观察 URL 映射回配置的 urlName(与 learn page 的 matchersForPage 一致)。 */
140
- export function urlNameForUrl(config, url) {
142
+ /**
143
+ * 把观察 URL 映射回 urlName(与 learn page 的 matchersForPage 一致)。
144
+ * 配置 urls 优先;配置未覆盖时用已学习的 system.urls 兜底,避免同一页面另建一份。
145
+ */
146
+ export function urlNameForUrl(config, url, knownUrls = null) {
141
147
  const target = String(url || '');
142
148
  if (!target) return '';
143
- for (const [name, value] of Object.entries(config?.urls || {})) {
144
- try {
145
- const resolved = resolveUrl(config, value);
146
- if (resolved === target) return name;
147
- const a = new URL(resolved);
148
- const b = new URL(target);
149
- if (a.pathname === b.pathname && a.search === b.search && a.hash === b.hash) return name;
150
- } catch {
151
- /* 忽略非法 URL 配置项 */
149
+ const findName = (entries) => {
150
+ for (const [name, value] of Object.entries(entries || {})) {
151
+ try {
152
+ const resolved = resolveUrl(config, value);
153
+ if (resolved === target) return name;
154
+ const a = new URL(resolved);
155
+ const b = new URL(target);
156
+ if (a.pathname === b.pathname && a.search === b.search && a.hash === b.hash) return name;
157
+ } catch {
158
+ /* 忽略非法 URL 配置项 */
159
+ }
152
160
  }
153
- }
154
- return '';
161
+ return '';
162
+ };
163
+ return findName(config?.urls) || findName(knownUrls);
155
164
  }
156
165
 
157
166
  /** URL → 稳定 slug(去掉协议/主机/尾斜杠,SPA hash 保留;取不到时返回空串)。 */
@@ -170,15 +179,29 @@ export function urlSlugOf(url) {
170
179
  }
171
180
  }
172
181
 
173
- function resolveObservationPage(config, observation, { pages, workingPages }) {
174
- const urlName = urlNameForUrl(config, observation.url);
182
+ function resolveObservationPage(config, observation, { pages, workingPages, systemUrls = {} }) {
183
+ const urlName = urlNameForUrl(config, observation.url, systemUrls);
184
+ // 弹窗与基础页共享 URL;弹窗页不能被当成基础页,否则运行观察会把基础页内容并进弹窗。
175
185
  const matches = (page) =>
176
- Boolean(page) && ((urlName && page.urlName === urlName) || (page.url && sameUrl(page.url, observation.url)));
186
+ Boolean(page) && !isDialogPageRecord(page) && ((urlName && page.urlName === urlName) || (page.url && sameUrl(page.url, observation.url)));
177
187
  for (const working of workingPages.values()) {
178
188
  if (matches(working.page)) return { id: working.id, working, matched: true, urlName: working.page.urlName || urlName };
179
189
  }
180
190
  const existing = pages.find(matches);
181
191
  if (existing) return { id: existing.id, working: null, matched: true, urlName: existing.urlName || urlName };
192
+ // 文档派生的占位页没有 URL/urlName,按标题/别名认领,避免测试到的页面另建一份。
193
+ const observedTitle = cleanLine(observation.title, 120);
194
+ if (observedTitle && !isGenericSystemTitle(observedTitle)) {
195
+ const stub = findStubPageForTitle(pages, observedTitle);
196
+ if (stub && !isDialogPageRecord(stub) && !workingPages.has(stub.id)) {
197
+ return { id: stub.id, working: null, matched: true, urlName, promoted: true };
198
+ }
199
+ // 同一页面可能从不同路由(/ebdapp/... 与 /sp/ebdpage/...)观察;标题 + 共享长页面 ID 视为同一页。
200
+ const routeMatch = findPageForTitleAndUrlToken(pages, observedTitle, observation.url);
201
+ if (routeMatch && !isDialogPageRecord(routeMatch) && !workingPages.has(routeMatch.id)) {
202
+ return { id: routeMatch.id, working: null, matched: true, urlName: routeMatch.urlName || urlName };
203
+ }
204
+ }
182
205
  let id = urlName ? slug(urlName).toLowerCase() : '';
183
206
  if (!id && observation.title && !isGenericSystemTitle(observation.title)) {
184
207
  id = slug(observation.title).toLowerCase();
@@ -196,11 +219,31 @@ function resolveObservationPage(config, observation, { pages, workingPages }) {
196
219
  }
197
220
 
198
221
  function dialogPageId(baseId, dialog) {
199
- const title = cleanLine(dialog?.title || '', LEARN_RUN_LIMITS.dialogSlug);
222
+ // 与 learn page --click 共用去实例后缀规则,避免同一弹窗因标题带单号另建一页。
223
+ const title = cleanLine(dialogPageTitle(dialog?.title) || dialog?.title || '', LEARN_RUN_LIMITS.dialogSlug);
200
224
  const suffix = title ? slug(title).toLowerCase() : 'dialog';
201
225
  return `${baseId}-dialog-${suffix || 'dialog'}`;
202
226
  }
203
227
 
228
+ /**
229
+ * 运行观察的弹窗页 id:先认领已有弹窗页(按标题 + 基础页/URL),
230
+ * 避免同一弹窗被 learn page 与运行学习各建一份。
231
+ */
232
+ function resolveDialogPageId({ pages, workingPages, generatedId, title, resolvedId, observation }) {
233
+ if (workingPages.has(generatedId)) return generatedId;
234
+ if (pages.some((page) => String(page.id) === generatedId)) return generatedId;
235
+ const matches = new Set();
236
+ for (const [id, working] of workingPages) {
237
+ if (!isDialogPageRecord(working.page) || !dialogTitleMatches(working.page, title)) continue;
238
+ if (dialogBaseMatches(working.page, { pages, basePageId: resolvedId, url: observation?.url })) matches.add(id);
239
+ }
240
+ if (!matches.size) {
241
+ const existing = findDialogPageForLearn(pages, { title, basePageId: resolvedId, url: observation?.url });
242
+ if (existing) return String(existing.id);
243
+ }
244
+ return matches.size === 1 ? [...matches][0] : generatedId;
245
+ }
246
+
204
247
  /* ------------------------------------------------------------------ */
205
248
  /* 观察 → 页面补丁 */
206
249
  /* ------------------------------------------------------------------ */
@@ -209,15 +252,27 @@ function pageTitleFromObservation(observation, { existing, urlName }) {
209
252
  if (existing?.title) return existing.title;
210
253
  const observed = cleanLine(observation.title, 120);
211
254
  if (observed && !isGenericSystemTitle(observed)) return observed;
255
+ const fromUrl = pageTitleFromUrl(observation.url);
256
+ if (fromUrl) return fromUrl;
212
257
  if (urlName) return urlName;
213
258
  return cleanLine(observation.path, 120) || observation.url || observation.stepId || '';
214
259
  }
215
260
 
261
+ /** 弹窗正文只保留结构文本:单号、数据行、分页与日期时间都是实例,不进正典。 */
262
+ function canonicalDialogText(value) {
263
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
264
+ if (!text || isCaseReferenced(text) || isInstanceValueText(text)) return '';
265
+ return text;
266
+ }
267
+
216
268
  function keywordsFromObservation(observation, { dialog = false } = {}) {
217
269
  const list = [];
218
270
  if (dialog) {
219
- list.push(observation.dialog?.title || '');
220
- list.push(...String(observation.dialog?.text || '').split('\n').slice(0, 8));
271
+ list.push(canonicalDialogText(observation.dialog?.title || ''));
272
+ list.push(...String(observation.dialog?.text || '').split('\n').slice(0, 8).map(canonicalDialogText));
273
+ list.push(...(observation.dialog?.headings || []).map(canonicalDialogText));
274
+ list.push(...(observation.dialog?.tableHeaders || []).map(canonicalDialogText));
275
+ list.push(...(observation.dialog?.fields || []).map(canonicalDialogText));
221
276
  } else {
222
277
  const observed = cleanLine(observation.title, 60);
223
278
  if (observed && !isGenericSystemTitle(observed)) list.push(observed);
@@ -230,8 +285,10 @@ function keywordsFromObservation(observation, { dialog = false } = {}) {
230
285
  function textsFromObservation(observation, { dialog = false } = {}) {
231
286
  const list = [];
232
287
  if (dialog) {
233
- list.push(observation.dialog?.title || '');
234
- list.push(...String(observation.dialog?.text || '').split('\n'));
288
+ list.push(canonicalDialogText(observation.dialog?.title || ''));
289
+ list.push(...String(observation.dialog?.text || '').split('\n').map(canonicalDialogText));
290
+ list.push(...(observation.dialog?.headings || []).map(canonicalDialogText));
291
+ list.push(...(observation.dialog?.fields || []).map(canonicalDialogText));
235
292
  } else {
236
293
  list.push(...(observation.headings || []));
237
294
  list.push(...String(observation.text || '').split('\n').slice(0, 12));
@@ -267,7 +324,7 @@ function observationRefOf(observation, runDir) {
267
324
  };
268
325
  }
269
326
 
270
- function pagePatchFromObservation(observation, { id, urlName, existing, runDir }) {
327
+ function pagePatchFromObservation(observation, { id, urlName, existing }) {
271
328
  const patch = {
272
329
  id,
273
330
  title: pageTitleFromObservation(observation, { existing, urlName }),
@@ -276,38 +333,48 @@ function pagePatchFromObservation(observation, { id, urlName, existing, runDir }
276
333
  table: { headers: (observation.tableHeaders || []).slice(0, 40) },
277
334
  confidence: confidenceFromObservation(observation),
278
335
  source: existing?.source || 'learn-run',
279
- sources: [sourceOf(observation, runDir)],
280
- observations: [observationRefOf(observation, runDir)],
281
336
  };
282
337
  if (urlName) {
283
338
  patch.urlName = urlName;
284
- if (!existing || (!existing.urlName && existing.url)) patch.url = existing?.url || undefined;
339
+ // 占位页认领后补上实测入口,后续运行可直接按 URL 命中;已有 URL 的页面不覆盖。
340
+ if (!existing?.url) patch.url = canonicalPageUrl(observation.url) || undefined;
285
341
  } else {
286
- patch.url = observation.url || undefined;
342
+ patch.url = canonicalPageUrl(observation.url) || undefined;
287
343
  }
288
344
  return patch;
289
345
  }
290
346
 
291
- function dialogPagePatch(observation, { id, baseTitle, runDir }) {
347
+ function dialogPagePatch(observation, { id, baseTitle, baseId }) {
292
348
  const dialog = observation.dialog || {};
293
349
  const observedTitle = cleanLine(observation.title, 100);
294
350
  const title =
295
- cleanLine(dialog.title, 100) ||
296
- (observedTitle && !isGenericSystemTitle(observedTitle) ? `${observedTitle} · 弹窗` : '') ||
297
- baseTitle ||
298
- '弹窗';
299
- return {
351
+ canonicalDialogText(
352
+ cleanLine(dialogPageTitle(dialog.title), 100) ||
353
+ (observedTitle && !isGenericSystemTitle(observedTitle) ? `${observedTitle} · 弹窗` : '') ||
354
+ baseTitle ||
355
+ '弹窗',
356
+ ) || '弹窗';
357
+ const headers = uniqueNonEmpty((dialog.tableHeaders || []).map(canonicalDialogText), { max: 40, maxLength: 60 });
358
+ const fields = uniqueNonEmpty((dialog.fields || []).map(canonicalDialogText), { max: 40, maxLength: 60 });
359
+ const buttons = uniqueNonEmpty((dialog.buttons || []).map(canonicalDialogText), { max: 60, maxLength: 60 });
360
+ const inputs = Array.isArray(dialog.inputs) ? dialog.inputs : [];
361
+ const patch = {
300
362
  id,
301
363
  type: 'dialog',
302
364
  title,
365
+ basePageId: baseId || undefined,
303
366
  keywords: keywordsFromObservation(observation, { dialog: true }),
304
367
  texts: textsFromObservation(observation, { dialog: true }),
305
368
  confidence: confidenceFromObservation(observation, { dialog: true }),
306
369
  source: 'learn-run',
307
- sources: [sourceOf(observation, runDir)],
308
- observations: [observationRefOf(observation, runDir)],
309
- url: observation.url || undefined,
370
+ url: canonicalPageUrl(observation.url) || undefined,
310
371
  };
372
+ if (headers.length) patch.table = { headers };
373
+ if (fields.length || buttons.length || inputs.length) {
374
+ patch.regions = { observed: { inputs, buttons, fields } };
375
+ }
376
+ if (baseId) patch.notes = [`基础页面:${baseId}`];
377
+ return patch;
311
378
  }
312
379
 
313
380
  /* ------------------------------------------------------------------ */
@@ -335,8 +402,6 @@ function createWorkingPage(id, existing) {
335
402
  page: base,
336
403
  // 新建页面标注 type=page,弹窗页由 patch 覆盖成 dialog;已有页面不强行补字段
337
404
  type: existing ? existing.type || '' : 'page',
338
- sources: [...(existing?.sources || [])],
339
- observations: [...(existing?.observations || [])],
340
405
  pendingActions: [],
341
406
  originalActionIds: new Set((existing?.actions || []).map((action) => action.id)),
342
407
  };
@@ -345,10 +410,6 @@ function createWorkingPage(id, existing) {
345
410
  function applyPagePatch(working, patch) {
346
411
  working.page = mergePage(working.page, { ...patch, updatedAt: nowIso() });
347
412
  if (patch.type) working.type = patch.type;
348
- if (Array.isArray(patch.sources)) working.sources = unionBy(working.sources, patch.sources, sourceKey);
349
- if (Array.isArray(patch.observations)) {
350
- working.observations = unionBy(working.observations, patch.observations, observationKey);
351
- }
352
413
  }
353
414
 
354
415
  /** 动作合并:id 相同只保留最新 steps;内容不变时保持原 updatedAt(保证重复学习幂等)。 */
@@ -393,14 +454,14 @@ function dedupeActionsById(actions = []) {
393
454
  function finalizePage(working) {
394
455
  const page = { ...working.page, id: working.id };
395
456
  if (working.type) page.type = working.type;
396
- page.sources = unionBy(working.sources, [], sourceKey).slice(-LEARN_RUN_LIMITS.sources);
397
- page.observations = unionBy(working.observations, [], observationKey).slice(-LEARN_RUN_LIMITS.observations);
398
457
  page.texts = (page.texts || []).slice(-LEARN_RUN_LIMITS.texts);
399
458
  page.keywords = (page.keywords || []).slice(0, LEARN_RUN_LIMITS.keywords);
400
459
  page.actions = mergeActionsStable(page.actions || [], dedupeActionsById(working.pendingActions)).slice(
401
460
  0,
402
461
  LEARN_RUN_LIMITS.actions,
403
462
  );
463
+ // 认领的文档占位页一旦具备可复用结构,立即转为正典页,不必等下一次整理。
464
+ if (page.status === 'stub' && isStructuredPage(page)) page.status = 'canonical';
404
465
  return dropUndefined(page);
405
466
  }
406
467
 
@@ -495,7 +556,9 @@ export function isIgnorableObservation(observation = {}) {
495
556
  const url = String(observation.url || '');
496
557
  if (!url) return false;
497
558
  if (/^chrome-error:/i.test(url) || /^about:blank/i.test(url) || /^chrome:/i.test(url)) return true;
498
- return /\/login(?:[?#/]|$)/i.test(url) || /[/?]service=[^&]*login/i.test(url);
559
+ if (/\/login(?:[?#/]|$)/i.test(url) || /[/?]service=[^&]*login/i.test(url)) return true;
560
+ // PAGE 型路由首次进入可能只渲染应用门户/空白壳;把门户菜单当成目标页面内容会污染正典。
561
+ return isPortalShellLearnObservation(observation);
499
562
  }
500
563
 
501
564
  export function learnRunObservations(config, { runDir: runDirRef, logger } = {}) {
@@ -510,7 +573,7 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
510
573
  const warnings = badLines > 0 ? [`pages.jsonl 有 ${badLines} 行不是合法 JSON,已跳过`] : [];
511
574
  if (badLines > 0) log.warn(warnings[0]);
512
575
  if (ignored.length > 0) {
513
- const message = `已跳过 ${ignored.length} 条登录/错误页观察(不写入知识库)`;
576
+ const message = `已跳过 ${ignored.length} 条登录/错误/门户空白页观察(不写入知识库)`;
514
577
  warnings.push(message);
515
578
  log.info(message);
516
579
  }
@@ -523,6 +586,7 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
523
586
  actionsAdded: 0,
524
587
  observations: observations.length,
525
588
  ignored: ignored.length,
589
+ experiencesAdded: 0,
526
590
  learnedPages: [],
527
591
  learnedPageItems: [],
528
592
  observedPageItems: [],
@@ -535,6 +599,7 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
535
599
 
536
600
  const knowledge = loadKnowledge(config, { create: true });
537
601
  const pages = [...(knowledge.pages.pages || [])];
602
+ const systemUrls = knowledge?.system?.urls || {};
538
603
  const workingPages = new Map();
539
604
  const pageRefs = [];
540
605
 
@@ -549,7 +614,7 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
549
614
 
550
615
  // 1) 页面与弹窗页面(同 url/urlName 合并;弹窗页 id=<base>-dialog-<titleSlug>)
551
616
  for (const observation of observations) {
552
- const resolved = resolveObservationPage(config, observation, { pages, workingPages });
617
+ const resolved = resolveObservationPage(config, observation, { pages, workingPages, systemUrls });
553
618
  const baseWorking = ensureWorking(resolved.id);
554
619
  const hasDialog = Boolean(observation.dialog && (observation.dialog.title || observation.dialog.text));
555
620
  let dialogId = null;
@@ -565,14 +630,22 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
565
630
  ...(resolved.urlName ? { urlName: resolved.urlName } : { url: observation.url || undefined }),
566
631
  });
567
632
  }
568
- dialogId = dialogPageId(resolved.id, observation.dialog);
633
+ const dialogTitle = dialogPageTitle(observation.dialog?.title) || cleanLine(observation.dialog?.title, 100);
634
+ dialogId = resolveDialogPageId({
635
+ pages,
636
+ workingPages,
637
+ generatedId: dialogPageId(resolved.id, observation.dialog),
638
+ title: dialogTitle,
639
+ resolvedId: resolved.id,
640
+ observation,
641
+ });
569
642
  const dialogWorking = ensureWorking(dialogId);
570
643
  applyPagePatch(
571
644
  dialogWorking,
572
645
  dialogPagePatch(observation, {
573
646
  id: dialogId,
574
647
  baseTitle: baseWorking.page.title || resolved.id,
575
- runDir: relRun,
648
+ baseId: resolved.id,
576
649
  }),
577
650
  );
578
651
  } else {
@@ -582,13 +655,34 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
582
655
  id: resolved.id,
583
656
  urlName: resolved.urlName,
584
657
  existing: baseWorking.existing,
585
- runDir: relRun,
586
658
  }),
587
659
  );
588
660
  }
589
661
  pageRefs.push({ baseId: resolved.id, dialogId, hasDialog });
590
662
  }
591
663
 
664
+ // 运行观察属于执行证据:按页面聚合成页面观察事件,写入 experiences.jsonl,
665
+ // 正典页面只保留可复用的动作/字段/表头,不再携带 runDir/stepId/实例 URL。
666
+ const evidenceByPage = new Map();
667
+ observations.forEach((observation, index) => {
668
+ const ref = pageRefs[index];
669
+ if (!ref) return;
670
+ const pageId = ref.hasDialog && ref.dialogId ? ref.dialogId : ref.baseId;
671
+ let event = evidenceByPage.get(pageId);
672
+ if (!event) {
673
+ event = {
674
+ id: `page-observation:${pageId}:${relRun}`,
675
+ kind: 'page-observation',
676
+ pageId,
677
+ sources: [],
678
+ observations: [],
679
+ };
680
+ evidenceByPage.set(pageId, event);
681
+ }
682
+ event.sources.push(sourceOf(observation, relRun));
683
+ event.observations.push(observationRefOf(observation, relRun));
684
+ });
685
+
592
686
  // 2) 成功步骤 → 页面动作
593
687
  const steps = Array.isArray(run.steps) ? run.steps : [];
594
688
  const observationIndexByStep = new Map();
@@ -662,6 +756,17 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
662
756
  saveKnowledge(config, knowledge);
663
757
  }
664
758
 
759
+ const evidenceEvents = [...evidenceByPage.values()].map((event) => {
760
+ const page = pages.find((item) => item.id === event.pageId);
761
+ return {
762
+ ...event,
763
+ title: page?.title || '',
764
+ sources: unionBy(event.sources, [], sourceKey).slice(-LEARN_RUN_LIMITS.sources),
765
+ observations: unionBy(event.observations, [], observationKey).slice(-LEARN_RUN_LIMITS.observations),
766
+ };
767
+ });
768
+ const experiencesAdded = evidenceEvents.length ? appendExperiences(config, evidenceEvents) : 0;
769
+
665
770
  // 本次 run 观察到的全部页面(不只本轮有变化的),供批次中心 Episode 稳定复用。
666
771
  const observedPageItems = [];
667
772
  const observedPageRecords = [];
@@ -671,7 +776,7 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
671
776
  observedPageRecords.push(page);
672
777
  }
673
778
 
674
- const summary = { observations: observations.length, pagesAdded, pagesMerged, actionsAdded, actionsConsidered };
779
+ const summary = { observations: observations.length, pagesAdded, pagesMerged, actionsAdded, actionsConsidered, experiencesAdded };
675
780
  const learning = appendLearning(config, {
676
781
  kind: 'run-pages',
677
782
  dedupeKey: 'run-pages|' + relRun,
@@ -689,6 +794,7 @@ export function learnRunObservations(config, { runDir: runDirRef, logger } = {})
689
794
  pagesAdded,
690
795
  pagesMerged,
691
796
  actionsAdded,
797
+ experiencesAdded,
692
798
  learnedPages,
693
799
  learnedPageItems,
694
800
  learnedPageRecords,
@@ -0,0 +1,34 @@
1
+ // 一次运行后的统一沉淀:页面/动作观察 + 等待/失败/耗时学习。
2
+ // 顺序固定为观察在前、计时在后,后者能用到前者刚合并的页面记录。
3
+ import { learnFromRun } from './knowledge.mjs';
4
+ import { learnRunObservations } from './learn-run.mjs';
5
+
6
+ /**
7
+ * 沉淀一次运行的全部可复用证据。
8
+ * 单个阶段失败只记录错误,不阻塞另一阶段,也不改变运行结果。
9
+ */
10
+ export function learnRun(config, { runDir, logger } = {}) {
11
+ const errors = [];
12
+ let observations = null;
13
+ let timing = null;
14
+
15
+ try {
16
+ observations = learnRunObservations(config, { runDir, logger });
17
+ } catch (error) {
18
+ errors.push({ stage: 'observations', message: String(error?.message || error) });
19
+ }
20
+
21
+ try {
22
+ timing = learnFromRun(config, { runDir, logger });
23
+ } catch (error) {
24
+ errors.push({ stage: 'timing', message: String(error?.message || error) });
25
+ }
26
+
27
+ return {
28
+ ok: errors.length === 0,
29
+ runDir: String(runDir || ''),
30
+ observations,
31
+ timing,
32
+ errors,
33
+ };
34
+ }
@@ -18,6 +18,7 @@ export const OBSERVE_LIMITS = {
18
18
  tableHeaders: 40,
19
19
  buttons: 60,
20
20
  inputs: 40,
21
+ dialogFields: 40,
21
22
  dialogText: 1200,
22
23
  text: 1500,
23
24
  path: 300,
@@ -73,7 +74,18 @@ function normalizeDialog(dialog) {
73
74
  const title = truncate(String(dialog.title || '').replace(/\s+/g, ' ').trim(), 100).replace(/…$/, '');
74
75
  const text = truncate(String(dialog.text || ''), OBSERVE_LIMITS.dialogText);
75
76
  if (!title && !text) return null;
76
- return { title, text };
77
+ const out = { title, text };
78
+ const headings = uniqueStrings(dialog.headings, { max: OBSERVE_LIMITS.headings, maxLength: 80 });
79
+ const tableHeaders = uniqueStrings(dialog.tableHeaders, { max: OBSERVE_LIMITS.tableHeaders, maxLength: 60 });
80
+ const buttons = uniqueStrings(dialog.buttons, { max: OBSERVE_LIMITS.buttons, maxLength: 60 });
81
+ const fields = uniqueStrings(dialog.fields, { max: OBSERVE_LIMITS.dialogFields, maxLength: 40 });
82
+ if (headings.length) out.headings = headings;
83
+ if (tableHeaders.length) out.tableHeaders = tableHeaders;
84
+ if (buttons.length) out.buttons = buttons;
85
+ if (fields.length) out.fields = fields;
86
+ const inputs = normalizeInputs(dialog.inputs);
87
+ if (inputs.length) out.inputs = inputs;
88
+ return out;
77
89
  }
78
90
 
79
91
  /**
@@ -85,6 +97,7 @@ export function pageObservationScript(limits = {}) {
85
97
  const maxTableHeaders = Number(limits.tableHeaders) || 40;
86
98
  const maxButtons = Number(limits.buttons) || 60;
87
99
  const maxInputs = Number(limits.inputs) || 40;
100
+ const maxDialogFields = Number(limits.dialogFields) || 40;
88
101
  const maxDialogText = Number(limits.dialogText) || 1200;
89
102
  const maxText = Number(limits.text) || 1500;
90
103
  const maxPath = Number(limits.path) || 300;
@@ -133,44 +146,99 @@ export function pageObservationScript(limits = {}) {
133
146
  .filter((text) => text.length > 0 && text.length <= 60 && !/^[\d\s.,%+\-/]+$/.test(text)),
134
147
  ).slice(0, maxButtons);
135
148
 
136
- const inputs = [];
137
- const inputSeen = new Set();
138
- for (const element of document.querySelectorAll('input, textarea')) {
139
- if (!visible(element)) continue;
140
- const type = String(element.getAttribute('type') || element.tagName).toLowerCase();
141
- if (['hidden', 'checkbox', 'radio', 'submit', 'button', 'file', 'reset'].includes(type)) continue;
142
- const record = {
143
- placeholder: element.getAttribute('placeholder') || '',
144
- name: element.getAttribute('name') || '',
145
- type,
146
- ariaLabel: element.getAttribute('aria-label') || '',
147
- label: oneLine(element.labels && element.labels[0] ? element.labels[0].innerText : '', 80),
148
- };
149
- const key = JSON.stringify(record);
150
- if (inputSeen.has(key)) continue;
151
- inputSeen.add(key);
152
- inputs.push(record);
153
- if (inputs.length >= maxInputs) break;
154
- }
149
+ const collectInputs = (scope) => {
150
+ const out = [];
151
+ const seen = new Set();
152
+ for (const element of scope.querySelectorAll('input, textarea')) {
153
+ if (!visible(element)) continue;
154
+ const type = String(element.getAttribute('type') || element.tagName).toLowerCase();
155
+ if (['hidden', 'checkbox', 'radio', 'submit', 'button', 'file', 'reset'].includes(type)) continue;
156
+ const record = {
157
+ placeholder: element.getAttribute('placeholder') || '',
158
+ name: element.getAttribute('name') || '',
159
+ type,
160
+ ariaLabel: element.getAttribute('aria-label') || '',
161
+ label: oneLine(element.labels && element.labels[0] ? element.labels[0].innerText : '', 80),
162
+ };
163
+ const key = JSON.stringify(record);
164
+ if (seen.has(key)) continue;
165
+ seen.add(key);
166
+ out.push(record);
167
+ if (out.length >= maxInputs) break;
168
+ }
169
+ return out;
170
+ };
171
+ const inputs = collectInputs(document);
155
172
 
156
- // 弹窗:低代码系统常见 .ant-modal/.el-dialog/role=dialog/aria-modal/dialog[open]
173
+ // 弹窗:低代码系统常见 .ant-modal/.el-dialog/role=dialog/aria-modal/dialog[open];
174
+ // 低代码中置弹窗用 .ui-dialog-wrap-middle(带 hasMask),右侧详情抽屉是页面内容,不算弹窗。
157
175
  let dialog = null;
158
- const dialogRoots = [
176
+ const visibleDialogRoots = [
159
177
  ...document.querySelectorAll(
160
- '.ant-modal-content, .ant-modal, .el-dialog, .modal, [role="dialog"], [aria-modal="true"], dialog[open]',
178
+ '.ant-modal-content, .ant-modal, .el-dialog, .modal, .ui-dialog-wrap-middle, .ui-dialog-wrap-hasMask, [role="dialog"], [aria-modal="true"], dialog[open]',
161
179
  ),
162
180
  ].filter(visible);
181
+ // 嵌套外壳只保留最外层,避免读到弹窗局部内容。
182
+ const dialogRoots = visibleDialogRoots.filter(
183
+ (element) => !visibleDialogRoots.some((other) => other !== element && other.contains(element)),
184
+ );
163
185
  if (dialogRoots.length) {
164
186
  const root = dialogRoots[dialogRoots.length - 1];
165
- const titleElement = root.querySelector(
166
- '.ant-modal-title, .ant-modal-header, .el-dialog__title, [class*="title"], h1, h2, h3, h4',
167
- );
187
+ // 标题优先语义化标题/正文标头,[class*="title"] 只作兜底,避免读到区块标题。
188
+ const titleElement =
189
+ root.querySelector(
190
+ '.ant-modal-title, .el-dialog__title, .ui-dialog-title, .ui-dialog-layout-header, [class*="dialog-header"], h1, h2, h3, h4, [role="heading"]',
191
+ ) || root.querySelector('[class*="title"]');
168
192
  const title = oneLine(
169
193
  (titleElement && (titleElement.innerText || titleElement.textContent)) || root.getAttribute('aria-label') || '',
170
194
  100,
171
195
  );
172
196
  const text = block(root.innerText || root.textContent || '', maxDialogText);
173
- if (title || text) dialog = { title, text };
197
+ const dialogHeadings = unique(
198
+ [
199
+ ...root.querySelectorAll(
200
+ 'h1, h2, h3, h4, [role="heading"], [class*="ebcom-title"], [class*="section-title"], [class*="block-title"], [class*="group-title"], [class*="nlist-header-title-block"], [class*="steps-item-content-title"]',
201
+ ),
202
+ ]
203
+ .filter(visible)
204
+ .map((element) => oneLine(element.innerText || element.textContent, 80))
205
+ .filter((item) => item.length >= 2),
206
+ ).slice(0, maxHeadings);
207
+ const dialogTableHeaders = unique(
208
+ [...root.querySelectorAll('th, [role="columnheader"]')]
209
+ .filter(visible)
210
+ .map((element) => oneLine(element.innerText || element.textContent, 60))
211
+ .filter(Boolean),
212
+ ).slice(0, maxTableHeaders);
213
+ const dialogButtons = unique(
214
+ [...root.querySelectorAll('button, a, [role="button"], [role="tab"], [role="menuitem"]')]
215
+ .filter(visible)
216
+ .map((element) => oneLine(element.innerText || element.textContent, 60))
217
+ .filter((item) => item.length > 0 && item.length <= 60 && !/^[\d\s.,%+\-/]+$/.test(item)),
218
+ ).slice(0, maxButtons);
219
+ // label+value 详情字段名:不在表格里,排除列值与单号日期。
220
+ const dialogFields = unique(
221
+ [
222
+ ...root.querySelectorAll(
223
+ '[class*="list-item-name"], [class*="form-label"], [class*="field-label"], [class*="item-label"], label',
224
+ ),
225
+ ]
226
+ .filter(visible)
227
+ .filter((element) => !element.closest('table'))
228
+ .map((element) => oneLine(element.innerText || element.textContent, 40))
229
+ .filter((item) => item.length >= 1 && item.length <= 20 && !/\d{6,}/.test(item)),
230
+ ).slice(0, maxDialogFields);
231
+ if (title || text) {
232
+ dialog = {
233
+ title,
234
+ text,
235
+ headings: dialogHeadings,
236
+ tableHeaders: dialogTableHeaders,
237
+ buttons: dialogButtons,
238
+ inputs: collectInputs(root),
239
+ fields: dialogFields,
240
+ };
241
+ }
174
242
  }
175
243
 
176
244
  return {