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.
- package/README.md +76 -11
- package/bin/uitest.mjs +189 -11
- package/client.js +222 -25
- package/host/agent-bridge.mjs +9 -2
- package/host/agent-test.mjs +1 -1
- package/host/context-budget.mjs +1 -1
- package/index.js +14 -2
- package/lib/agent-session.mjs +81 -3
- package/lib/agent-tasks.mjs +212 -0
- package/lib/batch.mjs +204 -13
- package/lib/browser-ab.mjs +21 -6
- package/lib/browser.mjs +5 -5
- package/lib/config.mjs +1 -0
- package/lib/convert.mjs +178 -40
- package/lib/doc-structure.mjs +316 -0
- package/lib/flow.mjs +49 -14
- package/lib/knowledge-central-episodes.mjs +120 -0
- package/lib/knowledge-central-import.mjs +16 -1
- package/lib/knowledge-central.mjs +176 -25
- package/lib/knowledge-clean.mjs +749 -0
- package/lib/knowledge-consolidate.mjs +1271 -0
- package/lib/knowledge-coverage.mjs +150 -0
- package/lib/knowledge-docs.mjs +3 -3
- package/lib/knowledge-effect.mjs +148 -0
- package/lib/knowledge-facts.mjs +1008 -0
- package/lib/knowledge-maintain.mjs +185 -0
- package/lib/knowledge-permission.mjs +447 -0
- package/lib/knowledge-query.mjs +304 -26
- package/lib/knowledge-store.mjs +169 -14
- package/lib/knowledge-summarize.mjs +332 -0
- package/lib/knowledge.mjs +944 -47
- package/lib/learn-run.mjs +157 -51
- package/lib/run-learn.mjs +34 -0
- package/lib/run-observe.mjs +95 -27
- package/lib/run-stats.mjs +71 -0
- package/package.json +12 -2
- package/scripts/knowledge-central-purge.mjs +248 -0
- package/scripts/knowledge-central-sync.mjs +102 -20
- package/scripts/knowledge-consolidate.mjs +158 -0
- package/scripts/knowledge-coverage.mjs +94 -0
- package/scripts/knowledge-effect.mjs +82 -0
- package/scripts/knowledge-permission-probe.mjs +196 -0
- package/scripts/knowledge-permission-report.mjs +140 -0
- package/scripts/knowledge-report.mjs +492 -0
- package/scripts/knowledge-summarize.mjs +200 -0
- package/skills/uitest/SKILL.md +4 -2
- package/skills/uitest/references/convert-knowledge.md +66 -13
- package/studio/host.mjs +143 -6
- package/studio/knowledge.mjs +279 -42
- package/studio/snapshot.mjs +6 -1
package/studio/knowledge.mjs
CHANGED
|
@@ -1,19 +1,35 @@
|
|
|
1
1
|
// 批次知识沉淀:运行期间只采集到各自的 run 目录;批次结束后串行合并进知识库,避免并发写。
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
|
|
4
|
-
import { appendLearning, learnFromRun, loadKnowledge,
|
|
4
|
+
import { appendExperiences, appendLearning, learnFromRun, loadKnowledge, readExperiences, readLearnings } from '../lib/knowledge.mjs';
|
|
5
5
|
import { learnRunObservations } from '../lib/learn-run.mjs';
|
|
6
6
|
import { centralConfig, centralIngest, stableHash } from '../lib/knowledge-central.mjs';
|
|
7
|
-
import { PAGE_EPISODE_SOURCE, PROCESS_EPISODE_SOURCE, pageEpisodeBody, processEpisodeBody } from '../lib/knowledge-central-episodes.mjs';
|
|
7
|
+
import { EXPERIENCE_EPISODE_SOURCE, PAGE_EPISODE_SOURCE, PROCESS_EPISODE_SOURCE, experienceEpisodeBody, pageEpisodeBody, processEpisodeBody } from '../lib/knowledge-central-episodes.mjs';
|
|
8
8
|
import { categorySourceTag } from '../lib/knowledge-categories.mjs';
|
|
9
|
+
import { maintainKnowledge, maintenanceOptions } from '../lib/knowledge-maintain.mjs';
|
|
9
10
|
import { nowIso, sleep, slug } from '../lib/util.mjs';
|
|
10
11
|
import { acquireLock, listBatches, patchBatch, patchStage, readBatch, readCaseRun, readCaseRuns, writeBatchText } from './store.mjs';
|
|
11
12
|
import { correctionKey, correctionText, detectSelfCorrections } from './experience.mjs';
|
|
12
13
|
|
|
14
|
+
const distillJobs = new Map();
|
|
15
|
+
|
|
16
|
+
function distillJobKey(config, batchId) {
|
|
17
|
+
return String(config.projectDir || '') + '\0' + String(batchId || '');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function isDistillActive(config, batchId) {
|
|
21
|
+
return distillJobs.has(distillJobKey(config, batchId));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function yieldEventLoop() {
|
|
25
|
+
return new Promise((resolve) => setImmediate(resolve));
|
|
26
|
+
}
|
|
27
|
+
|
|
13
28
|
function pageSummary(page) {
|
|
14
29
|
return {
|
|
15
30
|
id: page.id,
|
|
16
31
|
title: page.title || page.urlName || page.id,
|
|
32
|
+
summary: page.summary || '',
|
|
17
33
|
urlName: page.urlName || '',
|
|
18
34
|
url: page.url || '',
|
|
19
35
|
headings: Array.isArray(page.headings) ? page.headings.slice(0, 8) : [],
|
|
@@ -38,13 +54,17 @@ function processSummary(item) {
|
|
|
38
54
|
id: item.id,
|
|
39
55
|
name: item.name || item.title || item.id,
|
|
40
56
|
caseId: item.caseId || '',
|
|
57
|
+
summary: item.summary || '',
|
|
41
58
|
steps: (item.steps || []).map((step) => (typeof step === 'string' ? step : step.text || step.desc || '')).filter(Boolean).slice(0, 20),
|
|
42
59
|
notes: (item.notes || []).filter(Boolean).slice(-8),
|
|
43
60
|
corrections: (item.corrections || []).slice(-8),
|
|
44
61
|
reviews: (item.reviews || []).slice(-5),
|
|
45
62
|
confidence: item.confidence ?? null,
|
|
46
|
-
updatedAt: item.updatedAt || item.learnedAt || '',
|
|
63
|
+
updatedAt: item.updatedAt || item.learnedAt || item.at || '',
|
|
47
64
|
source: item.source || null,
|
|
65
|
+
evidence: item.evidence === true,
|
|
66
|
+
kind: item.kind || '',
|
|
67
|
+
batchId: item.batchId || '',
|
|
48
68
|
};
|
|
49
69
|
}
|
|
50
70
|
|
|
@@ -62,26 +82,44 @@ export function knowledgeSnapshot(config, { limit = 200 } = {}) {
|
|
|
62
82
|
} catch {
|
|
63
83
|
learnings = [];
|
|
64
84
|
}
|
|
85
|
+
let experiences = [];
|
|
86
|
+
try {
|
|
87
|
+
experiences = readExperiences(config, { limit: Math.min(200, limit) })
|
|
88
|
+
.filter((item) => ['case-process', 'case-experience'].includes(item.kind));
|
|
89
|
+
} catch {
|
|
90
|
+
experiences = [];
|
|
91
|
+
}
|
|
65
92
|
const pages = knowledge?.pages?.pages || [];
|
|
66
93
|
const processes = knowledge?.processes?.processes || [];
|
|
67
|
-
const
|
|
94
|
+
const businessEntries = knowledge?.business?.entries || [];
|
|
95
|
+
const business = businessEntries.flatMap((entry) => {
|
|
96
|
+
const rules = Array.isArray(entry.rules) ? entry.rules : (entry.rules ? [entry.rules] : []);
|
|
97
|
+
if (!rules.length && (entry.text || entry.desc)) rules.push(entry.text || entry.desc);
|
|
98
|
+
return rules.map((rule, index) => ({
|
|
99
|
+
id: (entry.id || entry.title || 'business') + '#' + (index + 1),
|
|
100
|
+
title: entry.title || entry.name || entry.id || '',
|
|
101
|
+
text: typeof rule === 'string' ? rule : rule?.text || rule?.desc || '',
|
|
102
|
+
source: entry.source || '',
|
|
103
|
+
})).filter((rule) => rule.text);
|
|
104
|
+
});
|
|
68
105
|
const corrections = processes.reduce((sum, item) => sum + (Array.isArray(item.corrections) ? item.corrections.length : 0), 0);
|
|
106
|
+
const experienceSummaries = experiences.map((item) => processSummary({ ...item, evidence: true }));
|
|
107
|
+
const processSummaries = processes.map(processSummary);
|
|
69
108
|
return {
|
|
70
109
|
summary: {
|
|
71
110
|
pages: pages.length,
|
|
72
|
-
processes:
|
|
111
|
+
processes: processSummaries.length + experienceSummaries.length,
|
|
112
|
+
canonicalProcesses: processSummaries.length,
|
|
113
|
+
experiences: experienceSummaries.length,
|
|
73
114
|
business: business.length,
|
|
115
|
+
businessEntries: businessEntries.length,
|
|
74
116
|
learnings: learnings.length,
|
|
75
117
|
corrections,
|
|
76
118
|
},
|
|
77
119
|
pages: pages.slice(0, limit).map(pageSummary),
|
|
78
|
-
processes:
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
title: rule.title || rule.name || rule.id,
|
|
82
|
-
text: rule.text || rule.desc || '',
|
|
83
|
-
source: rule.source || '',
|
|
84
|
-
})),
|
|
120
|
+
processes: [...processSummaries, ...experienceSummaries].slice(0, limit),
|
|
121
|
+
experiences: experienceSummaries.slice(0, limit),
|
|
122
|
+
business: business.slice(0, limit),
|
|
85
123
|
learnings: learnings.slice(0, limit).map((item) => ({
|
|
86
124
|
id: item.id,
|
|
87
125
|
kind: item.kind,
|
|
@@ -144,7 +182,8 @@ function staleCaseIds(config, batchId, runs) {
|
|
|
144
182
|
return stale;
|
|
145
183
|
}
|
|
146
184
|
|
|
147
|
-
function buildBatchCentralEpisodes(batchId, runs, learned, { pageRecords = new Map(), processRecords = new Map(), knownPages = new Map(), skipCaseIds = new Set() } = {}) {
|
|
185
|
+
export function buildBatchCentralEpisodes(batchId, runs, learned, { pageRecords = new Map(), processRecords = new Map(), experiences = [], knownPages = new Map(), skipCaseIds = new Set() } = {}) {
|
|
186
|
+
const experienceByCase = new Map((experiences || []).map((experience) => [String(experience.caseId), experience]));
|
|
148
187
|
const episodes = [];
|
|
149
188
|
for (const item of learned) {
|
|
150
189
|
// 手动/阻断用例没有实际执行,不能用空快照覆盖已有的 case 知识。
|
|
@@ -173,6 +212,7 @@ function buildBatchCentralEpisodes(batchId, runs, learned, { pageRecords = new M
|
|
|
173
212
|
episodes.push({
|
|
174
213
|
key: caseKey,
|
|
175
214
|
name: caseKey,
|
|
215
|
+
target: 'evidence',
|
|
176
216
|
replace_prefix: caseKey + ':',
|
|
177
217
|
source_description: 'uitest case run observation · ' + categorySourceTag('operation'),
|
|
178
218
|
body: {
|
|
@@ -209,32 +249,69 @@ function buildBatchCentralEpisodes(batchId, runs, learned, { pageRecords = new M
|
|
|
209
249
|
episodes.push({
|
|
210
250
|
key: 'page:' + page.id,
|
|
211
251
|
name: 'page:' + page.id,
|
|
252
|
+
target: 'knowledge',
|
|
212
253
|
source_description: PAGE_EPISODE_SOURCE,
|
|
213
254
|
body: pageEpisodeBody(page),
|
|
214
255
|
});
|
|
215
256
|
}
|
|
216
257
|
const processRecord = processRecords.get(String(item.caseId));
|
|
217
|
-
|
|
258
|
+
const experience = experienceByCase.get(String(item.caseId));
|
|
259
|
+
if (experience) {
|
|
260
|
+
// 与全量同步使用同一 experience Episode 键与正文,避免重复写入中心库。
|
|
261
|
+
episodes.push({
|
|
262
|
+
key: 'experience:' + experience.id,
|
|
263
|
+
name: 'experience:' + experience.id,
|
|
264
|
+
target: 'evidence',
|
|
265
|
+
source_description: EXPERIENCE_EPISODE_SOURCE,
|
|
266
|
+
body: experienceEpisodeBody(experience),
|
|
267
|
+
});
|
|
268
|
+
} else if (item.process && processRecord) {
|
|
218
269
|
const processId = item.process.processId || item.caseId;
|
|
219
270
|
episodes.push({
|
|
220
271
|
key: 'process:' + processId,
|
|
221
272
|
name: 'process:' + processId,
|
|
273
|
+
target: 'evidence',
|
|
222
274
|
source_description: PROCESS_EPISODE_SOURCE,
|
|
223
275
|
body: processEpisodeBody(processRecord),
|
|
224
276
|
});
|
|
225
277
|
}
|
|
226
278
|
}
|
|
279
|
+
// 页面运行观察是证据:批次沉淀与全量同步使用同一 experience Episode,避免两边互相覆盖。
|
|
280
|
+
const pageIds = new Set([...pageRecords.keys()].map((id) => String(id)));
|
|
281
|
+
const seenEvidence = new Set();
|
|
282
|
+
for (const experience of experiences) {
|
|
283
|
+
if (experience?.kind !== 'page-observation') continue;
|
|
284
|
+
if (!pageIds.has(String(experience.pageId))) continue;
|
|
285
|
+
if (seenEvidence.has(experience.id)) continue;
|
|
286
|
+
seenEvidence.add(experience.id);
|
|
287
|
+
episodes.push({
|
|
288
|
+
key: 'experience:' + experience.id,
|
|
289
|
+
name: 'experience:' + experience.id,
|
|
290
|
+
target: 'evidence',
|
|
291
|
+
source_description: EXPERIENCE_EPISODE_SOURCE,
|
|
292
|
+
body: experienceEpisodeBody(experience),
|
|
293
|
+
});
|
|
294
|
+
}
|
|
227
295
|
return episodes;
|
|
228
296
|
}
|
|
229
297
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
298
|
+
/**
|
|
299
|
+
* 知识组只收页面与正典事实;case-run 与 process 是执行证据,进证据组。
|
|
300
|
+
*/
|
|
301
|
+
export function splitCentralEpisodes(episodes = []) {
|
|
302
|
+
const knowledge = [];
|
|
303
|
+
const evidence = [];
|
|
304
|
+
for (const episode of episodes) {
|
|
305
|
+
if (episode?.target === 'evidence') evidence.push(episode);
|
|
306
|
+
else knowledge.push(episode);
|
|
236
307
|
}
|
|
237
|
-
|
|
308
|
+
return { knowledge, evidence };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function mergeProcessKnowledge(config, runs) {
|
|
312
|
+
// 用例级流程是执行证据,不写入正典 processes.json:只在内存里按 case 合并本轮记录,
|
|
313
|
+
// 结束后追加到 experiences.jsonl(按 batch+case+内容哈希幂等)。
|
|
314
|
+
const list = [];
|
|
238
315
|
let added = 0;
|
|
239
316
|
let merged = 0;
|
|
240
317
|
let correctionsAdded = 0;
|
|
@@ -260,7 +337,8 @@ function mergeProcessKnowledge(config, runs) {
|
|
|
260
337
|
caseId: run.caseId,
|
|
261
338
|
runDir: run.runDir,
|
|
262
339
|
status: run.status,
|
|
263
|
-
|
|
340
|
+
// 用 run 的时间而不是沉淀时间,重复提交同一批次时 Episode 正文保持稳定。
|
|
341
|
+
at: run.endedAt || run.startedAt || nowIso(),
|
|
264
342
|
};
|
|
265
343
|
const runKey = run.runDir || (String(run.caseId) + '@' + String(run.batchId || ''));
|
|
266
344
|
const notes = [];
|
|
@@ -398,9 +476,37 @@ function mergeProcessKnowledge(config, runs) {
|
|
|
398
476
|
confidence: 0.8,
|
|
399
477
|
});
|
|
400
478
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
479
|
+
const experiences = [];
|
|
480
|
+
for (const record of processRecords.values()) {
|
|
481
|
+
const batchId = record.sources?.[0]?.batchId || record.source?.batchId || '';
|
|
482
|
+
experiences.push({
|
|
483
|
+
id: 'case-run:' + [batchId, record.caseId, stableHash({
|
|
484
|
+
steps: record.steps,
|
|
485
|
+
corrections: record.corrections,
|
|
486
|
+
reviews: record.reviews,
|
|
487
|
+
notes: record.notes,
|
|
488
|
+
})].join(':'),
|
|
489
|
+
kind: 'case-process',
|
|
490
|
+
at: record.updatedAt || nowIso(),
|
|
491
|
+
batchId,
|
|
492
|
+
caseId: record.caseId,
|
|
493
|
+
name: record.name,
|
|
494
|
+
status: record.source?.status || '',
|
|
495
|
+
steps: record.steps,
|
|
496
|
+
corrections: record.corrections,
|
|
497
|
+
reviews: record.reviews,
|
|
498
|
+
notes: record.notes,
|
|
499
|
+
sources: record.sources,
|
|
500
|
+
confidence: record.confidence,
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
let experiencesAdded = 0;
|
|
504
|
+
if (experiences.length) {
|
|
505
|
+
try {
|
|
506
|
+
experiencesAdded = appendExperiences(config, experiences);
|
|
507
|
+
} catch {
|
|
508
|
+
/* 证据写入失败不应让批次沉淀整体失败 */
|
|
509
|
+
}
|
|
404
510
|
}
|
|
405
511
|
for (const event of learningEvents) {
|
|
406
512
|
try {
|
|
@@ -409,7 +515,7 @@ function mergeProcessKnowledge(config, runs) {
|
|
|
409
515
|
/* 学习事件失败不应让批次沉淀整体失败 */
|
|
410
516
|
}
|
|
411
517
|
}
|
|
412
|
-
return { added, merged, corrections: correctionsAdded, learnings: learningEvents.length, items: [...processDetails.values()], records: processRecords };
|
|
518
|
+
return { added, merged, corrections: correctionsAdded, learnings: learningEvents.length, experiencesAdded, experiences, items: [...processDetails.values()], records: processRecords };
|
|
413
519
|
}
|
|
414
520
|
|
|
415
521
|
/** 同一批次多轮/重跑时,保留上一轮的累计统计,避免第二轮把页面数覆盖成 0。 */
|
|
@@ -464,19 +570,42 @@ function mergeLearnedItem(item, previous) {
|
|
|
464
570
|
* 3) 成功执行与自我纠错 → 流程经验;
|
|
465
571
|
* 4) 写批次 knowledge.json 并把统计挂到 batch。
|
|
466
572
|
*/
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
const lock = await acquireKnowledgeLock(config);
|
|
573
|
+
async function runBatchKnowledgeDistill(config, batchId, { logger = null, startedAt = nowIso() } = {}) {
|
|
574
|
+
let lock = null;
|
|
470
575
|
try {
|
|
576
|
+
await patchStage(config, batchId, 'distill', {
|
|
577
|
+
status: 'running', phase: 'learn', done: 0, total: 0, startedAt, error: null,
|
|
578
|
+
});
|
|
579
|
+
lock = await acquireKnowledgeLock(config);
|
|
471
580
|
// 上一轮汇总必须在锁内读取,否则并发重试会用旧统计覆盖先完成的一轮。
|
|
472
581
|
const runs = readCaseRuns(config, batchId);
|
|
582
|
+
if (runs.length) {
|
|
583
|
+
await patchStage(config, batchId, 'distill', {
|
|
584
|
+
status: 'running', phase: 'learn', done: 0, total: runs.length, startedAt, error: null,
|
|
585
|
+
});
|
|
586
|
+
}
|
|
473
587
|
const previousByCase = new Map(
|
|
474
588
|
(readBatch(config, batchId).knowledge?.learned || []).map((item) => [String(item.caseId), item]),
|
|
475
589
|
);
|
|
476
590
|
const learned = [];
|
|
477
591
|
const errors = [];
|
|
478
592
|
const pageRecords = new Map();
|
|
479
|
-
|
|
593
|
+
const learnTotal = runs.length;
|
|
594
|
+
let learnWrites = 1;
|
|
595
|
+
let learnAt = Date.now();
|
|
596
|
+
const writeLearnProgress = async (done, force = false) => {
|
|
597
|
+
const now = Date.now();
|
|
598
|
+
if (!force && (learnWrites >= 20 || now - learnAt < 500)) return;
|
|
599
|
+
learnWrites += 1;
|
|
600
|
+
learnAt = now;
|
|
601
|
+
await patchStage(config, batchId, 'distill', {
|
|
602
|
+
status: 'running', phase: 'learn', done, total: learnTotal, startedAt, error: null,
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
for (let index = 0; index < runs.length; index += 1) {
|
|
606
|
+
// 本地学习是同步文件操作,定期让出事件循环,Host 才能响应进度轮询。
|
|
607
|
+
if (index > 0 && index % 25 === 0) await yieldEventLoop();
|
|
608
|
+
const run = runs[index];
|
|
480
609
|
const runCorrections = Array.isArray(run.corrections) && run.corrections.length
|
|
481
610
|
? run.corrections
|
|
482
611
|
: detectSelfCorrections(run.steps);
|
|
@@ -501,6 +630,7 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
|
|
|
501
630
|
};
|
|
502
631
|
if (!run.runDir) {
|
|
503
632
|
learned.push(mergeLearnedItem(item, previousByCase.get(String(item.caseId))));
|
|
633
|
+
await writeLearnProgress(index + 1, index + 1 === runs.length);
|
|
504
634
|
continue;
|
|
505
635
|
}
|
|
506
636
|
try {
|
|
@@ -545,16 +675,23 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
|
|
|
545
675
|
if (logger?.warn) logger.warn('知识沉淀失败 ' + run.caseId + ':' + item.error);
|
|
546
676
|
}
|
|
547
677
|
learned.push(mergeLearnedItem(item, previousByCase.get(String(item.caseId))));
|
|
678
|
+
await writeLearnProgress(index + 1, index + 1 === runs.length);
|
|
548
679
|
}
|
|
680
|
+
await patchStage(config, batchId, 'distill', {
|
|
681
|
+
status: 'running', phase: 'process', done: 0, total: 1, startedAt, error: null,
|
|
682
|
+
});
|
|
549
683
|
const skipCaseIds = staleCaseIds(config, batchId, runs);
|
|
550
684
|
let processes;
|
|
551
685
|
try {
|
|
552
686
|
processes = mergeProcessKnowledge(config, runs);
|
|
553
687
|
} catch (error) {
|
|
554
|
-
processes = { added: 0, merged: 0, corrections: 0, learnings: 0, items: [] };
|
|
688
|
+
processes = { added: 0, merged: 0, corrections: 0, learnings: 0, experiencesAdded: 0, experiences: [], items: [], records: new Map() };
|
|
555
689
|
errors.push({ caseId: '', message: '流程知识合并失败:' + String(error.message || error) });
|
|
556
690
|
if (logger?.warn) logger.warn('流程知识合并失败:' + String(error.message || error));
|
|
557
691
|
}
|
|
692
|
+
await patchStage(config, batchId, 'distill', {
|
|
693
|
+
status: 'running', phase: 'process', done: 1, total: 1, startedAt, error: null,
|
|
694
|
+
});
|
|
558
695
|
const processByCase = new Map((processes.items || []).map((item) => [String(item.caseId), item]));
|
|
559
696
|
for (const item of learned) {
|
|
560
697
|
item.process = processByCase.get(String(item.caseId)) || null;
|
|
@@ -566,46 +703,115 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
|
|
|
566
703
|
} catch {
|
|
567
704
|
/* 本地知识不可用时只靠本轮观察 */
|
|
568
705
|
}
|
|
706
|
+
await patchStage(config, batchId, 'distill', {
|
|
707
|
+
status: 'running', phase: 'episodes', done: 0, total: 1, startedAt, error: null,
|
|
708
|
+
});
|
|
569
709
|
const centralEpisodes = buildBatchCentralEpisodes(batchId, runs, learned, {
|
|
570
710
|
pageRecords,
|
|
571
711
|
processRecords: processes.records || new Map(),
|
|
712
|
+
experiences: [
|
|
713
|
+
...(processes.experiences || []),
|
|
714
|
+
...readExperiences(config, { limit: 2000 }).filter((event) => event.kind === 'page-observation'),
|
|
715
|
+
],
|
|
572
716
|
knownPages,
|
|
573
717
|
skipCaseIds,
|
|
574
718
|
});
|
|
719
|
+
const { knowledge: knowledgeEpisodes, evidence: evidenceEpisodes } = splitCentralEpisodes(centralEpisodes);
|
|
720
|
+
await patchStage(config, batchId, 'distill', {
|
|
721
|
+
status: 'running', phase: 'episodes', done: 1, total: 1, startedAt, error: null,
|
|
722
|
+
});
|
|
575
723
|
const centralBase = centralConfig(config);
|
|
576
724
|
let central = {
|
|
577
725
|
enabled: centralBase.enabled,
|
|
578
726
|
ok: false,
|
|
579
727
|
url: centralBase.url,
|
|
580
728
|
groupId: centralBase.groupId,
|
|
729
|
+
evidenceGroupId: centralBase.evidenceGroupId,
|
|
581
730
|
total: centralEpisodes.length,
|
|
582
731
|
ingested: 0,
|
|
583
732
|
skipped: 0,
|
|
584
733
|
failed: 0,
|
|
585
734
|
results: [],
|
|
586
735
|
errors: [],
|
|
736
|
+
mode: null,
|
|
737
|
+
groups: {},
|
|
587
738
|
at: nowIso(),
|
|
588
739
|
};
|
|
589
740
|
try {
|
|
590
741
|
if (centralBase.enabled) {
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
742
|
+
const groups = [
|
|
743
|
+
{ name: 'knowledge', groupId: centralBase.groupId, episodes: knowledgeEpisodes },
|
|
744
|
+
{ name: 'evidence', groupId: centralBase.evidenceGroupId, episodes: evidenceEpisodes },
|
|
745
|
+
].filter((group) => group.episodes.length);
|
|
746
|
+
if (!groups.length) {
|
|
747
|
+
central.ok = true;
|
|
748
|
+
} else {
|
|
749
|
+
const total = groups.reduce((sum, group) => sum + group.episodes.length, 0);
|
|
750
|
+
let offset = 0;
|
|
751
|
+
for (const group of groups) {
|
|
752
|
+
const report = await centralIngest(config, {
|
|
753
|
+
episodes: group.episodes,
|
|
754
|
+
groupId: group.groupId,
|
|
755
|
+
fast: true,
|
|
756
|
+
onProgress: async ({ done, mode }) => {
|
|
757
|
+
await patchStage(config, batchId, 'distill', {
|
|
758
|
+
status: 'running', phase: 'central', done: offset + done, total, startedAt, error: null, mode,
|
|
759
|
+
});
|
|
760
|
+
},
|
|
761
|
+
});
|
|
762
|
+
central.groups[group.name] = {
|
|
763
|
+
enabled: report.enabled,
|
|
764
|
+
groupId: report.groupId,
|
|
765
|
+
total: report.total,
|
|
766
|
+
ingested: report.ingested,
|
|
767
|
+
skipped: report.skipped,
|
|
768
|
+
failed: report.failed,
|
|
769
|
+
mode: report.mode,
|
|
770
|
+
};
|
|
771
|
+
central.ingested += Number(report.ingested) || 0;
|
|
772
|
+
central.skipped += Number(report.skipped) || 0;
|
|
773
|
+
central.failed += Number(report.failed) || 0;
|
|
774
|
+
central.results.push(...(report.results || []));
|
|
775
|
+
central.errors.push(...(report.errors || []));
|
|
776
|
+
central.mode = central.mode || report.mode || null;
|
|
777
|
+
offset += group.episodes.length;
|
|
778
|
+
}
|
|
779
|
+
central.ok = central.failed === 0 && central.errors.length === 0;
|
|
598
780
|
if (!central.ok && !central.error) {
|
|
599
|
-
central.error = String(
|
|
781
|
+
central.error = String(central.errors[0]?.error || '中心知识库写入失败');
|
|
600
782
|
}
|
|
601
|
-
} else {
|
|
602
|
-
central.ok = true;
|
|
603
783
|
}
|
|
604
784
|
}
|
|
605
785
|
} catch (error) {
|
|
606
786
|
central = { ...central, error: String(error.message || error), errors: [{ ok: false, error: String(error.message || error) }] };
|
|
607
787
|
if (logger?.warn) logger.warn('中心知识库写入失败:' + String(error.message || error));
|
|
608
788
|
}
|
|
789
|
+
let maintenanceResult = null;
|
|
790
|
+
let maintenanceError = '';
|
|
791
|
+
const maintenance = maintenanceOptions(config);
|
|
792
|
+
if (maintenance.afterBatch && runs.length) {
|
|
793
|
+
await patchStage(config, batchId, 'distill', {
|
|
794
|
+
status: 'running', phase: 'maintain', done: 0, total: 3, startedAt, error: null,
|
|
795
|
+
});
|
|
796
|
+
try {
|
|
797
|
+
maintenanceResult = await maintainKnowledge(config, {
|
|
798
|
+
options: maintenance,
|
|
799
|
+
logger,
|
|
800
|
+
onStage: async ({ done, total }) => {
|
|
801
|
+
await patchStage(config, batchId, 'distill', {
|
|
802
|
+
status: 'running', phase: 'maintain', done, total, startedAt, error: null,
|
|
803
|
+
});
|
|
804
|
+
},
|
|
805
|
+
});
|
|
806
|
+
if (!maintenanceResult.ok) {
|
|
807
|
+
maintenanceError = maintenanceResult.error;
|
|
808
|
+
if (logger?.warn) logger.warn('知识维护未全部完成:' + maintenanceError);
|
|
809
|
+
}
|
|
810
|
+
} catch (error) {
|
|
811
|
+
maintenanceError = String(error.message || error);
|
|
812
|
+
if (logger?.warn) logger.warn('知识维护失败:' + maintenanceError);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
609
815
|
const snapshot = knowledgeSnapshot(config, { limit: 50 });
|
|
610
816
|
const summary = {
|
|
611
817
|
at: nowIso(),
|
|
@@ -619,25 +825,56 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
|
|
|
619
825
|
corrections: learned.reduce((sum, item) => sum + item.corrections, 0),
|
|
620
826
|
processesAdded: processes.added,
|
|
621
827
|
processesMerged: processes.merged,
|
|
828
|
+
experiencesAdded: processes.experiencesAdded || 0,
|
|
622
829
|
experienceLearnings: processes.learnings,
|
|
623
830
|
learnedPages: learned.reduce((sum, item) => sum + item.pageItems.length, 0),
|
|
624
831
|
},
|
|
625
832
|
knowledge: snapshot.summary,
|
|
626
833
|
central,
|
|
834
|
+
maintenance: maintenanceResult,
|
|
835
|
+
maintenanceError: maintenanceError || undefined,
|
|
627
836
|
};
|
|
837
|
+
await patchStage(config, batchId, 'distill', {
|
|
838
|
+
status: 'running', phase: 'finalize', done: 0, total: 1, startedAt, error: null,
|
|
839
|
+
});
|
|
628
840
|
writeBatchText(config, batchId, 'knowledge.json', JSON.stringify(summary, null, 2) + '\n');
|
|
629
841
|
await patchBatch(config, batchId, { knowledge: summary });
|
|
842
|
+
await patchStage(config, batchId, 'distill', {
|
|
843
|
+
status: 'running', phase: 'finalize', done: 1, total: 1, startedAt, error: null,
|
|
844
|
+
});
|
|
630
845
|
await patchStage(config, batchId, 'distill', {
|
|
631
846
|
status: 'done',
|
|
847
|
+
phase: 'done',
|
|
848
|
+
done: 1,
|
|
849
|
+
total: 1,
|
|
632
850
|
at: summary.at,
|
|
633
851
|
pages: summary.totals.pages,
|
|
634
852
|
actions: summary.totals.actions,
|
|
635
853
|
processes: processes.added + processes.merged,
|
|
636
854
|
central: central.enabled ? central.ingested : 0,
|
|
855
|
+
maintenance: maintenanceResult ? (maintenanceResult.ok ? 'done' : 'failed') : 'off',
|
|
637
856
|
errors: errors.length,
|
|
857
|
+
mode: central.mode || null,
|
|
638
858
|
});
|
|
639
859
|
return summary;
|
|
860
|
+
} catch (error) {
|
|
861
|
+
await patchStage(config, batchId, 'distill', {
|
|
862
|
+
status: 'failed',
|
|
863
|
+
phase: 'failed',
|
|
864
|
+
error: String(error.message || error),
|
|
865
|
+
}).catch(() => {});
|
|
866
|
+
throw error;
|
|
640
867
|
} finally {
|
|
641
|
-
lock.release();
|
|
868
|
+
if (lock) lock.release();
|
|
642
869
|
}
|
|
643
870
|
}
|
|
871
|
+
|
|
872
|
+
export function commitBatchKnowledge(config, batchId, options = {}) {
|
|
873
|
+
const key = distillJobKey(config, batchId);
|
|
874
|
+
const promise = runBatchKnowledgeDistill(config, batchId, options);
|
|
875
|
+
distillJobs.set(key, promise);
|
|
876
|
+
promise.catch(() => {}).finally(() => {
|
|
877
|
+
if (distillJobs.get(key) === promise) distillJobs.delete(key);
|
|
878
|
+
});
|
|
879
|
+
return promise;
|
|
880
|
+
}
|
package/studio/snapshot.mjs
CHANGED
|
@@ -6,9 +6,11 @@ import fs from 'node:fs';
|
|
|
6
6
|
import { loadProjectCases } from '../lib/cases-import.mjs';
|
|
7
7
|
import { readResults, latestByCase, normalizeEvidenceFile } from '../lib/results.mjs';
|
|
8
8
|
import { readFlows } from '../host/state.mjs';
|
|
9
|
+
import { centralConfig } from '../lib/knowledge-central.mjs';
|
|
9
10
|
import { loadStudioCases } from './import.mjs';
|
|
10
11
|
import { knowledgeSnapshot } from './knowledge.mjs';
|
|
11
12
|
import { readRunFeedbacks } from '../lib/run-feedback.mjs';
|
|
13
|
+
import { latestAgentTasksSummary } from '../lib/agent-tasks.mjs';
|
|
12
14
|
import { listBatches, mergeBatchRuns, readCaseRuns } from './store.mjs';
|
|
13
15
|
import { documentRegistry, documentView } from './documents.mjs';
|
|
14
16
|
import { accountsPayload } from './accounts.mjs';
|
|
@@ -205,6 +207,7 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
205
207
|
archivedDocs: docs.filter((doc) => doc.archived).length,
|
|
206
208
|
};
|
|
207
209
|
const knowledge = knowledgeSnapshot(config, { limit: 100 });
|
|
210
|
+
const centralEffective = centralConfig(config);
|
|
208
211
|
const docsWarning = docRegistry.invalid
|
|
209
212
|
? '文档注册表损坏,文档写入已暂停:' + docRegistry.file + '(' + (docRegistry.error || '无法解析') + ')'
|
|
210
213
|
: '';
|
|
@@ -225,7 +228,8 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
225
228
|
knowledgeCentral: {
|
|
226
229
|
enabled: config.knowledge?.central?.enabled !== false,
|
|
227
230
|
url: config.knowledge?.central?.url || '',
|
|
228
|
-
groupId:
|
|
231
|
+
groupId: centralEffective.groupId,
|
|
232
|
+
evidenceGroupId: centralEffective.evidenceGroupId,
|
|
229
233
|
timeoutMs: Number(config.knowledge?.central?.timeoutMs) || 300000,
|
|
230
234
|
batchSize: Number(config.knowledge?.central?.batchSize) || 2,
|
|
231
235
|
searchTimeoutMs: Number(config.knowledge?.central?.searchTimeoutMs) || 10000,
|
|
@@ -240,6 +244,7 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
240
244
|
flowErrors: flowResult.errors || [],
|
|
241
245
|
batches: batches.map((batch) => batchSummary(batch, batch.status === 'running' ? readCaseRuns(config, batch.id) : [])),
|
|
242
246
|
activeBatch: active ? batchSummary(active, activeRuns) : null,
|
|
247
|
+
agentTasks: latestAgentTasksSummary(config),
|
|
243
248
|
docs,
|
|
244
249
|
docsError: docRegistry.invalid
|
|
245
250
|
? { code: 'DOCS_INVALID', file: docRegistry.file, message: docsWarning }
|