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
@@ -12,6 +12,7 @@ import { agentSessionBrowserNames, stopAgentBrowserSessions } from './agent-brow
12
12
  import { pickStoredValue, validateFlow } from './flow.mjs';
13
13
  import { appendPageObservation, collectPageObservation, observationFingerprint } from './run-observe.mjs';
14
14
  import { addResult, collectRunEvidence, normalizeEvidenceFile, normalizeStatus, RESULT_STATUSES } from './results.mjs';
15
+ import { learnRun } from './run-learn.mjs';
15
16
  import { findCase } from './xlsx.mjs';
16
17
  import { loadProjectCases } from './cases-import.mjs';
17
18
  import { accountConfigFor, accountsForExecution, inferRolesFromText, selectAccountForRole, selectAccountForStep } from '../studio/accounts.mjs';
@@ -29,6 +30,8 @@ import {
29
30
  truncate,
30
31
  writeFileAtomic,
31
32
  } from './util.mjs';
33
+ import { appendLearning } from './knowledge.mjs';
34
+ import { stableHash } from './knowledge-central.mjs';
32
35
 
33
36
  export const AGENT_SESSION_STATUSES = ['running', 'finished', 'failed'];
34
37
  export const ASSESSABLE_ACTIONS = new Set(['goto', 'click', 'fill', 'type', 'press', 'select', 'upload', 'reload', 'back', 'hover', 'login', 'waitFor', 'wait']);
@@ -690,6 +693,32 @@ export async function reviewAgentSession({
690
693
  writeJson(state.runJsonPath, runRecord);
691
694
  state.reviewedAt = review.at;
692
695
  saveAgentSession(config, state);
696
+ // 独立 CLI 会话没有 Studio 批次蒸馏时,复盘也要进入下一次执行的知识召回。
697
+ // 去重键与 Studio 蒸馏保持一致,后续批次蒸馏不会重复记账。
698
+ const compact = {
699
+ summary: review.summary.slice(0, 1200),
700
+ lessons: review.lessons.slice(0, 20),
701
+ issues: review.issues.slice(0, 20),
702
+ };
703
+ try {
704
+ appendLearning(config, {
705
+ kind: 'agent-review',
706
+ caseId: state.caseId,
707
+ runDir: state.runDir,
708
+ dedupeKey: 'agent-review|' + state.runDir + '|' + stableHash(compact),
709
+ detail: {
710
+ caseId: state.caseId,
711
+ status: runRecord.verdict || runRecord.status || null,
712
+ summary: compact.summary,
713
+ lessons: compact.lessons,
714
+ issues: compact.issues,
715
+ stepCount: review.stepCount,
716
+ },
717
+ confidence: 0.8,
718
+ });
719
+ } catch {
720
+ /* 知识库写入失败不阻塞复盘落盘 */
721
+ }
693
722
  return { ok: true, review };
694
723
  }
695
724
 
@@ -803,6 +832,23 @@ function usedVars(steps) {
803
832
  * 把一次通过的 Agent 执行轨迹沉淀成 flow。
804
833
  * 轨迹步骤本来就用 flow DSL 表达,所以这里是「落盘 + 去值化」,不是二次生成。
805
834
  */
835
+ function readFlowFile(file) {
836
+ try {
837
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
838
+ } catch {
839
+ return null;
840
+ }
841
+ }
842
+
843
+ /** 覆盖前留档;flow 目录下的 .backups 不参与 flow 索引。 */
844
+ function backupFlowFile(file) {
845
+ const dir = path.join(path.dirname(file), '.backups');
846
+ ensureDir(dir);
847
+ const dest = path.join(dir, `${path.basename(file, '.json')}-${timeStamp()}.json`);
848
+ fs.copyFileSync(file, dest);
849
+ return dest;
850
+ }
851
+
806
852
  export function distillAgentFlow({ config, state, runRecord, caseItem, force = false } = {}) {
807
853
  const observeOnly = new Set(['text', 'html', 'table', 'links', 'inputs']);
808
854
  const vars = { ...(runRecord?.vars || {}), ...(state?.vars || {}) };
@@ -835,8 +881,14 @@ export function distillAgentFlow({ config, state, runRecord, caseItem, force = f
835
881
  const caseId = String(state.caseId);
836
882
  const name = `agent-${slug(caseId)}`;
837
883
  const file = path.join(config.paths.flowsDir, `${name}.json`);
838
- if (fs.existsSync(file) && force !== true) {
839
- return { skipped: true, reason: `flow 已存在:${file}`, file };
884
+ let backup = null;
885
+ if (fs.existsSync(file)) {
886
+ const existing = readFlowFile(file);
887
+ const replaceable = force === true || existing?.generated?.by === 'uitest-agent-execute';
888
+ if (!replaceable) {
889
+ return { skipped: true, reason: `flow 已存在且不是 Agent 沉淀产物:${file}`, file };
890
+ }
891
+ backup = backupFlowFile(file);
840
892
  }
841
893
  const flow = {
842
894
  name,
@@ -854,6 +906,7 @@ export function distillAgentFlow({ config, state, runRecord, caseItem, force = f
854
906
  verdict: '通过',
855
907
  needsReview: false,
856
908
  confidence: 0.9,
909
+ ...(backup ? { replacedBackup: path.relative(config.paths.flowsDir, backup) } : {}),
857
910
  explanation: '由自然语言用例执行轨迹直接沉淀;步骤均已在该次运行中真实通过。',
858
911
  },
859
912
  };
@@ -864,7 +917,7 @@ export function distillAgentFlow({ config, state, runRecord, caseItem, force = f
864
917
  }
865
918
  ensureDir(config.paths.flowsDir);
866
919
  writeFileAtomic(file, `${JSON.stringify(flow, null, 2)}\n`);
867
- return { skipped: false, file, name, steps: steps.length, requires };
920
+ return { skipped: false, file, name, steps: steps.length, requires, backup };
868
921
  }
869
922
 
870
923
  /**
@@ -879,6 +932,7 @@ export async function finishAgentSession({
879
932
  evidence = [],
880
933
  distill = true,
881
934
  force = false,
935
+ learn = true,
882
936
  driver = abDriver,
883
937
  } = {}) {
884
938
  const { state } = loadAgentSession(config, sessionId);
@@ -922,6 +976,26 @@ export async function finishAgentSession({
922
976
  };
923
977
  writeJson(state.runJsonPath, runRecord);
924
978
 
979
+ // 独立 CLI 会话也要把本次执行沉淀进知识库;Studio 批次后续蒸馏按 dedupeKey 幂等。
980
+ let learned = null;
981
+ if (learn) {
982
+ try {
983
+ learned = learnRun(config, { runDir: state.runDir });
984
+ } catch (error) {
985
+ learned = { ok: false, errors: [{ stage: 'learn', message: String(error?.message || error) }] };
986
+ }
987
+ runRecord.learn = {
988
+ at: nowIso(),
989
+ pagesAdded: learned.observations?.pagesAdded || 0,
990
+ actionsAdded: learned.observations?.actionsAdded || 0,
991
+ waitsUpdated: learned.timing?.updatedPages?.length || 0,
992
+ suggestions: learned.timing?.suggestions?.length || 0,
993
+ learnings: learned.timing?.learnings?.length || 0,
994
+ errors: learned.errors,
995
+ };
996
+ writeJson(state.runJsonPath, runRecord);
997
+ }
998
+
925
999
  const runEvidence = collectRunEvidence(config, state.runDir, { maxKey: 5, maxError: 5 });
926
1000
  const evidenceList = [...new Set(
927
1001
  [...runEvidence.legacy, ...(Array.isArray(evidence) ? evidence : [])]
@@ -970,6 +1044,7 @@ export async function finishAgentSession({
970
1044
  evidence: evidenceList,
971
1045
  result: entry,
972
1046
  flow,
1047
+ learn: learned,
973
1048
  };
974
1049
  }
975
1050
 
@@ -1055,5 +1130,8 @@ export function listAgentSessions(config) {
1055
1130
  stepCount: state.stepCount || 0,
1056
1131
  createdAt: state.createdAt,
1057
1132
  updatedAt: state.updatedAt,
1133
+ finishedAt: state.finishedAt || null,
1134
+ flow: state.flow || null,
1135
+ note: state.note || '',
1058
1136
  }));
1059
1137
  }
@@ -0,0 +1,212 @@
1
+ // Agent 交接清单:批次把没有 flow 的用例写成结构化作业,宿主执行完后按会话对账。
2
+ // 清单是协议,不是执行器;这里不启动浏览器,也不写结果库。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { listAgentSessions } from './agent-session.mjs';
7
+ import { loadProjectCases } from './cases-import.mjs';
8
+ import { validateFlow } from './flow.mjs';
9
+ import { findCase } from './xlsx.mjs';
10
+ import { ensureDir, nowIso, slug, writeFileAtomic } from './util.mjs';
11
+ import { readCaseRuns } from '../studio/store.mjs';
12
+
13
+ export const AGENT_TASK_STATES = ['pending', 'done', 'partial', 'failed', 'blocked'];
14
+
15
+ const VERDICT_STATE = { 通过: 'done', 部分通过: 'partial', 失败: 'failed', 阻塞: 'blocked' };
16
+ // 工作室批次用例状态用的是英文,流水线批次历史记录里是中文,两套都要认。
17
+ const RUN_STATE = { passed: 'done', 通过: 'done', partial: 'partial', 部分通过: 'partial', failed: 'failed', 失败: 'failed', blocked: 'blocked', stopped: 'blocked' };
18
+
19
+ export function agentTasksFile(config, batchId) {
20
+ return path.join(config.paths.outputDir, 'batches', batchId, 'agent-tasks.json');
21
+ }
22
+
23
+ /** 从批次计划生成清单;只收 agent-ready。任务 id 只由批次和用例决定,可重复生成。 */
24
+ export function planAgentTasks({ config, plan, cases = [], batchId, createdAt = nowIso() }) {
25
+ const list = cases.length ? cases : loadProjectCases(config).cases;
26
+ const tasks = [];
27
+ for (const item of plan?.items || []) {
28
+ if (item.state !== 'agent-ready') continue;
29
+ const caseItem = findCase(list, item.caseId)?.case || {};
30
+ tasks.push({
31
+ id: `agent-task-${batchId}-${slug(item.caseId)}`,
32
+ batchId,
33
+ caseId: item.caseId,
34
+ title: item.title || caseItem.functionPoint || '',
35
+ precondition: item.precondition || caseItem.precondition || '',
36
+ steps: caseItem.steps || '',
37
+ expected: caseItem.expected || '',
38
+ advisoryNeeds: item.advisoryNeeds || [],
39
+ draftFlow: item.draftFlow
40
+ ? { name: item.draftFlow.name, file: item.draftFlow.file, generated: item.draftFlow.generated || null }
41
+ : null,
42
+ knowledge: {
43
+ library: config?.knowledge?.library || null,
44
+ hint: `uitest agent-session knowledge --case ${item.caseId}`,
45
+ },
46
+ acceptance: {
47
+ verdict: '通过',
48
+ distill: true,
49
+ note: item.draftFlow
50
+ ? '草稿 flow 缺可执行入口或断言;以它为参考修正,跑通后 finish 通过沉淀新 flow'
51
+ : '跑通后用 agent-session finish --verdict 通过 沉淀 flow;失败也要 finish 记录结论',
52
+ },
53
+ status: 'pending',
54
+ createdAt,
55
+ result: null,
56
+ });
57
+ }
58
+ return tasks;
59
+ }
60
+
61
+ export function persistAgentTasks(config, payload) {
62
+ const file = agentTasksFile(config, payload.batchId);
63
+ ensureDir(path.dirname(file));
64
+ const next = { ...payload, total: payload.tasks.length, updatedAt: nowIso(), file };
65
+ writeFileAtomic(file, `${JSON.stringify(next, null, 2)}\n`);
66
+ return {
67
+ file,
68
+ batchId: payload.batchId,
69
+ total: next.total,
70
+ pending: next.tasks.filter((task) => task.status === 'pending').length,
71
+ };
72
+ }
73
+
74
+ export function saveAgentTasks(config, batchId, tasks, createdAt = nowIso()) {
75
+ if (!tasks.length) return null;
76
+ return persistAgentTasks(config, {
77
+ version: 1,
78
+ batchId,
79
+ createdAt,
80
+ tasks,
81
+ });
82
+ }
83
+
84
+ export function readAgentTasks(config, batchId) {
85
+ const file = agentTasksFile(config, batchId);
86
+ if (!fs.existsSync(file)) return null;
87
+ const payload = JSON.parse(fs.readFileSync(file, 'utf8'));
88
+ return { ...payload, file };
89
+ }
90
+
91
+ /** 最近一个带清单的批次,供 CLI 省略 --batch。 */
92
+ export function latestAgentTasksBatch(config) {
93
+ const dir = path.join(config.paths.outputDir, 'batches');
94
+ if (!fs.existsSync(dir)) return null;
95
+ const names = fs
96
+ .readdirSync(dir, { withFileTypes: true })
97
+ .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, 'agent-tasks.json')))
98
+ .map((entry) => entry.name)
99
+ .sort();
100
+ return names.at(-1) || null;
101
+ }
102
+
103
+ export function summarizeAgentTasks(payload) {
104
+ const counts = {};
105
+ for (const task of payload?.tasks || []) counts[task.status] = (counts[task.status] || 0) + 1;
106
+ return {
107
+ batchId: payload?.batchId || '',
108
+ file: payload?.file || '',
109
+ total: (payload?.tasks || []).length,
110
+ pending: counts.pending || 0,
111
+ counts,
112
+ };
113
+ }
114
+
115
+ /** 供宿主快照与入口读取最近一份清单;没有清单时返回 null。 */
116
+ export function latestAgentTasksSummary(config) {
117
+ const batchId = latestAgentTasksBatch(config);
118
+ if (!batchId) return null;
119
+ const payload = readAgentTasks(config, batchId);
120
+ return payload ? summarizeAgentTasks(payload) : null;
121
+ }
122
+
123
+ /** 通过结论必须落下一个能回放的 flow;文件缺失或结构不合法都要在对账时暴露。 */
124
+ function inspectFlowArtifact(config, ref) {
125
+ if (!ref) return { flowValid: false, flowError: '结论为通过,但没有沉淀 flow 文件' };
126
+ const file = path.isAbsolute(ref) ? ref : path.join(config.paths.flowsDir, ref);
127
+ if (!fs.existsSync(file)) return { flowValid: false, flowError: `flow 文件不存在:${file}` };
128
+ try {
129
+ validateFlow(JSON.parse(fs.readFileSync(file, 'utf8')), file);
130
+ return { flowValid: true, flowError: null };
131
+ } catch (error) {
132
+ return { flowValid: false, flowError: error.message };
133
+ }
134
+ }
135
+
136
+ /** 宿主认领清单时登记批次,对账才知道哪些用例记录属于本轮认领。 */
137
+ export function recordAgentTasksAdoption(config, batchId, adoptedBatchId, at = nowIso()) {
138
+ const payload = readAgentTasks(config, batchId);
139
+ if (!payload) return null;
140
+ const adoptions = (payload.adoptions || []).filter((item) => item.batchId !== adoptedBatchId);
141
+ adoptions.push({ batchId: adoptedBatchId, at });
142
+ return persistAgentTasks(config, { ...payload, adoptions });
143
+ }
144
+
145
+ /**
146
+ * 对账:按 caseId 找任务创建后开始的已结束会话,写回结论,并校验通过的 flow 能否回放。
147
+ * 会话没有结论时回落到认领批次自己的用例记录,宿主执行失败也要落结论而不是永远 pending。
148
+ */
149
+ export function reconcileAgentTasks(config, payload) {
150
+ const sessions = listAgentSessions(config)
151
+ .filter((session) => session.status === 'finished' && session.verdict && session.finishedAt)
152
+ .sort((a, b) => String(b.finishedAt).localeCompare(String(a.finishedAt)));
153
+ const runs = reconcileAdoptedRuns(config, payload);
154
+ const tasks = (payload.tasks || []).map((task) => {
155
+ const match = sessions.find(
156
+ (session) => session.caseId === task.caseId && String(session.createdAt || '') >= String(task.createdAt || ''),
157
+ );
158
+ if (match) {
159
+ const artifact = match.verdict === '通过' ? inspectFlowArtifact(config, match.flow) : { flowValid: null, flowError: null };
160
+ return {
161
+ ...task,
162
+ status: VERDICT_STATE[match.verdict] || 'done',
163
+ reconciledAt: nowIso(),
164
+ result: {
165
+ sessionId: match.sessionId,
166
+ verdict: match.verdict,
167
+ runDir: match.runDir || null,
168
+ flow: match.flow || null,
169
+ ...artifact,
170
+ note: match.note || '',
171
+ finishedAt: match.finishedAt,
172
+ },
173
+ };
174
+ }
175
+ const run = runs.find((item) => item.caseId === task.caseId);
176
+ const state = run ? RUN_STATE[run.status] : null;
177
+ if (!state) return task;
178
+ const artifact = state === 'done' ? inspectFlowArtifact(config, run.flow) : { flowValid: null, flowError: null };
179
+ return {
180
+ ...task,
181
+ status: state,
182
+ reconciledAt: nowIso(),
183
+ result: {
184
+ source: 'batch',
185
+ batchId: run.batchId || null,
186
+ verdict: run.status,
187
+ runDir: run.runDir || null,
188
+ flow: run.flow || null,
189
+ ...artifact,
190
+ note: run.note || '',
191
+ finishedAt: run.endedAt || null,
192
+ },
193
+ };
194
+ });
195
+ return { ...payload, tasks };
196
+ }
197
+
198
+ function reconcileAdoptedRuns(config, payload) {
199
+ const out = [];
200
+ for (const adoption of payload.adoptions || []) {
201
+ let runs = [];
202
+ try {
203
+ runs = readCaseRuns(config, adoption.batchId);
204
+ } catch {
205
+ runs = [];
206
+ }
207
+ for (const run of runs) {
208
+ if (RUN_STATE[run.status]) out.push({ ...run, adoptedAt: adoption.at });
209
+ }
210
+ }
211
+ return out.sort((a, b) => String(b.endedAt || '').localeCompare(String(a.endedAt || '')));
212
+ }