dsh-uitest 2.1.4 → 2.3.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/lib/csv.mjs ADDED
@@ -0,0 +1,207 @@
1
+ // CSV 用例解析:把逗号/制表符分隔的行映射成与 xlsx 相同的 rows 结构,
2
+ // 表头识别、列别名与字段归一化全部复用 xlsx.mjs 的 buildCases。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { UitestError } from './util.mjs';
7
+ import { buildCases, indexToCol } from './xlsx.mjs';
8
+
9
+ export class CsvError extends UitestError {
10
+ constructor(message, detail = {}) {
11
+ super(message, { code: 'CSV_ERROR', detail });
12
+ this.name = 'CsvError';
13
+ }
14
+ }
15
+
16
+ /** Excel 在中文 Windows 上导出的 CSV 常见 GB18030;UTF-8 严格解码失败才回退。 */
17
+ function stripBom(text) {
18
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
19
+ }
20
+
21
+ function decodeText(buffer) {
22
+ try {
23
+ return stripBom(new TextDecoder('utf-8', { fatal: true }).decode(buffer));
24
+ } catch {
25
+ try {
26
+ return stripBom(new TextDecoder('gb18030').decode(buffer));
27
+ } catch {
28
+ return stripBom(new TextDecoder('utf-8').decode(buffer));
29
+ }
30
+ }
31
+ }
32
+
33
+ function countOutsideQuotes(line, delimiter) {
34
+ let quoted = false;
35
+ let count = 0;
36
+ for (let i = 0; i < line.length; i += 1) {
37
+ const ch = line[i];
38
+ if (ch === '"') {
39
+ if (quoted && line[i + 1] === '"') {
40
+ i += 1;
41
+ } else {
42
+ quoted = !quoted;
43
+ }
44
+ } else if (ch === delimiter && !quoted) {
45
+ count += 1;
46
+ }
47
+ }
48
+ return count;
49
+ }
50
+
51
+ /** 取前若干条顶层记录,跳过引号内换行,避免前言行或字段内容干扰分隔符判断。 */
52
+ function topLevelLines(text, limit = 20) {
53
+ const lines = [];
54
+ let current = '';
55
+ let quoted = false;
56
+ for (let i = 0; i < text.length; i += 1) {
57
+ const ch = text[i];
58
+ if (ch === '"') {
59
+ if (quoted && text[i + 1] === '"') {
60
+ current += '""';
61
+ i += 1;
62
+ } else {
63
+ quoted = !quoted;
64
+ current += ch;
65
+ }
66
+ continue;
67
+ }
68
+ if (!quoted && (ch === '\n' || ch === '\r')) {
69
+ if (ch === '\r' && text[i + 1] === '\n') i += 1;
70
+ if (current.trim()) lines.push(current);
71
+ current = '';
72
+ if (lines.length >= limit) return lines;
73
+ continue;
74
+ }
75
+ current += ch;
76
+ }
77
+ if (current.trim() && lines.length < limit) lines.push(current);
78
+ return lines;
79
+ }
80
+
81
+ function detectDelimiter(text) {
82
+ const lines = topLevelLines(text);
83
+ let best = ',';
84
+ let bestLines = 0;
85
+ let bestCount = 0;
86
+ for (const candidate of [',', '\t', ';']) {
87
+ let lineCount = 0;
88
+ let total = 0;
89
+ for (const line of lines) {
90
+ const count = countOutsideQuotes(line, candidate);
91
+ if (count > 0) lineCount += 1;
92
+ total += count;
93
+ }
94
+ if (lineCount > bestLines || (lineCount === bestLines && total > bestCount)) {
95
+ best = candidate;
96
+ bestLines = lineCount;
97
+ bestCount = total;
98
+ }
99
+ }
100
+ return best;
101
+ }
102
+
103
+ /**
104
+ * RFC 4180 风格解析:双引号包裹字段,字段内允许分隔符与换行,"" 表示一个引号。
105
+ * 返回二维字符串数组,行内保留空字段。
106
+ */
107
+ export function parseCsv(text, { delimiter } = {}) {
108
+ const split = delimiter || detectDelimiter(text);
109
+ const rows = [];
110
+ let row = [];
111
+ let field = '';
112
+ let quoted = false;
113
+ const endField = () => {
114
+ row.push(field);
115
+ field = '';
116
+ };
117
+ const endRow = () => {
118
+ endField();
119
+ rows.push(row);
120
+ row = [];
121
+ };
122
+ for (let i = 0; i < text.length; i += 1) {
123
+ const ch = text[i];
124
+ if (quoted) {
125
+ if (ch === '"') {
126
+ if (text[i + 1] === '"') {
127
+ field += '"';
128
+ i += 1;
129
+ } else {
130
+ quoted = false;
131
+ }
132
+ } else {
133
+ field += ch;
134
+ }
135
+ continue;
136
+ }
137
+ if (ch === '"' && field === '') {
138
+ quoted = true;
139
+ continue;
140
+ }
141
+ if (ch === split) {
142
+ endField();
143
+ continue;
144
+ }
145
+ if (ch === '\n') {
146
+ endRow();
147
+ continue;
148
+ }
149
+ if (ch === '\r') {
150
+ if (text[i + 1] === '\n') i += 1;
151
+ endRow();
152
+ continue;
153
+ }
154
+ field += ch;
155
+ }
156
+ if (field !== '' || row.length) endRow();
157
+ return rows;
158
+ }
159
+
160
+ /** CSV 只有一张表;sheet 名用文件名,与 xlsx 的表头/列映射保持一致。 */
161
+ export function loadCsvCases({ file, headerRow, fill = true, maxScan = 10 } = {}) {
162
+ if (!file) throw new CsvError('未指定 CSV 用例文件');
163
+ const resolved = path.resolve(String(file));
164
+ let buffer;
165
+ try {
166
+ buffer = fs.readFileSync(resolved);
167
+ } catch (err) {
168
+ if (err.code === 'ENOENT') throw new CsvError(`CSV 文件不存在:${resolved}`, { file: resolved });
169
+ throw new CsvError(`读取 CSV 文件失败:${resolved}:${err.message}`, { file: resolved, cause: err });
170
+ }
171
+ const text = decodeText(buffer);
172
+ const table = parseCsv(text);
173
+ const rows = new Map();
174
+ let lastCol = 0;
175
+ table.forEach((values, index) => {
176
+ const rowNumber = index + 1;
177
+ const cells = new Map();
178
+ values.forEach((value, col) => {
179
+ if (value === '') return;
180
+ cells.set(col, { ref: indexToCol(col) + rowNumber, type: 's', value });
181
+ if (col + 1 > lastCol) lastCol = col + 1;
182
+ });
183
+ if (cells.size) rows.set(rowNumber, cells);
184
+ });
185
+ if (!rows.size) throw new CsvError(`CSV 文件是空的:${resolved}`, { file: resolved });
186
+ const sheet = path.basename(resolved);
187
+ // 大文件行数可以到十万级,不能把全部键展开成 Math.max 参数(会触发调用栈上限)。
188
+ let lastRow = 0;
189
+ for (const rowNumber of rows.keys()) if (rowNumber > lastRow) lastRow = rowNumber;
190
+ const built = buildCases({
191
+ rows,
192
+ merges: [],
193
+ sheet,
194
+ file: resolved,
195
+ headerRow,
196
+ fill,
197
+ maxScan,
198
+ kind: 'csv',
199
+ });
200
+ return {
201
+ file: resolved,
202
+ sheet,
203
+ sheets: [sheet],
204
+ dimension: `A1:${indexToCol(Math.max(0, lastCol - 1))}${lastRow}`,
205
+ ...built,
206
+ };
207
+ }
@@ -299,6 +299,22 @@ export async function centralIngestFast(config, { episodes = [], groupId = '' }
299
299
  };
300
300
  }
301
301
 
302
+ /** 自动管线状态;轮询用短超时,失败返回 ok:false 不抛出。 */
303
+ export async function centralPipelineStatus(config, { groupId = '' } = {}) {
304
+ const central = centralConfig(config);
305
+ const group = String(groupId || central.groupId);
306
+ const base = { enabled: central.enabled, groupId: group };
307
+ if (!central.enabled) return { ok: false, ...base, error: '中心知识库未启用' };
308
+ try {
309
+ const payload = await requestJson(config, '/pipeline/status?group_id=' + encodeURIComponent(group), {
310
+ timeoutMs: Math.min(central.searchTimeoutMs, 15000),
311
+ });
312
+ return { ...base, ...payload, ok: payload?.ok !== false };
313
+ } catch (error) {
314
+ return { ok: false, ...base, error: String(error.message || error), code: error.code || '' };
315
+ }
316
+ }
317
+
302
318
  /** 把提取结果送入 Graphiti 做实体/关系抽取,补齐语义检索。 */
303
319
  export async function centralSemanticIndex(config, { limit = 5, groupId = '' } = {}) {
304
320
  const central = centralConfig(config);
package/lib/xlsx.mjs CHANGED
@@ -688,6 +688,7 @@ export function buildCases({
688
688
  headerRow,
689
689
  fill = true,
690
690
  maxScan = 10,
691
+ kind = 'xlsx',
691
692
  } = {}) {
692
693
  let header;
693
694
  if (headerRow !== undefined && headerRow !== null) {
@@ -755,7 +756,7 @@ export function buildCases({
755
756
  cases.push({
756
757
  sheet: sheet || null,
757
758
  rowNumber,
758
- source: { kind: 'xlsx', file: file || '', sheet: sheet || null, rowNumber },
759
+ source: { kind, file: file || '', sheet: sheet || null, rowNumber },
759
760
  seq,
760
761
  tcId,
761
762
  priority: readCell(rowNumber, 'priority'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-uitest",
3
- "version": "2.1.4",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "description": "Test Studio for DSH: import cases into natural-language tests, seed preconditions, run flow and Agent cases concurrently with agent-browser, archive evidence, write back by batch, and accumulate reusable flows and page knowledge.",
6
6
  "icon": "./icon.svg",
@@ -7,14 +7,14 @@ description: Test Studio for a running web system: import test-case documents in
7
7
 
8
8
  ## 何时使用
9
9
 
10
- - 有一份测试用例文档(Markdown、文本、xlsx),需要在真实 Web 系统上做回归或验收。
10
+ - 有一份测试用例文档(Markdown、文本、xlsx、CSV),需要在真实 Web 系统上做回归或验收。
11
11
  - 用例还没有 flow,需要 Agent 按自然语言执行;或者已有 flow,需要批量并发回归。
12
12
  - 需要前置造数、截图证据、把结果写回用例文档,并把通过轨迹沉淀成可复跑 flow。
13
13
  - 需要把执行中看到的页面结构、动作和坑点持续积累为知识。
14
14
 
15
15
  ## 一条主线
16
16
 
17
- 1. **导入文档**:uitest_import 把 .md/.txt/.xlsx/.json 或目录整理成自然语言用例。源文档不改;Markdown/文本会生成到 cases/studio/ 下。
17
+ 1. **导入文档**:uitest_import 把 .md/.txt/.xlsx/.csv/.json 或目录整理成自然语言用例。源文档不改;Markdown/文本会生成到 cases/studio/ 下,CSV 会生成 Markdown 回写镜像。
18
18
  2. **检查用例**:uitest_cases 读前置条件、测试过程、预期结果、执行方式(flow / agent / manual)和最近结果。
19
19
  3. **规划**:uitest_batch action=start 会先做计划:有 flow 的走 flow 泳道,没有 flow 的走 Agent 泳道,缺前置数据时按 fixtures/recipes 造数,人工用例标记阻塞。
20
20
  4. **执行**:flow 与 Agent 两条泳道并发;Agent 用 agent-browser 逐步操作,每步自动截图并写 run.json。
@@ -26,7 +26,8 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
26
26
 
27
27
  ## 工具
28
28
 
29
- - uitest_import:导入文档或目录;返回 doc、case ids、warning。
29
+ - uitest_import:导入文档或目录;返回 doc、case ids、warning。传 docId 可重新关联已有文档,mode=overwrite 删除源文档已移除的用例。
30
+ - uitest_docs:文档层:list 查文档与归属;writeback 单文档回写(默认预览);re-read 重新导读;archive/restore;delete 需 confirm=true。
30
31
  - uitest_accounts:读取/导入/编辑测试账号;导入「OMS测试账号」表格,密码会保存到本地账号配置。
31
32
  - uitest_cases:按 id/query/mode/status 查用例;mode 取 flow、agent、manual、blocked。
32
33
  - uitest_batch:action=start 创建批次;action=status 查实时进度与每例证据;action=stop 请求停止;action=writeback 预览或执行回写。
@@ -42,6 +43,9 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
42
43
 
43
44
  node bin/studio.mjs import cases/新用例.md --project .
44
45
  node bin/studio.mjs cases --project . --mode agent
46
+ node bin/studio.mjs docs --project .
47
+ node bin/studio.mjs docs writeback <docId> --dry-run --project .
48
+ node bin/studio.mjs docs re-read <docId> --project .
45
49
  node bin/studio.mjs plan --project . --case TC-FP001-01
46
50
  node bin/studio.mjs batch create --project . --case TC-FP001-01 --workers 3
47
51
  node bin/studio.mjs batch run --project . --id <batchId>
@@ -57,6 +61,7 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
57
61
  ## 数据模型
58
62
 
59
63
  - Case:tcId、title、module、priority、precondition、steps、expected、remark、mode、flow、status、lastRun。
64
+ - Document:id、docKey、name、kind、sourcePath、generatedPath、caseIds、version、diff、lastRead、writeback、archived;用例归属以文档账本为准,用例是否存在仍看用例库。
60
65
  - Batch:id、name、status、stage、options、plan、summary、stages、resultDoc、writeback、knowledge。
61
66
  - CaseRun:caseId、mode、status、startedAt、endedAt、durationMs、seed、flow、agent、steps、evidence、runDir、note。
62
67
  - Flow:name、title、file、cases、requires、seedRecipes、steps、generated。
@@ -71,7 +76,7 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
71
76
  - 每个 worker 只写自己的 case-run 文件;批次汇总、归档、回写、知识合并由协调器串行完成。
72
77
  - 结果文档只在批次结束后写一次。不要在每个用例结束时单独回写同一份文档。
73
78
  - 回写使用单写者锁;并发回写返回 WRITEBACK_BUSY。等当前批次完成再试。
74
- - Markdown 回写插入带标记的结果块,重复回写会替换而不是追加;xlsx 生成执行结果副本,不覆盖原文档。
79
+ - Markdown 回写插入带标记的结果块,重复回写会替换而不是追加;xlsx 生成执行结果副本,不覆盖原文档;CSV 写入生成的 Markdown 镜像,CSV 用例编号必须能被 Markdown 回写解析(如 TC-XXX-01)。
75
80
  - 写业务数据的配方默认不执行;只有 allowWrites=true 才放行。造数前先确认源单库存与资源锁。
76
81
 
77
82
  ## Agent 执行规则
@@ -0,0 +1,332 @@
1
+ // 文档对象策略层:归属视图、来源/用例文件状态、分组与回写目标。
2
+ // 文档身份存 docs.json;用例是否存在仍以用例库为准,caseIds 只是拥有关系账本。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { normalizeDocumentRecord } from '../lib/cases-import.mjs';
7
+ import { UitestError, formatDate, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
8
+ import { readDocs, updateDocs } from './store.mjs';
9
+
10
+ function asArray(value) {
11
+ return Array.isArray(value) ? value : [];
12
+ }
13
+
14
+ function caseDocId(caseItem) {
15
+ return String(caseItem?.docId || caseItem?.source?.docId || '');
16
+ }
17
+
18
+ function caseIdOf(caseItem) {
19
+ return String(caseItem?.tcId || caseItem?.id || '');
20
+ }
21
+
22
+ function caseKey(value) {
23
+ return String(value || '').toLowerCase();
24
+ }
25
+
26
+ function resolveProjectPath(config, value) {
27
+ const text = String(value || '');
28
+ if (!text) return '';
29
+ return path.isAbsolute(text) ? path.resolve(text) : path.resolve(config.projectDir, text);
30
+ }
31
+
32
+ export function documentRegistry(config) {
33
+ const store = readDocs(config);
34
+ return {
35
+ version: Number(store.version) || 1,
36
+ updatedAt: store.updatedAt || '',
37
+ invalid: store.invalid === true,
38
+ error: store.error || '',
39
+ file: store.file || '',
40
+ docs: asArray(store.docs).map(normalizeDocumentRecord),
41
+ };
42
+ }
43
+
44
+ export function findDocument(config, { docId = '', docKey = '', sourcePath = '' } = {}) {
45
+ const { docs } = documentRegistry(config);
46
+ if (docId) return docs.find((doc) => doc.id === String(docId)) || null;
47
+ const key = normalizeDocKey(docKey);
48
+ if (key) {
49
+ const hit = docs.find((doc) => doc.docKey === key || normalizeDocKey(doc.name) === key);
50
+ if (hit) return hit;
51
+ }
52
+ if (sourcePath) {
53
+ const abs = path.resolve(config.projectDir, String(sourcePath));
54
+ return docs.find((doc) => [doc.sourcePath, doc.generatedPath]
55
+ .filter(Boolean)
56
+ .some((value) => path.resolve(config.projectDir, value) === abs)) || null;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ function matchDocumentRecord(config, docs, input) {
62
+ const byId = docs.find((doc) => doc.id === input.id) || null;
63
+ const byKey = input.docKey ? docs.find((doc) => doc.docKey === input.docKey) || null : null;
64
+ const byPath = input.sourcePath
65
+ ? docs.find((doc) => doc.sourcePath && resolveProjectPath(config, doc.sourcePath) === resolveProjectPath(config, input.sourcePath)) || null
66
+ : null;
67
+ const existing = byId || byKey || byPath;
68
+ // 重新关联到另一份文档的源文件时不能静默删掉那份文档:身份冲突必须显式报错。
69
+ const conflict = [byKey, byPath].find((doc) => doc && existing && doc.id !== existing.id) || null;
70
+ return { existing, conflict };
71
+ }
72
+
73
+ function sourceInUseError(conflict, existing, input) {
74
+ return new UitestError('该源文件已属于文档:' + (conflict.name || conflict.id), {
75
+ code: 'DOC_SOURCE_IN_USE',
76
+ detail: {
77
+ docId: existing.id,
78
+ otherDocId: conflict.id,
79
+ sourcePath: input.sourcePath || '',
80
+ otherSourcePath: conflict.sourcePath || '',
81
+ },
82
+ });
83
+ }
84
+
85
+ /**
86
+ * 导入写文件前预检身份冲突:命中时整次导入不产生任何副作用。
87
+ * 锁内 saveDocumentRecord 仍会复查,防止预检与落库之间注册表被并发修改。
88
+ */
89
+ export function assertDocumentSourceAvailable(config, record) {
90
+ const input = normalizeDocumentRecord(record);
91
+ const { docs } = documentRegistry(config);
92
+ const { existing, conflict } = matchDocumentRecord(config, docs, input);
93
+ if (conflict) throw sourceInUseError(conflict, existing, input);
94
+ }
95
+
96
+ /**
97
+ * 按 id → docKey → sourcePath 的顺序 upsert 一条文档记录,并去重。
98
+ * 命中旧记录时保留它的 id,改名不会换身份。
99
+ * reconcile 在锁内拿到磁盘上的旧记录,供调用方决定哪些字段以磁盘为准。
100
+ */
101
+ export function saveDocumentRecord(config, record, { reconcile = null } = {}) {
102
+ const input = normalizeDocumentRecord(record);
103
+ return updateDocs(config, (store) => {
104
+ const docs = asArray(store.docs).map(normalizeDocumentRecord);
105
+ const { existing, conflict } = matchDocumentRecord(config, docs, input);
106
+ if (conflict) throw sourceInUseError(conflict, existing, input);
107
+ const base = reconcile ? reconcile(existing, input) : { ...(existing || {}), ...input };
108
+ const saved = normalizeDocumentRecord({
109
+ ...base,
110
+ id: existing?.id || input.id,
111
+ importedAt: existing?.importedAt || input.importedAt || nowIso(),
112
+ updatedAt: nowIso(),
113
+ });
114
+ store.docs = [saved, ...docs.filter((doc) => {
115
+ if (doc.id === saved.id) return false;
116
+ if (saved.docKey && doc.docKey === saved.docKey) return false;
117
+ if (saved.sourcePath && doc.sourcePath && resolveProjectPath(config, doc.sourcePath) === resolveProjectPath(config, saved.sourcePath)) return false;
118
+ return true;
119
+ })];
120
+ return saved;
121
+ });
122
+ }
123
+
124
+ export function documentSourceState(config, doc) {
125
+ const sourcePath = String(doc?.sourcePath || '');
126
+ if (!sourcePath) return 'missing';
127
+ const abs = resolveProjectPath(config, sourcePath);
128
+ try {
129
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? 'ready' : 'missing';
130
+ } catch {
131
+ return 'missing';
132
+ }
133
+ }
134
+
135
+ export function documentWritebackPath(config, doc, date = formatDate(new Date())) {
136
+ const dir = path.join(config.paths.uitestDir, 'studio', 'writeback', doc.id);
137
+ const name = slug(doc.name || doc.id, 60) + '-执行结果-' + String(date || '').replace(/-/g, '') + '.xlsx';
138
+ return path.join(dir, name);
139
+ }
140
+
141
+ export function documentCaseFile(config, doc) {
142
+ if (!doc) return '';
143
+ if (doc.kind === 'xlsx') {
144
+ return doc.writeback?.targetPath || documentWritebackPath(config, doc);
145
+ }
146
+ return doc.generatedPath || '';
147
+ }
148
+
149
+ export function documentCaseFileState(config, doc) {
150
+ if (!doc) return 'missing';
151
+ if (doc.kind === 'xlsx') {
152
+ if (!doc.writeback?.targetPath) return 'pending';
153
+ return fs.existsSync(resolveProjectPath(config, doc.writeback.targetPath)) ? 'ready' : 'missing';
154
+ }
155
+ const file = documentCaseFile(config, doc);
156
+ if (!file) return 'missing';
157
+ const abs = resolveProjectPath(config, file);
158
+ try {
159
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? 'ready' : 'missing';
160
+ } catch {
161
+ return 'missing';
162
+ }
163
+ }
164
+
165
+ export function documentCounts(doc, cases, { deletedCaseIds = [] } = {}) {
166
+ const linked = asArray(cases).filter((item) => caseDocId(item) === doc.id);
167
+ const visible = new Set(linked.map((item) => caseKey(caseIdOf(item))));
168
+ const deleted = new Set(asArray(deletedCaseIds).map(caseKey));
169
+ let tombstoned = 0;
170
+ let stale = 0;
171
+ for (const id of doc.caseIds || []) {
172
+ const key = caseKey(id);
173
+ if (!key || visible.has(key)) continue;
174
+ if (deleted.has(key)) tombstoned += 1;
175
+ else stale += 1;
176
+ }
177
+ return {
178
+ visibleCount: linked.length,
179
+ tombstonedCount: tombstoned,
180
+ staleCount: stale,
181
+ ownedCount: linked.length + tombstoned,
182
+ cases: linked,
183
+ };
184
+ }
185
+
186
+ function statusCountsOf(cases) {
187
+ const counts = { total: cases.length, passed: 0, partial: 0, failed: 0, blocked: 0, queued: 0, running: 0, stopped: 0, untested: 0 };
188
+ for (const item of cases) {
189
+ const key = Object.hasOwn(counts, item?.status) && item.status !== 'total' ? item.status : 'untested';
190
+ counts[key] += 1;
191
+ }
192
+ return counts;
193
+ }
194
+
195
+ function lastRunOf(cases) {
196
+ let last = null;
197
+ for (const item of cases) {
198
+ const run = item?.lastRun;
199
+ if (!run) continue;
200
+ if (!last || String(run.at || '') > String(last.at || '')) {
201
+ last = {
202
+ caseId: caseIdOf(item),
203
+ status: run.status || '',
204
+ at: run.at || '',
205
+ batchId: run.batchId || '',
206
+ };
207
+ }
208
+ }
209
+ return last;
210
+ }
211
+
212
+ export function documentView(config, doc, cases, { deletedCaseIds = [] } = {}) {
213
+ const record = normalizeDocumentRecord(doc);
214
+ const counts = documentCounts(record, cases, { deletedCaseIds });
215
+ return {
216
+ id: record.id,
217
+ docKey: record.docKey,
218
+ name: record.name,
219
+ kind: record.kind,
220
+ archived: record.archived === true,
221
+ archivedAt: record.archivedAt || '',
222
+ sourcePath: record.sourcePath,
223
+ generatedPath: record.generatedPath,
224
+ caseFile: documentCaseFile(config, record),
225
+ sourceState: documentSourceState(config, record),
226
+ caseFileState: documentCaseFileState(config, record),
227
+ visibleCount: counts.visibleCount,
228
+ ownedCount: counts.ownedCount,
229
+ tombstonedCount: counts.tombstonedCount,
230
+ staleCount: counts.staleCount,
231
+ version: record.version,
232
+ mode: record.mode,
233
+ importedAt: record.importedAt,
234
+ updatedAt: record.updatedAt,
235
+ lastRead: record.lastRead,
236
+ writeback: record.writeback,
237
+ diff: record.diff,
238
+ statusCounts: statusCountsOf(counts.cases),
239
+ lastRun: lastRunOf(counts.cases),
240
+ };
241
+ }
242
+
243
+ export function groupCasesByDocument(docs, cases) {
244
+ const groups = asArray(docs).map((doc) => {
245
+ const record = normalizeDocumentRecord(doc);
246
+ return { doc: record, cases: [] };
247
+ });
248
+ const byId = new Map(groups.map((group) => [group.doc.id, group]));
249
+ const unassigned = [];
250
+ for (const item of asArray(cases)) {
251
+ const group = byId.get(caseDocId(item));
252
+ if (group) group.cases.push(item);
253
+ else unassigned.push(item);
254
+ }
255
+ return { groups, unassigned };
256
+ }
257
+
258
+ export function documentWriteTarget(config, doc, date = formatDate(new Date())) {
259
+ if (!doc) return { kind: 'none', reason: 'DOC_NOT_FOUND' };
260
+ if (doc.kind === 'markdown' || doc.kind === 'json' || doc.kind === 'csv') {
261
+ const file = doc.generatedPath || '';
262
+ if (!file) return { kind: 'none', path: '', reason: 'DOC_CASE_FILE_MISSING' };
263
+ // CSV 的回写目标是导入时生成的 Markdown 镜像,下游统一按 Markdown 处理。
264
+ return { kind: 'markdown', path: file, sourcePath: doc.sourcePath || '', sourceState: documentSourceState(config, doc) };
265
+ }
266
+ if (doc.kind === 'xlsx') {
267
+ const target = documentWritebackPath(config, doc, date);
268
+ const sourceState = documentSourceState(config, doc);
269
+ return {
270
+ kind: 'xlsx',
271
+ path: target,
272
+ sourcePath: doc.sourcePath || '',
273
+ sourceState,
274
+ reason: sourceState === 'ready' ? '' : 'DOC_SOURCE_MISSING',
275
+ };
276
+ }
277
+ return { kind: 'none', path: '', reason: 'DOC_KIND_UNSUPPORTED' };
278
+ }
279
+
280
+ /** 锁内按 id 修改单条文档记录;回调拿到的是磁盘上的最新记录。 */
281
+ export function updateDocumentRecord(config, docId, mutate) {
282
+ const id = String(docId || '');
283
+ return updateDocs(config, (store) => {
284
+ const docs = asArray(store.docs).map(normalizeDocumentRecord);
285
+ const index = docs.findIndex((doc) => doc.id === id);
286
+ if (index < 0) throw new UitestError('文档不存在:' + id, { code: 'DOC_NOT_FOUND', detail: { docId: id } });
287
+ const current = { ...docs[index] };
288
+ const next = mutate(current) || current;
289
+ const saved = normalizeDocumentRecord({ ...next, id: docs[index].id, updatedAt: nowIso() });
290
+ docs[index] = saved;
291
+ store.docs = docs;
292
+ return saved;
293
+ });
294
+ }
295
+
296
+ /** 归档只改注册表,不碰用例、源文件或已生成的用例文件。 */
297
+ export function setDocumentArchived(config, docId, archived = true) {
298
+ const flag = archived === true;
299
+ return updateDocumentRecord(config, docId, (current) => ({
300
+ ...current,
301
+ archived: flag,
302
+ archivedAt: flag ? (current.archivedAt || nowIso()) : '',
303
+ }));
304
+ }
305
+
306
+ /**
307
+ * 删除文档记录。用例仍在用例库中,只是失去文档归属;源文件与用例文件都不删。
308
+ * 同一 docKey 再次导入会得到确定性 id,旧用例可以重新关联回来。
309
+ */
310
+ export function deleteDocumentRecord(config, docId) {
311
+ const id = String(docId || '');
312
+ return updateDocs(config, (store) => {
313
+ const docs = asArray(store.docs).map(normalizeDocumentRecord);
314
+ const index = docs.findIndex((doc) => doc.id === id);
315
+ if (index < 0) throw new UitestError('文档不存在:' + id, { code: 'DOC_NOT_FOUND', detail: { docId: id } });
316
+ const removed = docs[index];
317
+ store.docs = docs.filter((doc) => doc.id !== id);
318
+ return removed;
319
+ });
320
+ }
321
+
322
+ /**
323
+ * 回写只能做锁内读改写。调用方手里的文档快照可能已经落后于并发的
324
+ * 重新导读/导入,整条覆盖会回滚 version、lastRead 与 caseIds。
325
+ */
326
+ export function recordDocumentWriteback(config, doc, summary) {
327
+ const docId = typeof doc === 'string' ? doc : doc?.id;
328
+ return updateDocumentRecord(config, docId, (current) => ({
329
+ ...current,
330
+ writeback: { ...summary, at: summary?.at || nowIso() },
331
+ }));
332
+ }