dsh-requirement-dev-workbench 0.0.0-stage → 4.5.4
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/CHANGELOG.md +190 -0
- package/LICENSE +21 -0
- package/README.md +352 -2
- package/cordis.patch.yml +13 -0
- package/dsh/index.js +3018 -0
- package/lib/client.js +5590 -0
- package/package.json +64 -5
package/dsh/index.js
ADDED
|
@@ -0,0 +1,3018 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Native 工作台(包名沿用 dsh-requirement-dev-workbench)· 服务端入口
|
|
3
|
+
*
|
|
4
|
+
* 职责:
|
|
5
|
+
* - 把工作台设置(飞书多维表格地址、所选项目目录、技能根目录)持久化到 DSH 数据目录;
|
|
6
|
+
* - 通过 lark-cli 读取飞书多维表格里的开发需求;
|
|
7
|
+
* - 扫描并读取项目/全局 skill 与开发规范文档;
|
|
8
|
+
* - 在本工作台自己的路径前缀 /api/requirement-dev-workbench/ 下提供本机接口。
|
|
9
|
+
*
|
|
10
|
+
* 不持有任何凭证:一律调用用户本机已登录的 lark-cli。
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process'
|
|
13
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
14
|
+
import { homedir, tmpdir } from 'node:os'
|
|
15
|
+
import { readFile, mkdir, readdir, rm, stat, writeFile, appendFile } from 'node:fs/promises'
|
|
16
|
+
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
17
|
+
import { fileURLToPath } from 'node:url'
|
|
18
|
+
import Schema from '@deepseek-ai/schemastery'
|
|
19
|
+
|
|
20
|
+
export const name = 'requirement-dev-workbench'
|
|
21
|
+
export const inject = ['webServer']
|
|
22
|
+
export const Config = Schema.object({
|
|
23
|
+
root: Schema.string().required(),
|
|
24
|
+
larkCli: Schema.string().default(''),
|
|
25
|
+
identity: Schema.string().default('user'),
|
|
26
|
+
skillsRoots: Schema.array(Schema.string()).default([]),
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
const API_PREFIX = '/api/requirement-dev-workbench'
|
|
30
|
+
const MAX_OUTPUT = 4 * 1024 * 1024
|
|
31
|
+
const LARK_TIMEOUT_MS = 45_000
|
|
32
|
+
|
|
33
|
+
/* ------------------------------------------------------------------ 进程 */
|
|
34
|
+
|
|
35
|
+
function runCommand(command, args, { timeoutMs = LARK_TIMEOUT_MS } = {}) {
|
|
36
|
+
return new Promise((resolvePromise) => {
|
|
37
|
+
let child
|
|
38
|
+
try {
|
|
39
|
+
child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
40
|
+
} catch (error) {
|
|
41
|
+
resolvePromise({ ok: false, code: -1, stdout: '', stderr: String(error?.message ?? error) })
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
let stdout = ''
|
|
45
|
+
let stderr = ''
|
|
46
|
+
let settled = false
|
|
47
|
+
const finish = (result) => {
|
|
48
|
+
if (settled) return
|
|
49
|
+
settled = true
|
|
50
|
+
clearTimeout(timer)
|
|
51
|
+
resolvePromise(result)
|
|
52
|
+
}
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
try { child.kill() } catch { /* 已退出 */ }
|
|
55
|
+
finish({ ok: false, code: -1, stdout, stderr: `${stderr}\n[工作台] 命令超时(${timeoutMs}ms)` })
|
|
56
|
+
}, timeoutMs)
|
|
57
|
+
child.stdout?.on('data', (chunk) => {
|
|
58
|
+
if (stdout.length < MAX_OUTPUT) stdout += String(chunk)
|
|
59
|
+
})
|
|
60
|
+
child.stderr?.on('data', (chunk) => {
|
|
61
|
+
if (stderr.length < MAX_OUTPUT) stderr += String(chunk)
|
|
62
|
+
})
|
|
63
|
+
child.on('error', (error) => finish({ ok: false, code: -1, stdout, stderr: String(error?.message ?? error) }))
|
|
64
|
+
child.on('close', (code) => finish({ ok: code === 0, code: code ?? -1, stdout, stderr }))
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** .cmd/.bat 包装脚本里的真实入口(本机 lark-cli 是 node 脚本,见 %dp0%\node_modules\...\run.js)。 */
|
|
69
|
+
function cmdShimTarget(command) {
|
|
70
|
+
try {
|
|
71
|
+
const text = readFileSync(command, 'utf8')
|
|
72
|
+
const match = /%dp0%\\([^"\s]+\.js)/i.exec(text) || /%dp0%\\?([^"\s]+\.js)/i.exec(text)
|
|
73
|
+
if (!match) return ''
|
|
74
|
+
const target = resolve(dirname(command), match[1])
|
|
75
|
+
return existsSync(target) ? target : ''
|
|
76
|
+
} catch {
|
|
77
|
+
return ''
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* lark-cli 在本机是 .cmd/.ps1 包装。
|
|
83
|
+
* 能解析到真实 node 入口就直接跑(参数不再被 cmd.exe 重新解释一遍——带引号的 --json 经过 cmd.exe 会卡住),
|
|
84
|
+
* 解析不到才退回 cmd.exe/PowerShell 包装。
|
|
85
|
+
*/
|
|
86
|
+
function shellWrapper(command) {
|
|
87
|
+
const lower = command.toLowerCase()
|
|
88
|
+
if (lower.endsWith('.ps1')) {
|
|
89
|
+
return { file: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', command] }
|
|
90
|
+
}
|
|
91
|
+
if (lower.endsWith('.cmd') || lower.endsWith('.bat')) {
|
|
92
|
+
const direct = cmdShimTarget(command)
|
|
93
|
+
if (direct) {
|
|
94
|
+
const nodeExe = join(dirname(command), 'node.exe')
|
|
95
|
+
return {
|
|
96
|
+
file: existsSync(nodeExe) ? nodeExe : 'node',
|
|
97
|
+
args: [direct],
|
|
98
|
+
fallback: { file: 'cmd.exe', args: ['/d', '/s', '/c', command] },
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return { file: 'cmd.exe', args: ['/d', '/s', '/c', command] }
|
|
102
|
+
}
|
|
103
|
+
return { file: command, args: [] }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 跑 lark-cli:直接跑真身失败(例如找不到 node)时,自动退回包装脚本再试一次。 */
|
|
107
|
+
async function runLark(wrapper, args) {
|
|
108
|
+
const first = await runCommand(wrapper.file, [...wrapper.args, ...args])
|
|
109
|
+
if (first.ok || !wrapper.fallback || first.code !== -1) return first
|
|
110
|
+
return runCommand(wrapper.fallback.file, [...wrapper.fallback.args, ...args])
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 解析 lark-cli 的位置:先配置、再 PATH(where.exe),最后退回裸名。 */
|
|
114
|
+
async function resolveLarkCli(configured) {
|
|
115
|
+
if (configured) return configured
|
|
116
|
+
if (process.platform === 'win32') {
|
|
117
|
+
const probe = await runCommand('where.exe', ['lark-cli'], { timeoutMs: 10_000 })
|
|
118
|
+
const lines = probe.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
|
|
119
|
+
// where.exe 会同时列出一个没有扩展名的 shell 垫片(spawn 不了),优先可执行的扩展名。
|
|
120
|
+
const ranked = [...lines].sort((a, b) => extensionRank(a) - extensionRank(b))
|
|
121
|
+
for (const candidate of ranked) {
|
|
122
|
+
if (extensionRank(candidate) < 9) return candidate
|
|
123
|
+
for (const ext of ['.cmd', '.exe', '.bat', '.ps1']) {
|
|
124
|
+
const withExt = `${candidate}${ext}`
|
|
125
|
+
if (existsSync(withExt)) return withExt
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (lines[0]) return lines[0]
|
|
129
|
+
}
|
|
130
|
+
return 'lark-cli'
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 越小越优先:真正的可执行入口排在没有扩展名的垫片前面。 */
|
|
134
|
+
function extensionRank(file) {
|
|
135
|
+
const lower = String(file).toLowerCase()
|
|
136
|
+
if (lower.endsWith('.cmd') || lower.endsWith('.exe') || lower.endsWith('.bat')) return 0
|
|
137
|
+
if (lower.endsWith('.ps1')) return 1
|
|
138
|
+
return 9
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/* ----------------------------------------------------------------- 设置 */
|
|
142
|
+
|
|
143
|
+
const DEFAULT_SETTINGS = {
|
|
144
|
+
sourceName: '',
|
|
145
|
+
baseToken: '',
|
|
146
|
+
tableId: '',
|
|
147
|
+
viewId: '',
|
|
148
|
+
titleField: '',
|
|
149
|
+
statusField: '',
|
|
150
|
+
projectField: '',
|
|
151
|
+
ownerField: '',
|
|
152
|
+
projectDir: '',
|
|
153
|
+
skillsRoots: [],
|
|
154
|
+
expert: '',
|
|
155
|
+
// 全局默认:新建流水线是否用 AgentTeams 团队执行('true' / '')。每条流水线仍可单独覆盖。
|
|
156
|
+
flowTeamMode: '',
|
|
157
|
+
updatedAt: '',
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function settingsFile(config) {
|
|
161
|
+
return join(config.root, 'settings.json')
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function readSettings(config) {
|
|
165
|
+
try {
|
|
166
|
+
const raw = await readFile(settingsFile(config), 'utf8')
|
|
167
|
+
const parsed = JSON.parse(raw)
|
|
168
|
+
return { ...DEFAULT_SETTINGS, ...(parsed && typeof parsed === 'object' ? parsed : {}) }
|
|
169
|
+
} catch {
|
|
170
|
+
return { ...DEFAULT_SETTINGS }
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function writeSettings(config, patch) {
|
|
175
|
+
const current = await readSettings(config)
|
|
176
|
+
const next = { ...current }
|
|
177
|
+
for (const [key, value] of Object.entries(patch ?? {})) {
|
|
178
|
+
if (!(key in DEFAULT_SETTINGS)) continue
|
|
179
|
+
if (value === undefined || value === null) continue
|
|
180
|
+
next[key] = Array.isArray(value) ? value.map(String) : String(value)
|
|
181
|
+
}
|
|
182
|
+
next.updatedAt = new Date().toISOString()
|
|
183
|
+
await mkdir(dirname(settingsFile(config)), { recursive: true })
|
|
184
|
+
await writeFile(settingsFile(config), `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
185
|
+
return next
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/* --------------------------------------------------- 清单/看板的视图配置 */
|
|
189
|
+
|
|
190
|
+
const DEFAULT_VIEW = {
|
|
191
|
+
// v3:多表 + 可扩展模块
|
|
192
|
+
modules: [], // [{ key, tableKey, title, view: 'list' | 'board' | 'progress' }]
|
|
193
|
+
activeModule: '',
|
|
194
|
+
tables: {}, // tableKey -> 该表的页面配置切片
|
|
195
|
+
// v2 单表时代的字段,保留为「任何表的兜底默认值」
|
|
196
|
+
filters: [], // [{ field, values: [], text: '' }] 字段级筛选(选项多选 / 文本包含)
|
|
197
|
+
groupField: '状态', // 卡片看板按哪个字段分模块
|
|
198
|
+
cardSummaryField: '', // 卡片上展示的内容字段(空 = 原始需求)
|
|
199
|
+
listFields: [], // 汇总清单显示的列(空 = 自动挑)
|
|
200
|
+
cardFields: [], // 卡片上展示的字段(空 = 状态/负责人/优先级/期望完成时间)
|
|
201
|
+
moduleOrder: [], // 模块手工排序
|
|
202
|
+
hiddenModules: [], // 隐藏的模块
|
|
203
|
+
collapsedModules: [], // 折叠的模块
|
|
204
|
+
writeBackOnDrag: false, // 拖动卡片换模块时是否回写飞书
|
|
205
|
+
railWidth: 168, // 左侧模块栏宽度(可拖动调整,120~380)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 侧边栏宽度:只收 120~380 之间的整数,别的当默认值。 */
|
|
209
|
+
function clampRailWidth(value) {
|
|
210
|
+
const number = Number(value)
|
|
211
|
+
if (!Number.isFinite(number) || number <= 0) return DEFAULT_VIEW.railWidth
|
|
212
|
+
return Math.min(380, Math.max(120, Math.round(number)))
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** 单张表的配置切片:只接受已知键,防脏数据。 */
|
|
216
|
+
function sanitizeTableSlice(slice) {
|
|
217
|
+
const out = {}
|
|
218
|
+
if (!slice || typeof slice !== 'object') return out
|
|
219
|
+
if (Array.isArray(slice.filters)) {
|
|
220
|
+
out.filters = slice.filters
|
|
221
|
+
.filter((item) => item && typeof item.field === 'string' && item.field)
|
|
222
|
+
.map((item) => ({ field: item.field, values: asStringArray(item.values), text: String(item.text ?? '') }))
|
|
223
|
+
}
|
|
224
|
+
for (const key of ['groupField', 'cardSummaryField']) {
|
|
225
|
+
if (typeof slice[key] === 'string') out[key] = slice[key]
|
|
226
|
+
}
|
|
227
|
+
for (const key of ['listFields', 'cardFields', 'moduleOrder', 'hiddenModules', 'collapsedModules']) {
|
|
228
|
+
if (Array.isArray(slice[key])) out[key] = asStringArray(slice[key])
|
|
229
|
+
}
|
|
230
|
+
if (typeof slice.writeBackOnDrag === 'boolean') out.writeBackOnDrag = slice.writeBackOnDrag
|
|
231
|
+
return out
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 一个模块项:key 唯一,指向某张表 + 一种视图;template 记录它是按哪个标准模板建的(可缺省)。 */
|
|
235
|
+
function sanitizeModule(item, index) {
|
|
236
|
+
if (!item || typeof item !== 'object' || typeof item.tableKey !== 'string' || !item.tableKey) return null
|
|
237
|
+
const out = {
|
|
238
|
+
key: String(item.key || `${item.tableKey}#${index}`),
|
|
239
|
+
tableKey: item.tableKey,
|
|
240
|
+
title: String(item.title || item.tableKey),
|
|
241
|
+
view: ['list', 'board', 'progress'].includes(item.view) ? item.view : 'list',
|
|
242
|
+
}
|
|
243
|
+
// 模板 id 只是标签,认不出就丢掉,不影响模块本身。
|
|
244
|
+
const template = typeof item.template === 'string' ? item.template.trim() : ''
|
|
245
|
+
if (/^[a-z][a-z0-9-]{0,31}$/.test(template)) out.template = template
|
|
246
|
+
return out
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function viewFile(config) {
|
|
250
|
+
return join(config.root, 'view.json')
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function asStringArray(value) {
|
|
254
|
+
return Array.isArray(value) ? value.map(String) : []
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function readView(config) {
|
|
258
|
+
try {
|
|
259
|
+
const raw = await readFile(viewFile(config), 'utf8')
|
|
260
|
+
const parsed = JSON.parse(raw)
|
|
261
|
+
const source = parsed && typeof parsed === 'object' ? parsed : {}
|
|
262
|
+
const tables = {}
|
|
263
|
+
for (const [key, slice] of Object.entries(source.tables && typeof source.tables === 'object' ? source.tables : {})) {
|
|
264
|
+
tables[key] = sanitizeTableSlice(slice)
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
...DEFAULT_VIEW,
|
|
268
|
+
...source,
|
|
269
|
+
modules: Array.isArray(source.modules) ? source.modules.map(sanitizeModule).filter(Boolean) : [],
|
|
270
|
+
tables,
|
|
271
|
+
filters: Array.isArray(source.filters)
|
|
272
|
+
? source.filters
|
|
273
|
+
.filter((item) => item && typeof item.field === 'string' && item.field)
|
|
274
|
+
.map((item) => ({ field: item.field, values: asStringArray(item.values), text: String(item.text ?? '') }))
|
|
275
|
+
: [],
|
|
276
|
+
listFields: asStringArray(source.listFields),
|
|
277
|
+
cardFields: asStringArray(source.cardFields),
|
|
278
|
+
moduleOrder: asStringArray(source.moduleOrder),
|
|
279
|
+
hiddenModules: asStringArray(source.hiddenModules),
|
|
280
|
+
collapsedModules: asStringArray(source.collapsedModules),
|
|
281
|
+
writeBackOnDrag: Boolean(source.writeBackOnDrag),
|
|
282
|
+
railWidth: clampRailWidth(source.railWidth),
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
return { ...DEFAULT_VIEW, modules: [], tables: {}, filters: [], listFields: [], cardFields: [], moduleOrder: [], hiddenModules: [], collapsedModules: [] }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function writeView(config, patch) {
|
|
290
|
+
const current = await readView(config)
|
|
291
|
+
const next = { ...current }
|
|
292
|
+
if (Array.isArray(patch?.modules)) {
|
|
293
|
+
next.modules = patch.modules.map(sanitizeModule).filter(Boolean)
|
|
294
|
+
}
|
|
295
|
+
if (typeof patch?.activeModule === 'string') next.activeModule = patch.activeModule
|
|
296
|
+
if (patch?.tables && typeof patch.tables === 'object') {
|
|
297
|
+
next.tables = { ...(current.tables ?? {}) }
|
|
298
|
+
for (const [key, slice] of Object.entries(patch.tables)) {
|
|
299
|
+
next.tables[key] = { ...(next.tables[key] ?? {}), ...sanitizeTableSlice(slice) }
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (Array.isArray(patch?.filters)) {
|
|
303
|
+
next.filters = patch.filters
|
|
304
|
+
.filter((item) => item && typeof item.field === 'string' && item.field)
|
|
305
|
+
.map((item) => ({ field: item.field, values: asStringArray(item.values), text: String(item.text ?? '') }))
|
|
306
|
+
}
|
|
307
|
+
if (typeof patch?.groupField === 'string') next.groupField = patch.groupField
|
|
308
|
+
if (typeof patch?.cardSummaryField === 'string') next.cardSummaryField = patch.cardSummaryField
|
|
309
|
+
if (Array.isArray(patch?.listFields)) next.listFields = asStringArray(patch.listFields)
|
|
310
|
+
if (Array.isArray(patch?.cardFields)) next.cardFields = asStringArray(patch.cardFields)
|
|
311
|
+
if (Array.isArray(patch?.moduleOrder)) next.moduleOrder = asStringArray(patch.moduleOrder)
|
|
312
|
+
if (Array.isArray(patch?.hiddenModules)) next.hiddenModules = asStringArray(patch.hiddenModules)
|
|
313
|
+
if (Array.isArray(patch?.collapsedModules)) next.collapsedModules = asStringArray(patch.collapsedModules)
|
|
314
|
+
if (typeof patch?.writeBackOnDrag === 'boolean') next.writeBackOnDrag = patch.writeBackOnDrag
|
|
315
|
+
if (patch?.railWidth !== undefined) next.railWidth = clampRailWidth(patch.railWidth)
|
|
316
|
+
next.updatedAt = new Date().toISOString()
|
|
317
|
+
await mkdir(dirname(viewFile(config)), { recursive: true })
|
|
318
|
+
await writeFile(viewFile(config), `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
319
|
+
return next
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/* ----------------------------------- 多张飞书表(需求池 + 开发任务表…) */
|
|
323
|
+
|
|
324
|
+
const TASK_CONFIG_FILES = ['.dev-task-sources.json', join('doc', 'dev-task-sources.json')]
|
|
325
|
+
|
|
326
|
+
/** 读项目里已有的开发任务表配置(dev-task-sync 用的那一份)。 */
|
|
327
|
+
export async function loadTaskTables(projectDir) {
|
|
328
|
+
if (!projectDir) return null
|
|
329
|
+
for (const rel of TASK_CONFIG_FILES) {
|
|
330
|
+
const file = join(projectDir, rel)
|
|
331
|
+
const text = await readFile(file, 'utf8').catch(() => null)
|
|
332
|
+
if (text === null) continue
|
|
333
|
+
let parsed
|
|
334
|
+
try {
|
|
335
|
+
parsed = JSON.parse(text)
|
|
336
|
+
} catch {
|
|
337
|
+
continue
|
|
338
|
+
}
|
|
339
|
+
const raw = parsed?.projects && typeof parsed.projects === 'object' ? parsed.projects : {}
|
|
340
|
+
const names = Object.keys(raw)
|
|
341
|
+
if (!names.length) continue
|
|
342
|
+
return {
|
|
343
|
+
path: file,
|
|
344
|
+
defaultProject: parsed.defaultProject && raw[parsed.defaultProject] ? parsed.defaultProject : names[0],
|
|
345
|
+
projects: names.map((name) => ({ name, ...raw[name] })),
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return null
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function tableSpecFrom({ key, label, kind, sourceName, entry, configPath, defaultIdentity }) {
|
|
352
|
+
const url = parseBaseInput(entry?.baseUrl ?? '')
|
|
353
|
+
return {
|
|
354
|
+
key,
|
|
355
|
+
label,
|
|
356
|
+
kind,
|
|
357
|
+
sourceName,
|
|
358
|
+
tableName: String(entry?.tableName ?? ''),
|
|
359
|
+
baseToken: url.baseToken,
|
|
360
|
+
tableId: url.tableId || '',
|
|
361
|
+
viewId: url.viewId || '',
|
|
362
|
+
fieldMap: entry?.fields ?? null,
|
|
363
|
+
filter: entry?.filter ?? null,
|
|
364
|
+
identity: entry?.identity || defaultIdentity || 'user',
|
|
365
|
+
configPath: configPath ?? '',
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** 所有可用的表:项目里配了几张就有几张。 */
|
|
370
|
+
export async function listTables(config, settings) {
|
|
371
|
+
const tables = []
|
|
372
|
+
const requirement = await loadRequirementSources(settings.projectDir)
|
|
373
|
+
for (const source of requirement?.sources ?? []) {
|
|
374
|
+
tables.push(
|
|
375
|
+
tableSpecFrom({
|
|
376
|
+
key: `requirement:${source.name}`,
|
|
377
|
+
label: `开发需求 · ${source.name}`,
|
|
378
|
+
kind: 'requirement',
|
|
379
|
+
sourceName: source.name,
|
|
380
|
+
entry: source,
|
|
381
|
+
configPath: requirement.path,
|
|
382
|
+
defaultIdentity: config.identity,
|
|
383
|
+
}),
|
|
384
|
+
)
|
|
385
|
+
}
|
|
386
|
+
const tasks = await loadTaskTables(settings.projectDir)
|
|
387
|
+
for (const project of tasks?.projects ?? []) {
|
|
388
|
+
tables.push(
|
|
389
|
+
tableSpecFrom({
|
|
390
|
+
key: `task:${project.name}`,
|
|
391
|
+
label: `开发任务 · ${project.name}`,
|
|
392
|
+
kind: 'task',
|
|
393
|
+
sourceName: project.name,
|
|
394
|
+
entry: project,
|
|
395
|
+
configPath: tasks.path,
|
|
396
|
+
defaultIdentity: config.identity,
|
|
397
|
+
}),
|
|
398
|
+
)
|
|
399
|
+
}
|
|
400
|
+
// 不静默丢表:认不出来的表要留下原因,界面上可见(诊断报告 P3)。
|
|
401
|
+
const usable = []
|
|
402
|
+
const dropped = []
|
|
403
|
+
for (const table of tables) {
|
|
404
|
+
if (!table.baseToken) {
|
|
405
|
+
dropped.push({ key: table.key, label: table.label, configPath: table.configPath, reason: '缺 baseToken:配置里的链接认不出多维表格 base,请贴完整链接' })
|
|
406
|
+
continue
|
|
407
|
+
}
|
|
408
|
+
if (!table.tableId) {
|
|
409
|
+
dropped.push({ key: table.key, label: table.label, configPath: table.configPath, reason: '缺 tableId:配置里没有 table 参数' })
|
|
410
|
+
continue
|
|
411
|
+
}
|
|
412
|
+
// 飞书表 id 恒为 tblxxxx。以前把「表名」当 id 传下去,lark-cli 只会报一句看不懂的错。
|
|
413
|
+
if (!/^tbl[A-Za-z0-9]+$/.test(table.tableId)) {
|
|
414
|
+
dropped.push({
|
|
415
|
+
key: table.key,
|
|
416
|
+
label: table.label,
|
|
417
|
+
configPath: table.configPath,
|
|
418
|
+
reason: `tableId 不像飞书表 id(${table.tableId}):链接里应该是 ?table=tblxxxx,不能直接写表名`,
|
|
419
|
+
})
|
|
420
|
+
continue
|
|
421
|
+
}
|
|
422
|
+
usable.push(table)
|
|
423
|
+
}
|
|
424
|
+
return { tables: usable, dropped, requirementConfig: requirement?.path ?? '', taskConfig: tasks?.path ?? '' }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
export async function findTable(config, settings, key) {
|
|
428
|
+
const { tables, requirementConfig, taskConfig } = await listTables(config, settings)
|
|
429
|
+
const wanted = String(key ?? '').trim()
|
|
430
|
+
const found = wanted
|
|
431
|
+
? tables.find((table) => table.key === wanted) ??
|
|
432
|
+
tables.find((table) => table.sourceName === wanted) ??
|
|
433
|
+
tables.find((table) => table.tableId === wanted)
|
|
434
|
+
: null
|
|
435
|
+
return { table: found ?? tables[0] ?? null, tables, requirementConfig, taskConfig }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const recordCache = new Map()
|
|
439
|
+
// 最近一次上报的会话 id(来自对话输入框的专家入口),只存内存,不落盘、不含任何凭证。
|
|
440
|
+
let composerSession = { id: '', at: 0 }
|
|
441
|
+
/** 界面自检上报的最后一帧(内存里,用于排障;不落盘、无凭证)。 */
|
|
442
|
+
let uiMetrics = null
|
|
443
|
+
const RECORD_CACHE_MS = 60_000
|
|
444
|
+
|
|
445
|
+
/** 读一张表的原始记录(60 秒内存缓存,可 fresh 强制刷新)。 */
|
|
446
|
+
/**
|
|
447
|
+
* lark-cli 的 `--output` 只认三个根:当前工作目录、账号临时目录、home 下的 files。
|
|
448
|
+
* 写到 DSH 数据目录会被判为 "unsafe output path"(退出码 2),所以这里统一落临时目录,
|
|
449
|
+
* 读完立刻删。文件名带随机后缀,避免同一张表并发读时互相覆盖。
|
|
450
|
+
*/
|
|
451
|
+
function larkOutputFile(tableId, label = 'records') {
|
|
452
|
+
const safe = String(tableId).replace(/[^\w.-]/g, '_') || label
|
|
453
|
+
const rand = Math.random().toString(36).slice(2, 8)
|
|
454
|
+
return join(tmpdir(), `dsh-rdw-pull-${safe}-${Date.now().toString(36)}-${rand}.ndjson`)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** 从 lark-cli 的 stderr/stdout 里摘一小段人话,用于报错。 */
|
|
458
|
+
function larkSnippet(result) {
|
|
459
|
+
return String(result?.stderr || result?.stdout || '').trim().slice(0, 400)
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 删掉一次 ndjson 拉取留下的全部文件:本体 + lark-cli 伴生的 .manifest.json。 */
|
|
463
|
+
async function cleanupLarkOutput(outFile) {
|
|
464
|
+
const manifest = String(outFile).replace(/\.ndjson$/, '.manifest.json')
|
|
465
|
+
await rm(outFile, { force: true }).catch(() => {})
|
|
466
|
+
if (manifest !== outFile) await rm(manifest, { force: true }).catch(() => {})
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* 读一张表的记录:ndjson 优先,只有 ndjson **真的坏了** 才退回值矩阵。
|
|
471
|
+
*
|
|
472
|
+
* 关键区分(v3.7.1 修正):ndjson 正常退出、文件也写出来了,只是 0 条记录 —— 那多半是
|
|
473
|
+
* 这张表本来就是空的,不该报「通道不可用」。所以此时再用值矩阵交叉确认一次:
|
|
474
|
+
* 值矩阵也 0 条 → 安静地按空表显示;值矩阵有数据 → 用值矩阵并说明原因。
|
|
475
|
+
* 返回 { records, fetchMode, warning, ndjsonError, failure },failure 非空表示读失败要报错。
|
|
476
|
+
*/
|
|
477
|
+
async function readRecordsWithFallback({ wrapper, common, outFile, limit = 2000, matrixReader, command = '' }) {
|
|
478
|
+
const ndjson = await runLark(wrapper, [...common, '--limit', String(limit), '--format', 'ndjson', '--output', outFile, '--overwrite'])
|
|
479
|
+
// 退出码不可全信:.cmd 包装下 lark-cli 会以非 0 退出,但 ndjson 文件其实写好了。以文件里的记录为准。
|
|
480
|
+
const ndjsonText = await readFile(outFile, 'utf8').catch(() => null)
|
|
481
|
+
// lark-cli 除了 ndjson 还会写一个伴生的 .manifest.json,两个都要清掉,别在临时目录留垃圾。
|
|
482
|
+
await cleanupLarkOutput(outFile)
|
|
483
|
+
const records = ndjsonText === null ? [] : parseLarkRecords(ndjsonText)
|
|
484
|
+
let ndjsonError = ''
|
|
485
|
+
if (ndjsonText === null) ndjsonError = `lark-cli 没写出 ndjson 文件(退出码 ${ndjson.code ?? '?'}):${larkSnippet(ndjson)}`
|
|
486
|
+
else if (!ndjson.ok) ndjsonError = `lark-cli 退出码 ${ndjson.code ?? '?'}:${larkSnippet(ndjson)}`
|
|
487
|
+
if (records.length) {
|
|
488
|
+
return {
|
|
489
|
+
records,
|
|
490
|
+
fetchMode: 'ndjson',
|
|
491
|
+
warning: ndjson.ok ? '' : `lark-cli 退出码 ${ndjson.code ?? '?'},但 ndjson 里已有 ${records.length} 条记录,按记录显示。`,
|
|
492
|
+
ndjsonError,
|
|
493
|
+
failure: null,
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
// ndjson 一条都没有:用值矩阵交叉确认「表是空的」还是「通道坏了」。
|
|
497
|
+
const json = await runLark(wrapper, [...common, '--limit', '200', '--format', 'json'])
|
|
498
|
+
if (!json.ok) {
|
|
499
|
+
if (ndjsonError) {
|
|
500
|
+
return { records: [], fetchMode: 'ndjson', warning: '', ndjsonError, failure: { error: '读取飞书多维表格失败', detail: (json.stderr || json.stdout || ndjsonError).trim().slice(0, 1500), command } }
|
|
501
|
+
}
|
|
502
|
+
return { records: [], fetchMode: 'ndjson', warning: `值矩阵通道这次没读到(${larkSnippet(json) || '无输出'}),本次按 0 条显示。`, ndjsonError, failure: null }
|
|
503
|
+
}
|
|
504
|
+
const matrix = await matrixReader(json.stdout)
|
|
505
|
+
if (!matrix.aligned) {
|
|
506
|
+
// 值矩阵没法对齐字段:宁可报错,也不能显示串了位的字段。
|
|
507
|
+
if (ndjsonError) {
|
|
508
|
+
return { records: [], fetchMode: 'ndjson', warning: '', ndjsonError, failure: { error: '这张表读到的列和字段名对不上,已停下不展示(避免显示错的字段)', detail: `${matrix.reason};ndjson 通道失败原因:${ndjsonError}`, command } }
|
|
509
|
+
}
|
|
510
|
+
return { records: [], fetchMode: 'ndjson', warning: '', ndjsonError, failure: null }
|
|
511
|
+
}
|
|
512
|
+
if (!matrix.records.length) {
|
|
513
|
+
// 两个通道都读到 0 条:这张表就是空的(不是通道坏),安静显示。
|
|
514
|
+
return { records: [], fetchMode: 'ndjson', warning: '', ndjsonError: '', failure: null }
|
|
515
|
+
}
|
|
516
|
+
return {
|
|
517
|
+
records: matrix.records,
|
|
518
|
+
fetchMode: 'json',
|
|
519
|
+
warning: `ndjson 通道没解析到记录,已用值矩阵读到 ${matrix.records.length} 条(${matrix.reason})。${ndjsonError ? `ndjson 失败原因:${ndjsonError.slice(0, 200)}` : ''}`,
|
|
520
|
+
ndjsonError,
|
|
521
|
+
failure: null,
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function fetchTableRecords(config, table, { fresh = false, limit = 2000 } = {}) {
|
|
526
|
+
const cacheId = `${config.root}|${table.key}`
|
|
527
|
+
const hit = recordCache.get(cacheId)
|
|
528
|
+
if (!fresh && hit && Date.now() - hit.at < RECORD_CACHE_MS) return hit.payload
|
|
529
|
+
const larkCli = await resolveLarkCli(config.larkCli)
|
|
530
|
+
const wrapper = shellWrapper(larkCli)
|
|
531
|
+
const common = ['base', '+record-list', '--base-token', table.baseToken, '--table-id', table.tableId, '--as', table.identity]
|
|
532
|
+
if (table.viewId) common.push('--view-id', table.viewId)
|
|
533
|
+
const read = await readRecordsWithFallback({
|
|
534
|
+
wrapper,
|
|
535
|
+
common,
|
|
536
|
+
outFile: larkOutputFile(table.tableId, 'records'),
|
|
537
|
+
limit,
|
|
538
|
+
command: `lark-cli base +record-list --base-token ${table.baseToken} --table-id ${table.tableId} --as ${table.identity} --format ndjson`,
|
|
539
|
+
matrixReader: (stdout) => matrixToRecords(wrapper, table, stdout),
|
|
540
|
+
})
|
|
541
|
+
if (read.failure) {
|
|
542
|
+
return { ok: false, records: [], error: read.failure.error, detail: read.failure.detail, command: read.failure.command }
|
|
543
|
+
}
|
|
544
|
+
const payload = { ok: true, records: read.records, fetchMode: read.fetchMode, warning: read.warning, ndjsonError: read.ndjsonError, at: Date.now() }
|
|
545
|
+
recordCache.set(cacheId, { at: Date.now(), payload })
|
|
546
|
+
return payload
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** 任意一张表的记录 -> 统一结构(标题/状态/负责人等按该表的字段映射取)。 */
|
|
550
|
+
export function normalizeTableRecord(record, fieldMap) {
|
|
551
|
+
const fields = record?.fields && typeof record.fields === 'object' ? record.fields : record ?? {}
|
|
552
|
+
const names = Object.keys(fields)
|
|
553
|
+
const mapped = (logical) => {
|
|
554
|
+
const actual = fieldMap?.[logical]
|
|
555
|
+
return actual && actual in fields ? toPlain(fields[actual]) : ''
|
|
556
|
+
}
|
|
557
|
+
const title = mapped('title') || toPlain(fields[pickField(fields, '', ['需求标题', '任务标题', '标题', '名称', 'title', 'name'])]) || toPlain(fields[names[0]]) || '(无标题记录)'
|
|
558
|
+
return {
|
|
559
|
+
id: String(record?.record_id ?? record?.recordId ?? ''),
|
|
560
|
+
title,
|
|
561
|
+
status: mapped('status') || toPlain(fields[pickField(fields, '', ['状态', 'status', '进度'])]),
|
|
562
|
+
owner: mapped('owner') || toPlain(fields[pickField(fields, '', ['负责人', '指派', 'owner', 'assignee', '处理人'])]),
|
|
563
|
+
reviewer: mapped('reviewer'),
|
|
564
|
+
priority: mapped('priority'),
|
|
565
|
+
type: mapped('type'),
|
|
566
|
+
module: mapped('module'),
|
|
567
|
+
code: mapped('id'),
|
|
568
|
+
requirementId: mapped('requirementId'),
|
|
569
|
+
branch: mapped('branch'),
|
|
570
|
+
mrLink: mapped('mrLink'),
|
|
571
|
+
evidence: mapped('evidence'),
|
|
572
|
+
estimate: mapped('estimate'),
|
|
573
|
+
fieldNames: names,
|
|
574
|
+
fields: Object.fromEntries(names.map((key) => [key, toPlain(fields[key])])),
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const PROGRESS_DONE = ['已完成', '通过', '已验收', '已合并', 'done', 'closed']
|
|
579
|
+
const PROGRESS_ACTIVE = ['开发中', '联调中', '评审中', '进行中', '已领取', 'in progress']
|
|
580
|
+
|
|
581
|
+
/** 按某个字段统计一张表的进度分布。 */
|
|
582
|
+
export function summarizeProgress(items, field) {
|
|
583
|
+
const buckets = new Map()
|
|
584
|
+
for (const item of items) {
|
|
585
|
+
const value = String(item.fields?.[field] ?? '').trim() || '(未填写)'
|
|
586
|
+
buckets.set(value, (buckets.get(value) ?? 0) + 1)
|
|
587
|
+
}
|
|
588
|
+
const list = [...buckets.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count)
|
|
589
|
+
const sumOf = (words) =>
|
|
590
|
+
list.filter((entry) => words.some((word) => entry.value.toLowerCase().includes(word.toLowerCase()))).reduce((sum, entry) => sum + entry.count, 0)
|
|
591
|
+
const done = sumOf(PROGRESS_DONE)
|
|
592
|
+
const active = sumOf(PROGRESS_ACTIVE)
|
|
593
|
+
const total = items.length
|
|
594
|
+
return { field, total, buckets: list, done, active, todo: Math.max(0, total - done - active), percent: total ? Math.round((done / total) * 100) : 0 }
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** 跨表总览:每张表的总数、按状态字段的进度分布、几条样例。 */
|
|
598
|
+
async function buildOverview(config, settings, { fresh = false } = {}) {
|
|
599
|
+
const { tables, dropped } = await listTables(config, settings)
|
|
600
|
+
const out = []
|
|
601
|
+
for (const table of tables) {
|
|
602
|
+
const payload = await fetchTableRecords(config, table, { fresh })
|
|
603
|
+
if (!payload.ok) {
|
|
604
|
+
out.push({ key: table.key, label: table.label, kind: table.kind, tableName: table.tableName, error: payload.error, detail: payload.detail })
|
|
605
|
+
continue
|
|
606
|
+
}
|
|
607
|
+
const items = payload.records.map((record) => normalizeTableRecord(record, table.fieldMap))
|
|
608
|
+
const field = table.fieldMap?.status || pickField(items[0]?.fields ?? {}, '', ['状态', 'status', '进度'])
|
|
609
|
+
out.push({
|
|
610
|
+
key: table.key,
|
|
611
|
+
label: table.label,
|
|
612
|
+
kind: table.kind,
|
|
613
|
+
tableName: table.tableName,
|
|
614
|
+
configPath: table.configPath,
|
|
615
|
+
total: items.length,
|
|
616
|
+
fetchMode: payload.fetchMode,
|
|
617
|
+
warning: payload.warning,
|
|
618
|
+
progress: field ? summarizeProgress(items, field) : null,
|
|
619
|
+
sample: items.slice(0, 4).map((item) => ({ id: item.id, title: item.title, status: item.status, owner: item.owner })),
|
|
620
|
+
})
|
|
621
|
+
}
|
|
622
|
+
return { tables: out, dropped, generatedAt: new Date().toISOString() }
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/* ------------------------------------------- 工作台自己的执行记录(runs) */
|
|
626
|
+
|
|
627
|
+
function runsFile(config) {
|
|
628
|
+
return join(config.root, 'runs.jsonl')
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* 一条执行记录属于哪个任务:优先「表 + 记录 id」,没有 id 时退到标题。
|
|
633
|
+
* 「同一个任务只留一条记录」全靠这个键 —— 重复生成开发指令时更新这一条,而不是再加一条。
|
|
634
|
+
*/
|
|
635
|
+
export function runTaskKey(run) {
|
|
636
|
+
const recordId = String(run?.recordId ?? '').trim()
|
|
637
|
+
if (recordId) return `${String(run?.tableKey ?? '').trim()}|${recordId}`
|
|
638
|
+
const title = String(run?.title ?? '').trim()
|
|
639
|
+
if (title) return `title|${title}`
|
|
640
|
+
return `id|${String(run?.id ?? '').trim()}`
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** 事件流 -> 最新状态(每个任务一条,附历史与「生成过几次」)。 */
|
|
644
|
+
export function foldRuns(events) {
|
|
645
|
+
const map = new Map()
|
|
646
|
+
for (const event of events) {
|
|
647
|
+
if (!event || typeof event !== 'object') continue
|
|
648
|
+
if (event.type === 'create') {
|
|
649
|
+
const status = event.status || 'handed-off'
|
|
650
|
+
map.set(event.id, { ...event, status, generated: Number(event.generated ?? 1), history: [{ at: event.at, status, note: event.note ?? '' }] })
|
|
651
|
+
continue
|
|
652
|
+
}
|
|
653
|
+
if (event.type === 'regenerate' && map.has(event.id)) {
|
|
654
|
+
// 同一条任务又生成了一次:刷新时间/项目/备注,保留用户已经标好的状态,只把次数 +1。
|
|
655
|
+
const run = map.get(event.id)
|
|
656
|
+
run.at = event.at ?? run.at
|
|
657
|
+
if (event.title) run.title = event.title
|
|
658
|
+
if (event.projectDir !== undefined) run.projectDir = event.projectDir
|
|
659
|
+
if (event.note) run.note = event.note
|
|
660
|
+
run.generated = Number(run.generated ?? 1) + 1
|
|
661
|
+
run.history = [...(run.history ?? []), { at: event.at, status: run.status, note: event.note || '再次生成开发指令' }]
|
|
662
|
+
continue
|
|
663
|
+
}
|
|
664
|
+
if (event.type === 'update' && map.has(event.id)) {
|
|
665
|
+
const run = map.get(event.id)
|
|
666
|
+
run.status = event.status || run.status
|
|
667
|
+
if (event.note !== undefined) run.note = event.note
|
|
668
|
+
run.updatedAt = event.at
|
|
669
|
+
run.history = [...(run.history ?? []), { at: event.at, status: run.status, note: event.note ?? '' }]
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
// 老记录里同一条任务可能已经被点出好几条:这里按任务键合并,取最近的一条当代表,
|
|
673
|
+
// 历史合并、次数累加,状态以「最近一次显式改动」为准 —— 于是总览里一个任务只有一条。
|
|
674
|
+
const byTask = new Map()
|
|
675
|
+
for (const run of [...map.values()].sort((a, b) => String(a.at).localeCompare(String(b.at)))) {
|
|
676
|
+
const key = runTaskKey(run)
|
|
677
|
+
const hit = byTask.get(key)
|
|
678
|
+
if (!hit) {
|
|
679
|
+
byTask.set(key, { ...run, generated: Number(run.generated ?? 1) })
|
|
680
|
+
continue
|
|
681
|
+
}
|
|
682
|
+
const rank = (item) => String(item.updatedAt ?? item.at ?? '')
|
|
683
|
+
const newer = String(run.at ?? '') >= String(hit.at ?? '') ? run : hit
|
|
684
|
+
const older = newer === run ? hit : run
|
|
685
|
+
const statusSource = rank(newer) >= rank(older) ? newer : older
|
|
686
|
+
byTask.set(key, {
|
|
687
|
+
...newer,
|
|
688
|
+
status: statusSource.status ?? newer.status,
|
|
689
|
+
note: (rank(newer) >= rank(older) ? newer.note : older.note) ?? newer.note ?? '',
|
|
690
|
+
generated: Number(older.generated ?? 1) + Number(newer.generated ?? 1),
|
|
691
|
+
history: [...(older.history ?? []), ...(newer.history ?? [])].sort((a, b) => String(a.at).localeCompare(String(b.at))),
|
|
692
|
+
mergedIds: [...new Set([...(older.mergedIds ?? [older.id]), ...(newer.mergedIds ?? [newer.id])])],
|
|
693
|
+
})
|
|
694
|
+
}
|
|
695
|
+
return [...byTask.values()].sort((a, b) => String(b.at).localeCompare(String(a.at)))
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async function readRuns(config) {
|
|
699
|
+
const text = await readFile(runsFile(config), 'utf8').catch(() => '')
|
|
700
|
+
const events = text
|
|
701
|
+
.split(/\r?\n/)
|
|
702
|
+
.filter(Boolean)
|
|
703
|
+
.map((line) => {
|
|
704
|
+
try {
|
|
705
|
+
return JSON.parse(line)
|
|
706
|
+
} catch {
|
|
707
|
+
return null
|
|
708
|
+
}
|
|
709
|
+
})
|
|
710
|
+
.filter(Boolean)
|
|
711
|
+
return foldRuns(events)
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
async function appendRun(config, event) {
|
|
715
|
+
await mkdir(dirname(runsFile(config)), { recursive: true })
|
|
716
|
+
await appendFile(runsFile(config), `${JSON.stringify(event)}\n`, 'utf8')
|
|
717
|
+
return event
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/* ------------------------------------------------------------- 飞书需求 */
|
|
721
|
+
|
|
722
|
+
/** 从粘贴的飞书链接里抽出 base_token(/base/<token>)、table_id 与 view_id。 */
|
|
723
|
+
export function parseBaseInput(input) {
|
|
724
|
+
const text = String(input ?? '').trim()
|
|
725
|
+
if (!text) return { baseToken: '', tableId: '', viewId: '' }
|
|
726
|
+
if (/^https?:/i.test(text)) {
|
|
727
|
+
const base = /\/base\/([A-Za-z0-9]+)/.exec(text)
|
|
728
|
+
const table = /[?&]table=([^&#]+)/.exec(text)
|
|
729
|
+
const view = /[?&]view=([^&#]+)/.exec(text)
|
|
730
|
+
return {
|
|
731
|
+
baseToken: base ? base[1] : '',
|
|
732
|
+
tableId: table ? decodeURIComponent(table[1]) : '',
|
|
733
|
+
viewId: view ? decodeURIComponent(view[1]) : '',
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const parts = text.split(/[\s,|]+/).filter(Boolean)
|
|
737
|
+
return { baseToken: parts[0] ?? '', tableId: parts[1] ?? '', viewId: '' }
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function pickField(fields, explicit, hints) {
|
|
741
|
+
if (explicit && explicit in fields) return explicit
|
|
742
|
+
const names = Object.keys(fields)
|
|
743
|
+
for (const hint of hints) {
|
|
744
|
+
const hit = names.find((fieldName) => fieldName.toLowerCase().includes(hint.toLowerCase()))
|
|
745
|
+
if (hit) return hit
|
|
746
|
+
}
|
|
747
|
+
return ''
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function toPlain(value) {
|
|
751
|
+
if (value === null || value === undefined) return ''
|
|
752
|
+
if (typeof value === 'string') return value
|
|
753
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
|
|
754
|
+
if (Array.isArray(value)) return value.map(toPlain).filter(Boolean).join('、')
|
|
755
|
+
if (typeof value === 'object') {
|
|
756
|
+
for (const key of ['text', 'name', 'value', 'link', 'en_name']) {
|
|
757
|
+
if (key in value) return toPlain(value[key])
|
|
758
|
+
}
|
|
759
|
+
if ('file_token' in value) return '[附件]'
|
|
760
|
+
try {
|
|
761
|
+
return JSON.stringify(value)
|
|
762
|
+
} catch {
|
|
763
|
+
return String(value)
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
return String(value)
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** ndjson 里的一行可能就是一个裸记录对象(带 record_id),先认出来,别当成容器继续往下找。 */
|
|
770
|
+
function looksLikeRecord(value) {
|
|
771
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value) && ('record_id' in value || 'recordId' in value)
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
export function extractRecords(payload) {
|
|
775
|
+
if (Array.isArray(payload)) return payload
|
|
776
|
+
if (!payload || typeof payload !== 'object') return []
|
|
777
|
+
if (looksLikeRecord(payload)) return [payload]
|
|
778
|
+
for (const key of ['items', 'records', 'data']) {
|
|
779
|
+
const value = payload[key]
|
|
780
|
+
if (Array.isArray(value)) return value
|
|
781
|
+
if (value && typeof value === 'object') {
|
|
782
|
+
const nested = extractRecords(value)
|
|
783
|
+
if (nested.length) return nested
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return []
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
export function parseLarkRecords(stdout) {
|
|
790
|
+
const text = stdout.trim()
|
|
791
|
+
if (!text) return []
|
|
792
|
+
try {
|
|
793
|
+
return extractRecords(JSON.parse(text))
|
|
794
|
+
} catch {
|
|
795
|
+
/* 不是整段 JSON,按 ndjson 逐行解析 */
|
|
796
|
+
}
|
|
797
|
+
const rows = []
|
|
798
|
+
for (const line of text.split(/\r?\n/)) {
|
|
799
|
+
const trimmed = line.trim()
|
|
800
|
+
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) continue
|
|
801
|
+
try {
|
|
802
|
+
rows.push(...extractRecords(JSON.parse(trimmed)))
|
|
803
|
+
} catch {
|
|
804
|
+
/* 跳过无法解析的行 */
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
return rows
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
export function normalizeRecord(record, settings, fieldMap) {
|
|
811
|
+
const fields = record?.fields && typeof record.fields === 'object' ? record.fields : record ?? {}
|
|
812
|
+
const names = Object.keys(fields)
|
|
813
|
+
const mapped = (logical) => {
|
|
814
|
+
const actual = fieldMap?.[logical]
|
|
815
|
+
return actual && actual in fields ? toPlain(fields[actual]) : ''
|
|
816
|
+
}
|
|
817
|
+
const titleKey = pickField(fields, settings?.titleField, ['需求标题', '标题', '名称', 'title', 'name'])
|
|
818
|
+
const statusKey = pickField(fields, settings?.statusField, ['状态', 'status', '进度'])
|
|
819
|
+
const projectKey = pickField(fields, settings?.projectField, ['所属项目', '项目', '仓库', 'project', 'repo'])
|
|
820
|
+
const ownerKey = pickField(fields, settings?.ownerField, ['负责人', '指派', 'owner', 'assignee', '处理人'])
|
|
821
|
+
const title = mapped('title') || toPlain(fields[titleKey]) || toPlain(fields[names[0]]) || '(无标题记录)'
|
|
822
|
+
return {
|
|
823
|
+
id: String(record?.record_id ?? record?.recordId ?? record?.id ?? mapped('id') ?? ''),
|
|
824
|
+
title,
|
|
825
|
+
status: mapped('status') || toPlain(fields[statusKey]),
|
|
826
|
+
project: mapped('project') || toPlain(fields[projectKey]),
|
|
827
|
+
owner: mapped('owner') || toPlain(fields[ownerKey]),
|
|
828
|
+
code: mapped('id'),
|
|
829
|
+
rawRequirement: mapped('rawRequirement'),
|
|
830
|
+
design: mapped('design'),
|
|
831
|
+
designLink: mapped('designLink'),
|
|
832
|
+
devSupplement: mapped('devSupplement'),
|
|
833
|
+
acceptance: mapped('acceptance'),
|
|
834
|
+
priority: mapped('priority'),
|
|
835
|
+
type: mapped('type'),
|
|
836
|
+
prompt: mapped('prompt'),
|
|
837
|
+
fieldNames: names,
|
|
838
|
+
fields: Object.fromEntries(names.map((key) => [key, toPlain(fields[key])])),
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/* ---------------------------------------------- 需求源(复用项目内配置) */
|
|
843
|
+
|
|
844
|
+
const SOURCE_CONFIG_FILES = ['.requirement-sources.json', join('doc', 'requirement-sources.json')]
|
|
845
|
+
|
|
846
|
+
/** 读项目里已有的需求源配置(就是 feishu-requirement-intake 用的那一份)。 */
|
|
847
|
+
export async function loadRequirementSources(projectDir) {
|
|
848
|
+
if (!projectDir) return null
|
|
849
|
+
for (const rel of SOURCE_CONFIG_FILES) {
|
|
850
|
+
const file = join(projectDir, rel)
|
|
851
|
+
const text = await readFile(file, 'utf8').catch(() => null)
|
|
852
|
+
if (text === null) continue
|
|
853
|
+
let parsed
|
|
854
|
+
try {
|
|
855
|
+
parsed = JSON.parse(text)
|
|
856
|
+
} catch {
|
|
857
|
+
continue
|
|
858
|
+
}
|
|
859
|
+
const raw = parsed?.sources && typeof parsed.sources === 'object' ? parsed.sources : {}
|
|
860
|
+
const names = Object.keys(raw)
|
|
861
|
+
if (!names.length) continue
|
|
862
|
+
return {
|
|
863
|
+
path: file,
|
|
864
|
+
defaultSource: parsed.defaultSource && raw[parsed.defaultSource] ? parsed.defaultSource : names[0],
|
|
865
|
+
sources: names.map((name) => ({ name, ...raw[name] })),
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
return null
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/** 决定这次读哪张表:优先项目里已有的需求源配置,其次工作台设置里手填的。 */
|
|
872
|
+
export async function resolveRequirementsSource(config, settings) {
|
|
873
|
+
const detected = await loadRequirementSources(settings.projectDir)
|
|
874
|
+
const wanted = settings.sourceName || detected?.defaultSource || ''
|
|
875
|
+
const chosen = detected?.sources?.find((source) => source.name === wanted) ?? null
|
|
876
|
+
const fromUrl = parseBaseInput(chosen?.baseUrl ?? '')
|
|
877
|
+
const baseToken = fromUrl.baseToken || settings.baseToken
|
|
878
|
+
const tableId = fromUrl.tableId || settings.tableId || chosen?.tableName || ''
|
|
879
|
+
return {
|
|
880
|
+
label: chosen ? chosen.name : '手动填写',
|
|
881
|
+
sourceName: chosen ? chosen.name : '',
|
|
882
|
+
configPath: detected?.path ?? '',
|
|
883
|
+
baseToken,
|
|
884
|
+
tableId,
|
|
885
|
+
viewId: fromUrl.viewId || chosen?.viewId || settings.viewId,
|
|
886
|
+
fieldMap: chosen?.fields ?? null,
|
|
887
|
+
filter: chosen?.filter ?? null,
|
|
888
|
+
identity: chosen?.identity || config.identity || 'user',
|
|
889
|
+
configured: Boolean(baseToken && tableId),
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
function publicSource(source) {
|
|
894
|
+
return {
|
|
895
|
+
label: source.label,
|
|
896
|
+
sourceName: source.sourceName,
|
|
897
|
+
configPath: source.configPath,
|
|
898
|
+
tableId: source.tableId,
|
|
899
|
+
viewId: source.viewId,
|
|
900
|
+
identity: source.identity,
|
|
901
|
+
filter: source.filter,
|
|
902
|
+
fieldMap: source.fieldMap,
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/** json matrix(值矩阵)兜底:列名取自 +field-list,列数不一致就不猜。 */
|
|
907
|
+
/**
|
|
908
|
+
* 值矩阵的列顺序不一定等于 +field-list 的顺序(真机上就遇到过整体错位)。
|
|
909
|
+
* 用字段类型/选项值做校验:能唯一对上就用纠正后的顺序,对不上就明确报错,绝不猜着显示。
|
|
910
|
+
*/
|
|
911
|
+
export function alignMatrixColumns(rows, schema) {
|
|
912
|
+
const width = Array.isArray(rows?.[0]) ? rows[0].length : 0
|
|
913
|
+
if (!schema?.length || !width) return { names: [], aligned: false, reason: '没有可用的字段清单' }
|
|
914
|
+
if (schema.length !== width) return { names: [], aligned: false, reason: `列数不一致(字段 ${schema.length} / 数据 ${width})` }
|
|
915
|
+
const byName = new Map(schema.map((field) => [field.name, field]))
|
|
916
|
+
const optionSet = (field) => new Set((field?.options ?? []).map(String))
|
|
917
|
+
const partsOf = (value) => {
|
|
918
|
+
if (value === null || value === undefined || value === '') return []
|
|
919
|
+
const list = Array.isArray(value) ? value : [value]
|
|
920
|
+
return list.flatMap((item) => String(item).split(/[,,]/)).map((item) => item.trim()).filter(Boolean)
|
|
921
|
+
}
|
|
922
|
+
/** 某字段放在第 index 列时的违规数:选项字段的值必须落在它的选项里。 */
|
|
923
|
+
const violations = (field, index) => {
|
|
924
|
+
const options = optionSet(field)
|
|
925
|
+
if (!options.size) return 0
|
|
926
|
+
let bad = 0
|
|
927
|
+
for (const row of rows) {
|
|
928
|
+
const parts = partsOf(row[index])
|
|
929
|
+
if (parts.some((part) => !options.has(part))) bad += 1
|
|
930
|
+
}
|
|
931
|
+
return bad
|
|
932
|
+
}
|
|
933
|
+
const scoreOf = (names) => names.reduce((sum, name, index) => sum + violations(byName.get(name), index), 0)
|
|
934
|
+
const natural = schema.map((field) => field.name)
|
|
935
|
+
const naturalScore = scoreOf(natural)
|
|
936
|
+
if (naturalScore === 0) return { names: natural, aligned: true, reason: '列顺序与字段清单一致' }
|
|
937
|
+
|
|
938
|
+
// 用「有选项的字段」去认列:能唯一装下它的列就钉住,其余字段按原顺序补空位。
|
|
939
|
+
const pinned = new Map()
|
|
940
|
+
const pinnedFields = new Set()
|
|
941
|
+
for (const field of schema.filter((item) => (item.options ?? []).length)) {
|
|
942
|
+
const matches = []
|
|
943
|
+
for (let index = 0; index < width; index += 1) {
|
|
944
|
+
if (pinned.has(index) || violations(field, index) !== 0) continue
|
|
945
|
+
const filled = rows.some((row) => partsOf(row[index]).length)
|
|
946
|
+
if (filled) matches.push(index)
|
|
947
|
+
}
|
|
948
|
+
if (matches.length === 1) {
|
|
949
|
+
pinned.set(matches[0], field.name)
|
|
950
|
+
pinnedFields.add(field.name)
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
const rest = natural.filter((name) => !pinnedFields.has(name))
|
|
954
|
+
const candidate = []
|
|
955
|
+
for (let index = 0; index < width; index += 1) candidate.push(pinned.get(index) ?? rest.shift() ?? '')
|
|
956
|
+
const candidateScore = scoreOf(candidate)
|
|
957
|
+
if (candidate.length === width && candidate.every(Boolean) && candidateScore === 0) {
|
|
958
|
+
return { names: candidate, aligned: true, reason: `按选项值纠正了列顺序(原违规 ${naturalScore} 处,纠正后 0 处)` }
|
|
959
|
+
}
|
|
960
|
+
return { names: [], aligned: false, reason: `列顺序对不上字段清单(违规 ${naturalScore} 处,自动纠正后仍有 ${candidateScore} 处)` }
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/** 值矩阵自带字段名与记录 id:`data.fields` / `data.record_id_list` 与列一一对应,是权威顺序。 */
|
|
964
|
+
export function matrixShape(parsed) {
|
|
965
|
+
const rows = parsed?.data?.data
|
|
966
|
+
if (!Array.isArray(rows) || !rows.length || rows.every((row) => !Array.isArray(row))) return null
|
|
967
|
+
const names = Array.isArray(parsed?.data?.fields)
|
|
968
|
+
? parsed.data.fields.map((field) => (typeof field === 'string' ? field : String(field?.name ?? '')))
|
|
969
|
+
: []
|
|
970
|
+
const recordIds = Array.isArray(parsed?.data?.record_id_list) ? parsed.data.record_id_list.map(String) : []
|
|
971
|
+
return { rows, names, recordIds }
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/** 值矩阵 + 字段名 -> 记录;列数与字段名对不上就返回空(宁可不显示,也不能串字段)。 */
|
|
975
|
+
export function recordsFromMatrix(rows, names, recordIds = []) {
|
|
976
|
+
const width = Array.isArray(rows?.[0]) ? rows[0].length : -1
|
|
977
|
+
if (!rows?.length || !names?.length || names.length !== width || names.some((name) => !name)) return []
|
|
978
|
+
return rows.map((row, index) => ({
|
|
979
|
+
record_id: recordIds[index] ?? '',
|
|
980
|
+
fields: Object.fromEntries(names.map((name, column) => [name, row[column] ?? ''])),
|
|
981
|
+
}))
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/** 值矩阵 + 字段清单 -> 记录;对不上就返回空并带上原因(宁可不显示,也不能串字段)。 */
|
|
985
|
+
async function matrixToRecords(wrapper, source, stdout) {
|
|
986
|
+
let parsed
|
|
987
|
+
try {
|
|
988
|
+
parsed = JSON.parse(stdout)
|
|
989
|
+
} catch {
|
|
990
|
+
return { records: [], aligned: false, reason: '返回内容不是 JSON' }
|
|
991
|
+
}
|
|
992
|
+
const shape = matrixShape(parsed)
|
|
993
|
+
if (!shape) return { records: extractRecords(parsed), aligned: true, reason: '按对象形式解析' }
|
|
994
|
+
const { rows, names, recordIds } = shape
|
|
995
|
+
// 首选返回体自带的字段名:它和列严格一一对应。
|
|
996
|
+
const inline = recordsFromMatrix(rows, names, recordIds)
|
|
997
|
+
if (inline.length) return { records: inline, aligned: true, reason: `按返回体自带的 ${names.length} 个字段名对齐` }
|
|
998
|
+
|
|
999
|
+
// 没有自带字段名时,才退回 +field-list 并用选项值校正列顺序。
|
|
1000
|
+
const listed = await runLark(wrapper, [
|
|
1001
|
+
'base',
|
|
1002
|
+
'+field-list',
|
|
1003
|
+
'--base-token',
|
|
1004
|
+
source.baseToken,
|
|
1005
|
+
'--table-id',
|
|
1006
|
+
source.tableId,
|
|
1007
|
+
'--as',
|
|
1008
|
+
source.identity,
|
|
1009
|
+
'--format',
|
|
1010
|
+
'json',
|
|
1011
|
+
])
|
|
1012
|
+
const schema = parseFieldSchema(listed.stdout)
|
|
1013
|
+
const alignment = alignMatrixColumns(rows, schema)
|
|
1014
|
+
if (!alignment.aligned) return { records: [], aligned: false, reason: alignment.reason }
|
|
1015
|
+
return { records: recordsFromMatrix(rows, alignment.names, recordIds), aligned: true, reason: alignment.reason }
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function describeRead(source) {
|
|
1019
|
+
return `lark-cli base +record-list --base-token ${source.baseToken} --table-id ${source.tableId} --as ${source.identity}`
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/** 给前端用的表信息(不含 token)。 */
|
|
1023
|
+
function publicTable(table) {
|
|
1024
|
+
return {
|
|
1025
|
+
key: table.key,
|
|
1026
|
+
label: table.label,
|
|
1027
|
+
kind: table.kind,
|
|
1028
|
+
sourceName: table.sourceName,
|
|
1029
|
+
tableName: table.tableName,
|
|
1030
|
+
tableId: table.tableId,
|
|
1031
|
+
identity: table.identity,
|
|
1032
|
+
configPath: table.configPath,
|
|
1033
|
+
filter: table.filter,
|
|
1034
|
+
fieldMap: table.fieldMap,
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
async function fetchRequirements(config, settings) {
|
|
1039
|
+
const source = await resolveRequirementsSource(config, settings)
|
|
1040
|
+
const described = publicSource(source)
|
|
1041
|
+
if (!source.configured) {
|
|
1042
|
+
return { configured: false, items: [], source: described, message: '还没有配置飞书多维表格(可以选项目里已有的需求源,或手动粘贴链接)' }
|
|
1043
|
+
}
|
|
1044
|
+
const larkCli = await resolveLarkCli(config.larkCli)
|
|
1045
|
+
const wrapper = shellWrapper(larkCli)
|
|
1046
|
+
const common = [
|
|
1047
|
+
'base',
|
|
1048
|
+
'+record-list',
|
|
1049
|
+
'--base-token',
|
|
1050
|
+
source.baseToken,
|
|
1051
|
+
'--table-id',
|
|
1052
|
+
source.tableId,
|
|
1053
|
+
'--as',
|
|
1054
|
+
source.identity,
|
|
1055
|
+
]
|
|
1056
|
+
if (source.viewId) common.push('--view-id', source.viewId)
|
|
1057
|
+
|
|
1058
|
+
const read = await readRecordsWithFallback({
|
|
1059
|
+
wrapper,
|
|
1060
|
+
common,
|
|
1061
|
+
outFile: larkOutputFile(source.tableId, 'source-records'),
|
|
1062
|
+
limit: 2000,
|
|
1063
|
+
command: `${describeRead(source)} --format ndjson`,
|
|
1064
|
+
matrixReader: (stdout) => matrixToRecords(wrapper, source, stdout),
|
|
1065
|
+
})
|
|
1066
|
+
if (read.failure) {
|
|
1067
|
+
return { configured: true, items: [], source: described, error: read.failure.error, detail: read.failure.detail, command: read.failure.command }
|
|
1068
|
+
}
|
|
1069
|
+
const { records, fetchMode, warning } = read
|
|
1070
|
+
|
|
1071
|
+
const items = records.map((record) => normalizeRecord(record, settings, source.fieldMap))
|
|
1072
|
+
return { configured: true, items, count: items.length, source: described, fetchMode, warning }
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** 单元格值的写法按字段类型来(单选/多选要数组,勾选是布尔,数字不加引号)。 */
|
|
1076
|
+
export function cellValueFor(value, fieldType = '') {
|
|
1077
|
+
const type = String(fieldType ?? '').toLowerCase()
|
|
1078
|
+
if (value === null || value === undefined || value === '') return null
|
|
1079
|
+
if (type.includes('checkbox') || type.includes('check')) return value === true || value === 'true' || value === '是'
|
|
1080
|
+
if (type.includes('number') || type.includes('currency') || type.includes('percent') || type.includes('rating') || type === 'num') {
|
|
1081
|
+
const number = Number(value)
|
|
1082
|
+
return Number.isFinite(number) ? number : String(value)
|
|
1083
|
+
}
|
|
1084
|
+
if (type.includes('select')) return Array.isArray(value) ? value : [value]
|
|
1085
|
+
return Array.isArray(value) ? value : String(value)
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/** 回写用 +record-batch-update:一次一条记录一个字段。 */
|
|
1089
|
+
export function buildBatchUpdatePayload(recordId, field, value, fieldType) {
|
|
1090
|
+
return { update_records: { [String(recordId)]: { [String(field)]: cellValueFor(value, fieldType) } } }
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
async function updateRequirementStatus(config, settings, body) {
|
|
1094
|
+
const source = await resolveRequirementsSource(config, settings)
|
|
1095
|
+
if (!source.configured) return { ok: false, error: '还未配置飞书多维表格' }
|
|
1096
|
+
const recordId = String(body?.recordId ?? '').trim()
|
|
1097
|
+
const status = String(body?.status ?? '').trim()
|
|
1098
|
+
if (!recordId || !status) return { ok: false, error: '缺少记录 ID 或状态值' }
|
|
1099
|
+
const statusField = String(body?.field ?? '').trim() || settings.statusField || source.fieldMap?.status || '状态'
|
|
1100
|
+
const fieldType = String(body?.fieldType ?? '').trim() || (await cachedFieldType(config, source.tableId, statusField))
|
|
1101
|
+
const payload = buildBatchUpdatePayload(recordId, statusField, status, fieldType)
|
|
1102
|
+
const larkCli = await resolveLarkCli(config.larkCli)
|
|
1103
|
+
const wrapper = shellWrapper(larkCli)
|
|
1104
|
+
// 带引号的 JSON 经过 cmd.exe / PowerShell 包装会被再解释一遍,所以走 --json @文件;
|
|
1105
|
+
// lark-cli 只允许读当前目录、系统临时目录或 ~/files 下的文件。
|
|
1106
|
+
const payloadFile = join(tmpdir(), `dsh-rdw-write-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`)
|
|
1107
|
+
await writeFile(payloadFile, JSON.stringify(payload), 'utf8')
|
|
1108
|
+
const args = [
|
|
1109
|
+
'base',
|
|
1110
|
+
'+record-batch-update',
|
|
1111
|
+
'--base-token',
|
|
1112
|
+
source.baseToken,
|
|
1113
|
+
'--table-id',
|
|
1114
|
+
source.tableId,
|
|
1115
|
+
'--json',
|
|
1116
|
+
`@${payloadFile}`,
|
|
1117
|
+
'--as',
|
|
1118
|
+
source.identity,
|
|
1119
|
+
]
|
|
1120
|
+
if (body?.dryRun) args.push('--dry-run')
|
|
1121
|
+
const result = await runLark(wrapper, args)
|
|
1122
|
+
await rm(payloadFile, { force: true }).catch(() => {})
|
|
1123
|
+
if (!result.ok) {
|
|
1124
|
+
return {
|
|
1125
|
+
ok: false,
|
|
1126
|
+
error: '回写飞书失败',
|
|
1127
|
+
detail: (result.stderr || result.stdout || '').trim().slice(0, 1500),
|
|
1128
|
+
command: `lark-cli base +record-batch-update --base-token ${source.baseToken} --table-id ${source.tableId} --json '${JSON.stringify(payload)}' --as ${source.identity}`,
|
|
1129
|
+
hint: '本机 lark-cli 写回用 +record-batch-update;字段名与选项值必须和表里完全一致。',
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
return { ok: true, field: statusField, status, payload, dryRun: Boolean(body?.dryRun), result: (result.stdout || '').trim().slice(0, 400) }
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/** 从缓存的字段清单里查某个字段的类型(拿不到就返回空,值按字符串写)。 */
|
|
1136
|
+
async function cachedFieldType(config, tableId, fieldName) {
|
|
1137
|
+
try {
|
|
1138
|
+
const text = await readFile(fieldSchemaFile(config, tableId), 'utf8')
|
|
1139
|
+
const fields = parseFieldSchema(text)
|
|
1140
|
+
return fields.find((field) => field.name === fieldName)?.type ?? ''
|
|
1141
|
+
} catch {
|
|
1142
|
+
return ''
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/* --------------------------------------------------------- 表结构(字段) */
|
|
1147
|
+
|
|
1148
|
+
const FIELD_SCHEMA_TTL_MS = 10 * 60 * 1000
|
|
1149
|
+
|
|
1150
|
+
function fieldSchemaFile(config, tableId) {
|
|
1151
|
+
return join(config.root, `fields-${String(tableId).replace(/[^\w.-]/g, '_') || 'table'}.json`)
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/** +field-list 的返回 -> 精简的字段清单(名称/类型/选项值)。 */
|
|
1155
|
+
export function parseFieldSchema(stdout) {
|
|
1156
|
+
let parsed
|
|
1157
|
+
try {
|
|
1158
|
+
parsed = JSON.parse(stdout)
|
|
1159
|
+
} catch {
|
|
1160
|
+
return []
|
|
1161
|
+
}
|
|
1162
|
+
const list = parsed?.data?.fields
|
|
1163
|
+
if (!Array.isArray(list)) return []
|
|
1164
|
+
return list
|
|
1165
|
+
.map((field) => ({
|
|
1166
|
+
name: String(field?.name ?? ''),
|
|
1167
|
+
type: String(field?.type ?? ''),
|
|
1168
|
+
options: Array.isArray(field?.options) ? field.options.map((option) => String(option?.name ?? '')).filter(Boolean) : [],
|
|
1169
|
+
}))
|
|
1170
|
+
.filter((field) => field.name)
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
async function fetchFieldSchema(config, settings, explicitTable) {
|
|
1174
|
+
const source = explicitTable ?? (await resolveRequirementsSource(config, settings))
|
|
1175
|
+
if (!source.configured && !explicitTable) {
|
|
1176
|
+
return { configured: false, fields: [], source: described, message: '还没有配置飞书多维表格' }
|
|
1177
|
+
}
|
|
1178
|
+
const described = explicitTable ? publicTable(explicitTable) : publicSource(source)
|
|
1179
|
+
const cacheFile = fieldSchemaFile(config, source.tableId)
|
|
1180
|
+
const cached = await readFile(cacheFile, 'utf8')
|
|
1181
|
+
.then((text) => JSON.parse(text))
|
|
1182
|
+
.catch(() => null)
|
|
1183
|
+
if (cached && Array.isArray(cached.fields) && Date.now() - Number(cached.cachedAt ?? 0) < FIELD_SCHEMA_TTL_MS) {
|
|
1184
|
+
return { configured: true, fields: cached.fields, source: described, cachedAt: cached.cachedAt, fromCache: true }
|
|
1185
|
+
}
|
|
1186
|
+
const larkCli = await resolveLarkCli(config.larkCli)
|
|
1187
|
+
const wrapper = shellWrapper(larkCli)
|
|
1188
|
+
const result = await runLark(wrapper, [
|
|
1189
|
+
'base',
|
|
1190
|
+
'+field-list',
|
|
1191
|
+
'--base-token',
|
|
1192
|
+
source.baseToken,
|
|
1193
|
+
'--table-id',
|
|
1194
|
+
source.tableId,
|
|
1195
|
+
'--as',
|
|
1196
|
+
source.identity,
|
|
1197
|
+
'--format',
|
|
1198
|
+
'json',
|
|
1199
|
+
])
|
|
1200
|
+
const fields = result.ok ? parseFieldSchema(result.stdout) : []
|
|
1201
|
+
if (!fields.length) {
|
|
1202
|
+
if (cached?.fields?.length) {
|
|
1203
|
+
return { configured: true, fields: cached.fields, source: described, cachedAt: cached.cachedAt, fromCache: true, warning: '读表结构失败,用的是上次缓存' }
|
|
1204
|
+
}
|
|
1205
|
+
return {
|
|
1206
|
+
configured: true,
|
|
1207
|
+
fields: [],
|
|
1208
|
+
source: described,
|
|
1209
|
+
error: '读取表结构失败',
|
|
1210
|
+
detail: (result.stderr || result.stdout || '').trim().slice(0, 1000),
|
|
1211
|
+
command: `lark-cli base +field-list --base-token ${source.baseToken} --table-id ${source.tableId} --as ${source.identity}`,
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const cachedAt = Date.now()
|
|
1215
|
+
await mkdir(dirname(cacheFile), { recursive: true })
|
|
1216
|
+
await writeFile(cacheFile, `${JSON.stringify({ tableId: source.tableId, cachedAt, fields }, null, 2)}\n`, 'utf8')
|
|
1217
|
+
return { configured: true, fields, source: described, cachedAt }
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/* ------------------------------------------------------------ 技能/规范 */
|
|
1221
|
+
|
|
1222
|
+
function isInside(child, parent) {
|
|
1223
|
+
const rel = relative(resolve(parent), resolve(child))
|
|
1224
|
+
return rel === '' || (!rel.startsWith('..') && !rel.startsWith(`..${sep}`))
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/* ------------------------------------------------------------ 目录浏览 */
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* 「选择项目目录」的兜底实现。
|
|
1231
|
+
*
|
|
1232
|
+
* 社区版 DSH Desktop 有 uiWorkspace.pickDirectory(),官方 DeepSeek Harness 没有 ——
|
|
1233
|
+
* 那里点按钮只会得到一句「当前宿主没有提供目录选择器」。所以工作台自带一份只读目录浏览:
|
|
1234
|
+
* 客户端弹自己的选择器,服务端只回目录(不回文件内容),任何宿主都能用。
|
|
1235
|
+
*/
|
|
1236
|
+
|
|
1237
|
+
/** 本机可浏览的根:Windows 枚举真实存在的盘符,其他系统就是 /。 */
|
|
1238
|
+
function directoryRoots() {
|
|
1239
|
+
if (process.platform === 'win32') {
|
|
1240
|
+
const roots = []
|
|
1241
|
+
for (const letter of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
|
|
1242
|
+
const path = `${letter}:\\`
|
|
1243
|
+
try {
|
|
1244
|
+
if (existsSync(path)) roots.push({ name: `${letter}:`, path })
|
|
1245
|
+
} catch {
|
|
1246
|
+
/* 空光驱 / 断开的网络盘,跳过 */
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return roots
|
|
1250
|
+
}
|
|
1251
|
+
return [{ name: '/', path: '/' }]
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
async function listDirectories(target) {
|
|
1255
|
+
const roots = directoryRoots()
|
|
1256
|
+
const home = homedir()
|
|
1257
|
+
const raw = String(target ?? '').trim()
|
|
1258
|
+
if (!raw) return { ok: true, path: '', parent: '', roots, home, entries: [] }
|
|
1259
|
+
const resolved = resolve(raw)
|
|
1260
|
+
let info
|
|
1261
|
+
try {
|
|
1262
|
+
info = await stat(resolved)
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
return { ok: false, path: raw, parent: '', roots, home, entries: [], error: `打不开这个目录:${error?.code ?? error?.message ?? error}` }
|
|
1265
|
+
}
|
|
1266
|
+
if (!info.isDirectory()) {
|
|
1267
|
+
return { ok: false, path: resolved, parent: '', roots, home, entries: [], error: '这是一个文件,不是目录' }
|
|
1268
|
+
}
|
|
1269
|
+
let listing
|
|
1270
|
+
try {
|
|
1271
|
+
listing = await readdir(resolved, { withFileTypes: true })
|
|
1272
|
+
} catch (error) {
|
|
1273
|
+
return { ok: false, path: resolved, parent: '', roots, home, entries: [], error: `读取目录失败:${error?.code ?? error?.message ?? error}` }
|
|
1274
|
+
}
|
|
1275
|
+
const entries = []
|
|
1276
|
+
for (const dirent of listing) {
|
|
1277
|
+
if (entries.length >= 800) break
|
|
1278
|
+
let isDirectory = dirent.isDirectory()
|
|
1279
|
+
if (!isDirectory && dirent.isSymbolicLink()) {
|
|
1280
|
+
try {
|
|
1281
|
+
isDirectory = (await stat(join(resolved, dirent.name))).isDirectory()
|
|
1282
|
+
} catch {
|
|
1283
|
+
isDirectory = false
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
if (!isDirectory) continue
|
|
1287
|
+
entries.push({ name: dirent.name, path: join(resolved, dirent.name) })
|
|
1288
|
+
}
|
|
1289
|
+
entries.sort((left, right) => left.name.localeCompare(right.name, 'zh-Hans-CN', { numeric: true, sensitivity: 'base' }))
|
|
1290
|
+
const parent = dirname(resolved) === resolved ? '' : dirname(resolved)
|
|
1291
|
+
return { ok: true, path: resolved, parent, roots, home, entries }
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
function parseFrontmatter(text) {
|
|
1295
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
|
|
1296
|
+
if (!match) return {}
|
|
1297
|
+
const out = {}
|
|
1298
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
1299
|
+
const pair = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line)
|
|
1300
|
+
if (!pair) continue
|
|
1301
|
+
let value = pair[2].trim()
|
|
1302
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
1303
|
+
value = value.slice(1, -1)
|
|
1304
|
+
}
|
|
1305
|
+
if (value && value !== '>' && value !== '|') out[pair[1]] = value
|
|
1306
|
+
}
|
|
1307
|
+
return out
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
/** 角色/专家定义:<目录>/agents/<id>.md(WorkBuddy 的专家也是这一种文件)。 */
|
|
1311
|
+
async function collectExpertsInRoot(root, items) {
|
|
1312
|
+
const agentsDir = join(dirname(root.path), 'agents')
|
|
1313
|
+
const agentEntries = await readdir(agentsDir, { withFileTypes: true }).catch(() => [])
|
|
1314
|
+
for (const entry of agentEntries) {
|
|
1315
|
+
if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) continue
|
|
1316
|
+
const file = join(agentsDir, entry.name)
|
|
1317
|
+
const text = await readFile(file, 'utf8').catch(() => null)
|
|
1318
|
+
if (text === null) continue
|
|
1319
|
+
const front = parseFrontmatter(text)
|
|
1320
|
+
const id = entry.name.replace(/\.md$/i, '')
|
|
1321
|
+
items.push({
|
|
1322
|
+
kind: 'agent',
|
|
1323
|
+
scope: root.scope,
|
|
1324
|
+
convention: root.convention,
|
|
1325
|
+
rootPath: agentsDir,
|
|
1326
|
+
group: `${root.label} · 角色/规范`,
|
|
1327
|
+
id: `agent:${id}`,
|
|
1328
|
+
agentId: id,
|
|
1329
|
+
name: front.name || id,
|
|
1330
|
+
dirName: id,
|
|
1331
|
+
displayName: front.displayName || '',
|
|
1332
|
+
profession: front.profession || '',
|
|
1333
|
+
description: front.description || '',
|
|
1334
|
+
maxTurns: front.maxTurns ? Number(front.maxTurns) || 0 : 0,
|
|
1335
|
+
tags: front.tags ? String(front.tags).split(/[,,]/).map((tag) => tag.trim()).filter(Boolean) : [],
|
|
1336
|
+
path: file,
|
|
1337
|
+
chars: text.length,
|
|
1338
|
+
})
|
|
1339
|
+
}
|
|
1340
|
+
return agentsDir
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/** 技能目录:技能本体 + 同名目录下的角色/专家文件(.claude/agents/*.md 这类)。 */
|
|
1344
|
+
async function collectSkillsInRoot(root, items) {
|
|
1345
|
+
const entries = await readdir(root.path, { withFileTypes: true }).catch(() => [])
|
|
1346
|
+
for (const entry of entries) {
|
|
1347
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) continue
|
|
1348
|
+
const file = join(root.path, entry.name, 'SKILL.md')
|
|
1349
|
+
const text = await readFile(file, 'utf8').catch(() => null)
|
|
1350
|
+
if (text === null) continue
|
|
1351
|
+
const front = parseFrontmatter(text)
|
|
1352
|
+
items.push({
|
|
1353
|
+
kind: 'skill',
|
|
1354
|
+
scope: root.scope,
|
|
1355
|
+
convention: root.convention,
|
|
1356
|
+
rootPath: root.path,
|
|
1357
|
+
group: root.label,
|
|
1358
|
+
id: `${root.label}:${entry.name}`,
|
|
1359
|
+
name: front.name || entry.name,
|
|
1360
|
+
dirName: entry.name,
|
|
1361
|
+
description: front.description || '',
|
|
1362
|
+
path: file,
|
|
1363
|
+
chars: text.length,
|
|
1364
|
+
})
|
|
1365
|
+
}
|
|
1366
|
+
await collectExpertsInRoot(root, items)
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
/** DeepSeek Harness 通用技能根(跨项目可用);没有就返回空。 */
|
|
1370
|
+
function harnessSkillDir() {
|
|
1371
|
+
const dshHome = process.env.DSH_HOME
|
|
1372
|
+
return dshHome ? join(dshHome, 'skills') : ''
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/** 技能名统一成 kebab-case,顺带挡掉路径穿越。 */
|
|
1376
|
+
export function slugifySkillName(value) {
|
|
1377
|
+
return String(value ?? '')
|
|
1378
|
+
.trim()
|
|
1379
|
+
.toLowerCase()
|
|
1380
|
+
.replace(/[\s_]+/g, '-')
|
|
1381
|
+
.replace(/[^a-z0-9-]/g, '')
|
|
1382
|
+
.replace(/-{2,}/g, '-')
|
|
1383
|
+
.replace(/^-+|-+$/g, '')
|
|
1384
|
+
.slice(0, 48)
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
/** 生成一份能直接被 DSH 识别的 SKILL.md(frontmatter + 正文)。 */
|
|
1388
|
+
export function renderSkillMarkdown({ name, description, whenToUse = '', steps = [], notes = [] }) {
|
|
1389
|
+
const lines = ['---', `name: ${name}`, `description: ${String(description).replace(/\s+/g, ' ').trim()}`, '---', '', `# ${name}`, '']
|
|
1390
|
+
lines.push('## 什么时候用', '', whenToUse || String(description).trim() || '(补一句:什么场景下该用这个技能)', '')
|
|
1391
|
+
lines.push('## 怎么做', '')
|
|
1392
|
+
const stepLines = (steps ?? []).map((line) => String(line).trim()).filter(Boolean)
|
|
1393
|
+
if (stepLines.length) for (const [index, line] of stepLines.entries()) lines.push(`${index + 1}. ${line}`)
|
|
1394
|
+
else lines.push('1. (写下这个技能的固定步骤)')
|
|
1395
|
+
lines.push('', '## 注意', '')
|
|
1396
|
+
const noteLines = (notes ?? []).map((line) => String(line).trim()).filter(Boolean)
|
|
1397
|
+
if (noteLines.length) for (const line of noteLines) lines.push(`- ${line}`)
|
|
1398
|
+
else lines.push('- (写下易错点/红线)')
|
|
1399
|
+
return `${lines.join('\n')}\n`
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** 新建技能:默认写进 DeepSeek Harness 通用技能根,也可以写进当前项目的 .claude/skills。 */
|
|
1403
|
+
async function createSkill(config, settings, body) {
|
|
1404
|
+
const name = slugifySkillName(body?.name)
|
|
1405
|
+
if (!name) return { ok: false, error: '技能名称请用小写字母、数字和连字符(例如 java-code-review)' }
|
|
1406
|
+
const description = String(body?.description ?? '').trim()
|
|
1407
|
+
if (!description) return { ok: false, error: '请写一句技能描述(AI 靠它判断什么时候用这个技能)' }
|
|
1408
|
+
const scope = body?.scope === 'project' ? 'project' : 'harness'
|
|
1409
|
+
let dir = ''
|
|
1410
|
+
if (scope === 'project') {
|
|
1411
|
+
const projectDir = String(settings.projectDir ?? '').trim()
|
|
1412
|
+
if (!projectDir) return { ok: false, error: '还没选项目目录,先选一个再创建项目内技能' }
|
|
1413
|
+
dir = join(projectDir, '.claude', 'skills', name)
|
|
1414
|
+
} else {
|
|
1415
|
+
const root = harnessSkillDir()
|
|
1416
|
+
if (!root) return { ok: false, error: '取不到 DSH_HOME,定位不到 DeepSeek Harness 技能目录' }
|
|
1417
|
+
dir = join(root, name)
|
|
1418
|
+
}
|
|
1419
|
+
const file = join(dir, 'SKILL.md')
|
|
1420
|
+
if (existsSync(file) && !body?.overwrite) {
|
|
1421
|
+
return { ok: false, error: `技能「${name}」已存在,换个名字或先删掉它`, path: file, exists: true }
|
|
1422
|
+
}
|
|
1423
|
+
const text = renderSkillMarkdown({
|
|
1424
|
+
name,
|
|
1425
|
+
description,
|
|
1426
|
+
whenToUse: String(body?.whenToUse ?? '').trim(),
|
|
1427
|
+
steps: String(body?.steps ?? '').split('\n'),
|
|
1428
|
+
notes: String(body?.notes ?? '').split('\n'),
|
|
1429
|
+
})
|
|
1430
|
+
try {
|
|
1431
|
+
await mkdir(dir, { recursive: true })
|
|
1432
|
+
await writeFile(file, text, 'utf8')
|
|
1433
|
+
} catch (error) {
|
|
1434
|
+
return { ok: false, error: `写技能文件失败:${String(error?.message ?? error)}`, path: file }
|
|
1435
|
+
}
|
|
1436
|
+
return { ok: true, name, scope, path: file, dir, chars: text.length, overwrote: Boolean(body?.overwrite) }
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
async function collectDocs(projectDir, items) {
|
|
1440
|
+
if (!projectDir) return
|
|
1441
|
+
const standardsDir = join(projectDir, 'doc', 'standards')
|
|
1442
|
+
const entries = await readdir(standardsDir, { withFileTypes: true }).catch(() => [])
|
|
1443
|
+
for (const entry of entries) {
|
|
1444
|
+
if (!entry.isFile() || !entry.name.toLowerCase().endsWith('.md')) continue
|
|
1445
|
+
items.push({ id: `doc:${entry.name}`, name: entry.name.replace(/\.md$/i, ''), path: join(standardsDir, entry.name) })
|
|
1446
|
+
}
|
|
1447
|
+
for (const name of ['AGENTS.md', 'CLAUDE.md']) {
|
|
1448
|
+
const file = join(projectDir, name)
|
|
1449
|
+
const text = await readFile(file, 'utf8').catch(() => null)
|
|
1450
|
+
if (text !== null) items.push({ id: `doc:${name}`, name, path: file })
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/** 项目内的技能目录约定:与 DSH 技能管理器的项目来源一致,另加 .agent / .code 两个别名。 */
|
|
1455
|
+
const SKILL_CONVENTIONS = [
|
|
1456
|
+
{ dir: '.dsh', label: '.dsh(本项目专用)' },
|
|
1457
|
+
{ dir: '.agents', label: '.agents' },
|
|
1458
|
+
{ dir: '.agent', label: '.agent' },
|
|
1459
|
+
{ dir: '.claude', label: '.claude' },
|
|
1460
|
+
{ dir: '.codex', label: '.codex' },
|
|
1461
|
+
{ dir: '.code', label: '.code' },
|
|
1462
|
+
{ dir: '.cursor', label: '.cursor' },
|
|
1463
|
+
{ dir: '.gemini', label: '.gemini' },
|
|
1464
|
+
{ dir: '.github', label: '.github' },
|
|
1465
|
+
{ dir: '.opencode', label: '.opencode' },
|
|
1466
|
+
{ dir: '', label: 'skills' },
|
|
1467
|
+
]
|
|
1468
|
+
|
|
1469
|
+
/** 用户级(全局)技能目录:环境变量可以改根,和 DSH 技能管理器保持一致。 */
|
|
1470
|
+
function globalSkillDirs() {
|
|
1471
|
+
const home = process.env.USERPROFILE || process.env.HOME || ''
|
|
1472
|
+
if (!home) return []
|
|
1473
|
+
const pick = (envName, fallback) => process.env[envName] || join(home, fallback)
|
|
1474
|
+
return [
|
|
1475
|
+
{ convention: '.agents', label: '全局 skill · .agents(公共 Agent)', path: join(pick('DSH_AGENTS_HOME', '.agents'), 'skills') },
|
|
1476
|
+
{ convention: '.claude', label: '全局 skill · .claude(Claude)', path: join(pick('DSH_CLAUDE_HOME', '.claude'), 'skills') },
|
|
1477
|
+
{ convention: '.codex', label: '全局 skill · .codex(Codex)', path: join(pick('DSH_CODEX_HOME', '.codex'), 'skills') },
|
|
1478
|
+
{ convention: '.gemini', label: '全局 skill · .gemini(Gemini)', path: join(pick('DSH_GEMINI_HOME', '.gemini'), 'skills') },
|
|
1479
|
+
{ convention: '.cursor', label: '全局 skill · .cursor', path: join(home, '.cursor', 'skills') },
|
|
1480
|
+
{ convention: '.cc-switch', label: '全局 skill · .cc-switch', path: join(home, '.cc-switch', 'skills') },
|
|
1481
|
+
{ convention: '.opencode', label: '全局 skill · .opencode', path: join(home, '.opencode', 'skills') },
|
|
1482
|
+
{ convention: 'skills', label: '全局 skill · 用户 skills 目录', path: join(home, 'skills') },
|
|
1483
|
+
]
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
function skillRootsFor(config, settings) {
|
|
1487
|
+
const roots = []
|
|
1488
|
+
const push = (scope, convention, label, path, note = '') => {
|
|
1489
|
+
if (!path) return
|
|
1490
|
+
const key = resolve(path).toLowerCase()
|
|
1491
|
+
if (roots.some((root) => resolve(root.path).toLowerCase() === key)) return
|
|
1492
|
+
roots.push({ scope, convention, label, path, note, exists: existsSync(path) })
|
|
1493
|
+
}
|
|
1494
|
+
// 1) DeepSeek Harness 自己的技能根:跨项目通用,也是「新建技能」默认写入的位置
|
|
1495
|
+
const harness = harnessSkillDir()
|
|
1496
|
+
if (harness) push('harness', '', 'DeepSeek Harness · 通用技能', harness, 'DSH 全局技能根,任何项目都能用')
|
|
1497
|
+
// 2) 全局(用户级)约定目录
|
|
1498
|
+
for (const entry of globalSkillDirs()) push('global', entry.convention, entry.label, entry.path)
|
|
1499
|
+
// 3) 项目内约定目录
|
|
1500
|
+
const projectDir = settings.projectDir
|
|
1501
|
+
if (projectDir) {
|
|
1502
|
+
for (const convention of SKILL_CONVENTIONS) {
|
|
1503
|
+
const path = convention.dir ? join(projectDir, convention.dir, 'skills') : join(projectDir, 'skills')
|
|
1504
|
+
push('project', convention.dir || 'skills', `项目 skill · ${convention.label}`, path)
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
// 4) 自定义目录(主机配置或工作台设置里加的)
|
|
1508
|
+
for (const extra of config.skillsRoots ?? []) push('custom', '', '自定义 skill', extra)
|
|
1509
|
+
for (const extra of settings.skillsRoots ?? []) push('custom', '', '自定义 skill', extra)
|
|
1510
|
+
return roots
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
async function listSkills(config, settings) {
|
|
1514
|
+
const roots = skillRootsFor(config, settings)
|
|
1515
|
+
const items = []
|
|
1516
|
+
for (const root of roots) {
|
|
1517
|
+
if (!root.exists) continue
|
|
1518
|
+
await collectSkillsInRoot(root, items)
|
|
1519
|
+
}
|
|
1520
|
+
const docs = []
|
|
1521
|
+
await collectDocs(settings.projectDir, docs)
|
|
1522
|
+
const summary = {}
|
|
1523
|
+
for (const scope of ['harness', 'global', 'project', 'custom']) summary[scope] = { scope, roots: 0, exists: 0, skills: 0, agents: 0 }
|
|
1524
|
+
for (const root of roots) {
|
|
1525
|
+
const bucket = summary[root.scope]
|
|
1526
|
+
if (!bucket) continue
|
|
1527
|
+
bucket.roots += 1
|
|
1528
|
+
if (root.exists) bucket.exists += 1
|
|
1529
|
+
}
|
|
1530
|
+
for (const item of items) {
|
|
1531
|
+
const bucket = summary[item.scope]
|
|
1532
|
+
if (!bucket) continue
|
|
1533
|
+
if (item.kind === 'agent') bucket.agents += 1
|
|
1534
|
+
else bucket.skills += 1
|
|
1535
|
+
}
|
|
1536
|
+
return {
|
|
1537
|
+
roots,
|
|
1538
|
+
items,
|
|
1539
|
+
docs,
|
|
1540
|
+
projectDir: settings.projectDir,
|
|
1541
|
+
harnessSkillDir: harnessSkillDir(),
|
|
1542
|
+
summary: Object.values(summary),
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
async function readSkillFile(config, settings, target) {
|
|
1547
|
+
const wanted = String(target ?? '').trim()
|
|
1548
|
+
if (!wanted) return { ok: false, error: '缺少文件路径' }
|
|
1549
|
+
const listing = await listSkills(config, settings)
|
|
1550
|
+
const allowed = [
|
|
1551
|
+
...listing.items.map((item) => item.path),
|
|
1552
|
+
...listing.docs.map((item) => item.path),
|
|
1553
|
+
]
|
|
1554
|
+
const hit = allowed.find((path) => resolve(path) === resolve(wanted))
|
|
1555
|
+
if (!hit) return { ok: false, error: '该路径不在本工作台可读的技能/规范范围内' }
|
|
1556
|
+
const text = await readFile(hit, 'utf8').catch(() => null)
|
|
1557
|
+
if (text === null) return { ok: false, error: '文件读不到' }
|
|
1558
|
+
return { ok: true, path: hit, text }
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
/* -------------------------------------------- 专家 / 专家团(参考 WorkBuddy) */
|
|
1562
|
+
|
|
1563
|
+
/** 专家文件放哪:通用 = DSH_HOME/agents;项目 = <项目>/<约定>/agents(默认 .claude)。 */
|
|
1564
|
+
function expertDirFor(scope, convention, settings) {
|
|
1565
|
+
if (scope === 'project') {
|
|
1566
|
+
const projectDir = String(settings.projectDir ?? '').trim()
|
|
1567
|
+
if (!projectDir) return ''
|
|
1568
|
+
const safe = SKILL_CONVENTIONS.some((entry) => entry.dir && entry.dir === convention) ? convention : '.claude'
|
|
1569
|
+
return join(projectDir, safe, 'agents')
|
|
1570
|
+
}
|
|
1571
|
+
return process.env.DSH_HOME ? join(process.env.DSH_HOME, 'agents') : ''
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
function expertTargets(config, settings) {
|
|
1575
|
+
return {
|
|
1576
|
+
harness: { dir: expertDirFor('harness', '', settings), label: 'DeepSeek Harness 通用专家(所有项目可用)' },
|
|
1577
|
+
project: { dir: expertDirFor('project', '.claude', settings), label: '当前项目专家(写进 <.claude>/agents)' },
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
/** 专家团清单文件:通用放 DSH_HOME/experts,项目放 <项目>/.dsh/experts。 */
|
|
1582
|
+
function teamFiles(config, settings) {
|
|
1583
|
+
const projectDir = String(settings.projectDir ?? '').trim()
|
|
1584
|
+
const list = []
|
|
1585
|
+
if (process.env.DSH_HOME) list.push({ scope: 'harness', path: join(process.env.DSH_HOME, 'experts', 'teams.json'), label: 'DeepSeek Harness 通用专家团' })
|
|
1586
|
+
if (projectDir) list.push({ scope: 'project', path: join(projectDir, '.dsh', 'experts', 'teams.json'), label: '当前项目专家团' })
|
|
1587
|
+
return list
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
async function readTeamFile(file) {
|
|
1591
|
+
const raw = await readFile(file.path, 'utf8').catch(() => null)
|
|
1592
|
+
if (!raw) return []
|
|
1593
|
+
try {
|
|
1594
|
+
const parsed = JSON.parse(raw)
|
|
1595
|
+
const teams = Array.isArray(parsed?.teams) ? parsed.teams : []
|
|
1596
|
+
return teams
|
|
1597
|
+
.filter((team) => team && typeof team.id === 'string' && team.id)
|
|
1598
|
+
.map((team) => ({
|
|
1599
|
+
kind: 'team',
|
|
1600
|
+
scope: file.scope,
|
|
1601
|
+
path: file.path,
|
|
1602
|
+
id: String(team.id),
|
|
1603
|
+
name: String(team.name || team.id),
|
|
1604
|
+
profession: String(team.profession || ''),
|
|
1605
|
+
description: String(team.description || ''),
|
|
1606
|
+
lead: String(team.lead || ''),
|
|
1607
|
+
members: Array.isArray(team.members) ? team.members.map(String) : [],
|
|
1608
|
+
flow: Array.isArray(team.flow) ? team.flow.map(String) : [],
|
|
1609
|
+
createdAt: String(team.createdAt || ''),
|
|
1610
|
+
}))
|
|
1611
|
+
} catch {
|
|
1612
|
+
return []
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/** 专家作用域优先级:同名时以「当前项目」的为准(最贴近这个仓库的上下文)。 */
|
|
1617
|
+
const EXPERT_SCOPE_ORDER = { project: 0, harness: 1, global: 2, custom: 3 }
|
|
1618
|
+
|
|
1619
|
+
async function listExperts(config, settings) {
|
|
1620
|
+
const roots = skillRootsFor(config, settings)
|
|
1621
|
+
const found = []
|
|
1622
|
+
const agentDirs = []
|
|
1623
|
+
for (const root of roots) {
|
|
1624
|
+
// 技能目录可能还没建,但同级的 agents 目录里可能已经有专家:所以这里不看 root.exists
|
|
1625
|
+
const dir = await collectExpertsInRoot(root, found)
|
|
1626
|
+
if (dir) agentDirs.push({ scope: root.scope, convention: root.convention, label: root.label, path: dir, exists: existsSync(dir) })
|
|
1627
|
+
}
|
|
1628
|
+
// 同一个专家名字常在 .claude/agents 和 .agents/agents 各放一份:只留一份,其余位置记进 alsoIn
|
|
1629
|
+
const byId = new Map()
|
|
1630
|
+
const experts = []
|
|
1631
|
+
for (const expert of [...found].sort((a, b) => (EXPERT_SCOPE_ORDER[a.scope] ?? 9) - (EXPERT_SCOPE_ORDER[b.scope] ?? 9))) {
|
|
1632
|
+
const hit = byId.get(expert.agentId)
|
|
1633
|
+
if (hit) {
|
|
1634
|
+
hit.alsoIn = [...(hit.alsoIn ?? []), expert.path]
|
|
1635
|
+
continue
|
|
1636
|
+
}
|
|
1637
|
+
const copy = { ...expert }
|
|
1638
|
+
byId.set(expert.agentId, copy)
|
|
1639
|
+
experts.push(copy)
|
|
1640
|
+
}
|
|
1641
|
+
const teams = []
|
|
1642
|
+
for (const file of teamFiles(config, settings)) teams.push(...(await readTeamFile(file)))
|
|
1643
|
+
const summary = { harness: 0, global: 0, project: 0, custom: 0 }
|
|
1644
|
+
for (const expert of experts) if (expert.scope in summary) summary[expert.scope] += 1
|
|
1645
|
+
return {
|
|
1646
|
+
experts,
|
|
1647
|
+
teams,
|
|
1648
|
+
agentDirs,
|
|
1649
|
+
summary,
|
|
1650
|
+
duplicates: found.length - experts.length,
|
|
1651
|
+
selected: String(settings.expert ?? ''),
|
|
1652
|
+
targets: expertTargets(config, settings),
|
|
1653
|
+
// 「交给 AI 完善并创建」要把落盘位置原样告诉 agent,所以把专家团清单文件的绝对路径也带出去。
|
|
1654
|
+
teamFiles: teamFiles(config, settings),
|
|
1655
|
+
projectDir: settings.projectDir,
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
/** 生成一份专家角色定义(frontmatter 用扁平键,正文参考 WorkBuddy 的四段式)。 */
|
|
1660
|
+
export function renderExpertMarkdown({ id, name, displayName = '', profession = '', description, maxTurns = 0, abilities = [], flow = [], outputs = [], cautions = [] }) {
|
|
1661
|
+
const lines = ['---', `name: ${id}`, `description: ${String(description).replace(/\s+/g, ' ').trim()}`, `displayName: ${displayName || name || id}`, `profession: ${profession || name || id}`]
|
|
1662
|
+
if (Number(maxTurns) > 0) lines.push(`maxTurns: ${Number(maxTurns)}`)
|
|
1663
|
+
lines.push('---', '', `# ${displayName || name || id} · ${profession || name || id}`, '')
|
|
1664
|
+
lines.push(String(description).trim(), '')
|
|
1665
|
+
const section = (title, items, fallback) => {
|
|
1666
|
+
lines.push(`## ${title}`, '')
|
|
1667
|
+
const list = (items ?? []).map((line) => String(line).trim()).filter(Boolean)
|
|
1668
|
+
if (list.length) for (const [index, line] of list.entries()) lines.push(`${index + 1}. ${line}`)
|
|
1669
|
+
else lines.push(fallback)
|
|
1670
|
+
lines.push('')
|
|
1671
|
+
}
|
|
1672
|
+
section('核心能力', abilities, '1. (写下这个专家最擅长的几件事)')
|
|
1673
|
+
section('工作流程', flow, '1. (写下他接到需求后的固定步骤)')
|
|
1674
|
+
section('输出规范', outputs, '1. (写下他交付时要给什么:结构、字段、示例)')
|
|
1675
|
+
section('注意事项', cautions, '1. (写下他的红线与不越界的地方)')
|
|
1676
|
+
return `${lines.join('\n')}`
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
async function createExpert(config, settings, body) {
|
|
1680
|
+
const id = slugifySkillName(body?.id || body?.name)
|
|
1681
|
+
if (!id) return { ok: false, error: '专家标识请用小写字母、数字和连字符(例如 java-backend-expert)' }
|
|
1682
|
+
const description = String(body?.description ?? '').trim()
|
|
1683
|
+
if (!description) return { ok: false, error: '请写一句这个专家是干什么的(AI 靠它判断什么时候请他)' }
|
|
1684
|
+
const scope = body?.scope === 'project' ? 'project' : 'harness'
|
|
1685
|
+
const dir = expertDirFor(scope, String(body?.convention || '.claude'), settings)
|
|
1686
|
+
if (!dir) return { ok: false, error: scope === 'project' ? '还没选项目目录,选一个再创建项目专家' : '取不到 DSH_HOME,定位不到通用专家目录' }
|
|
1687
|
+
const convention = scope === 'project' ? String(body?.convention || '.claude') : ''
|
|
1688
|
+
const file = join(dir, `${id}.md`)
|
|
1689
|
+
if (existsSync(file) && !body?.overwrite) return { ok: false, error: `专家「${id}」已存在,换个标识或先删掉它`, path: file, exists: true }
|
|
1690
|
+
const text = renderExpertMarkdown({
|
|
1691
|
+
id,
|
|
1692
|
+
name: String(body?.name ?? '').trim(),
|
|
1693
|
+
displayName: String(body?.displayName ?? '').trim(),
|
|
1694
|
+
profession: String(body?.profession ?? '').trim(),
|
|
1695
|
+
description,
|
|
1696
|
+
maxTurns: Number(body?.maxTurns ?? 0) || 0,
|
|
1697
|
+
abilities: String(body?.abilities ?? '').split('\n'),
|
|
1698
|
+
flow: String(body?.flow ?? '').split('\n'),
|
|
1699
|
+
outputs: String(body?.outputs ?? '').split('\n'),
|
|
1700
|
+
cautions: String(body?.cautions ?? '').split('\n'),
|
|
1701
|
+
})
|
|
1702
|
+
try {
|
|
1703
|
+
await mkdir(dir, { recursive: true })
|
|
1704
|
+
await writeFile(file, text, 'utf8')
|
|
1705
|
+
} catch (error) {
|
|
1706
|
+
return { ok: false, error: `写专家文件失败:${String(error?.message ?? error)}`, path: file }
|
|
1707
|
+
}
|
|
1708
|
+
return { ok: true, kind: 'expert', id, scope, convention, path: file, chars: text.length, overwrote: Boolean(body?.overwrite) }
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
async function createTeam(config, settings, body) {
|
|
1712
|
+
const id = slugifySkillName(body?.id || body?.name)
|
|
1713
|
+
if (!id) return { ok: false, error: '专家团标识请用小写字母、数字和连字符(例如 hr-delivery-team)' }
|
|
1714
|
+
const name = String(body?.name ?? '').trim() || id
|
|
1715
|
+
const scope = body?.scope === 'project' ? 'project' : 'harness'
|
|
1716
|
+
const file = teamFiles(config, settings).find((entry) => entry.scope === scope)
|
|
1717
|
+
if (!file) return { ok: false, error: scope === 'project' ? '还没选项目目录,选一个再建项目专家团' : '取不到 DSH_HOME,定位不到通用专家团目录' }
|
|
1718
|
+
const listing = await listExperts(config, settings)
|
|
1719
|
+
const known = new Map(listing.experts.map((expert) => [expert.agentId, expert]))
|
|
1720
|
+
const members = [...new Set((Array.isArray(body?.members) ? body.members : []).map((value) => slugifySkillName(value)).filter(Boolean))]
|
|
1721
|
+
const missing = members.filter((member) => !known.has(member))
|
|
1722
|
+
if (missing.length) return { ok: false, error: `这些专家还没找到:${missing.join('、')}(先创建专家,或从列表里选)` }
|
|
1723
|
+
if (!members.length) return { ok: false, error: '专家团至少要有 1 名专家' }
|
|
1724
|
+
const lead = slugifySkillName(body?.lead) || members[0]
|
|
1725
|
+
if (!members.includes(lead)) members.unshift(lead)
|
|
1726
|
+
const existing = await readTeamFile(file)
|
|
1727
|
+
const team = {
|
|
1728
|
+
id,
|
|
1729
|
+
name,
|
|
1730
|
+
profession: String(body?.profession ?? '').trim(),
|
|
1731
|
+
description: String(body?.description ?? '').trim(),
|
|
1732
|
+
lead,
|
|
1733
|
+
members,
|
|
1734
|
+
flow: String(body?.flow ?? '').split('\n').map((line) => line.trim()).filter(Boolean),
|
|
1735
|
+
createdAt: new Date().toISOString(),
|
|
1736
|
+
}
|
|
1737
|
+
const kept = existing.filter((entry) => entry.id !== id)
|
|
1738
|
+
if (existing.some((entry) => entry.id === id) && !body?.overwrite) return { ok: false, error: `专家团「${id}」已存在,勾上覆盖再建`, path: file.path, exists: true }
|
|
1739
|
+
const payload = { version: 1, updatedAt: new Date().toISOString(), teams: [...kept.map(({ kind, scope: _s, path: _p, ...rest }) => rest), team] }
|
|
1740
|
+
try {
|
|
1741
|
+
await mkdir(dirname(file.path), { recursive: true })
|
|
1742
|
+
await writeFile(file.path, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
|
|
1743
|
+
} catch (error) {
|
|
1744
|
+
return { ok: false, error: `写专家团失败:${String(error?.message ?? error)}`, path: file.path }
|
|
1745
|
+
}
|
|
1746
|
+
return { ok: true, kind: 'team', id, scope, path: file.path, members, lead, overwrote: Boolean(body?.overwrite) }
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
/* ------------------------------------------------- 飞书文档(文档信息) */
|
|
1750
|
+
|
|
1751
|
+
/** 从粘贴的飞书链接/token 里认出文档坐标(/docx/、/docs/、/wiki/、/file/ 都收)。 */
|
|
1752
|
+
export function parseDocInput(input) {
|
|
1753
|
+
const text = String(input ?? '').trim()
|
|
1754
|
+
if (!text) return { doc: '', kind: '', url: '' }
|
|
1755
|
+
if (/^https?:/i.test(text)) {
|
|
1756
|
+
const hit = /\/(docx|docs|wiki|file)\/([A-Za-z0-9]+)/.exec(text)
|
|
1757
|
+
return { doc: hit ? hit[2] : '', kind: hit ? hit[1] : '', url: text }
|
|
1758
|
+
}
|
|
1759
|
+
const token = text.split(/[\s,|]+/).filter(Boolean)[0] ?? ''
|
|
1760
|
+
return { doc: /^[A-Za-z0-9_-]{6,}$/.test(token) ? token : '', kind: '', url: '' }
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
/**
|
|
1764
|
+
* `lark-cli docs +fetch` 的返回 -> { title, text }。
|
|
1765
|
+
* 成功:{ ok:true, data:{ document:{ document_id, revision_id, content, tips } } }
|
|
1766
|
+
* 失败:{ ok:false, error:{ type, subtype, code, message, hint } }(授权类的 JSON 走 stderr)
|
|
1767
|
+
*/
|
|
1768
|
+
export function parseDocPayload(stdout) {
|
|
1769
|
+
const raw = String(stdout ?? '').trim()
|
|
1770
|
+
let parsed = null
|
|
1771
|
+
try {
|
|
1772
|
+
parsed = JSON.parse(raw)
|
|
1773
|
+
} catch {
|
|
1774
|
+
parsed = null
|
|
1775
|
+
}
|
|
1776
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
1777
|
+
return { ok: false, error: 'lark-cli 没返回可解析的 JSON', detail: raw.slice(0, 600) }
|
|
1778
|
+
}
|
|
1779
|
+
if (parsed.ok === false) {
|
|
1780
|
+
const error = parsed.error ?? {}
|
|
1781
|
+
return {
|
|
1782
|
+
ok: false,
|
|
1783
|
+
error: String(error.message || error.subtype || '读取飞书文档失败'),
|
|
1784
|
+
detail: `type=${error.type ?? '?'} code=${error.code ?? '?'}`,
|
|
1785
|
+
hint: String(error.hint ?? ''),
|
|
1786
|
+
source: 'lark-cli',
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
const document = parsed?.data?.document ?? {}
|
|
1790
|
+
const content = String(document.content ?? '')
|
|
1791
|
+
const titleTag = /<title>([\s\S]*?)<\/title>/i.exec(content)
|
|
1792
|
+
const heading = /^#{1,3}\s+(.+)$/m.exec(content)
|
|
1793
|
+
const title = String(titleTag ? titleTag[1] : heading ? heading[1] : '').trim()
|
|
1794
|
+
const text = content.replace(/<title>[\s\S]*?<\/title>/i, '').trim()
|
|
1795
|
+
return {
|
|
1796
|
+
ok: true,
|
|
1797
|
+
documentId: String(document.document_id ?? ''),
|
|
1798
|
+
revision: Number(document.revision_id ?? 0) || 0,
|
|
1799
|
+
title,
|
|
1800
|
+
text,
|
|
1801
|
+
chars: text.length,
|
|
1802
|
+
tips: String(document.tips ?? ''),
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
const DOC_SCOPES = ['full', 'outline', 'keyword']
|
|
1807
|
+
|
|
1808
|
+
function safeFilePart(value, fallback = 'doc') {
|
|
1809
|
+
return String(value ?? '').replace(/[^\w.-]/g, '_') || fallback
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
function docsIndexFile(config) {
|
|
1813
|
+
return join(config.root, 'docs.json')
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
function docsContentDir(config) {
|
|
1817
|
+
return join(config.root, 'docs')
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
/** 已拉取过的文档清单(只记来源与标题,不记凭证)。 */
|
|
1821
|
+
async function readDocs(config) {
|
|
1822
|
+
try {
|
|
1823
|
+
const parsed = JSON.parse(await readFile(docsIndexFile(config), 'utf8'))
|
|
1824
|
+
const items = Array.isArray(parsed?.items) ? parsed.items : []
|
|
1825
|
+
return items
|
|
1826
|
+
.filter((item) => item && typeof item.id === 'string' && item.id)
|
|
1827
|
+
.map((item) => ({
|
|
1828
|
+
id: String(item.id),
|
|
1829
|
+
title: String(item.title ?? ''),
|
|
1830
|
+
url: String(item.url ?? ''),
|
|
1831
|
+
kind: String(item.kind ?? ''),
|
|
1832
|
+
revision: Number(item.revision ?? 0) || 0,
|
|
1833
|
+
chars: Number(item.chars ?? 0) || 0,
|
|
1834
|
+
addedAt: String(item.addedAt ?? ''),
|
|
1835
|
+
}))
|
|
1836
|
+
} catch {
|
|
1837
|
+
return []
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
async function writeDocs(config, items) {
|
|
1842
|
+
await mkdir(dirname(docsIndexFile(config)), { recursive: true })
|
|
1843
|
+
await writeFile(docsIndexFile(config), `${JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), items }, null, 2)}\n`, 'utf8')
|
|
1844
|
+
return items
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
/** 拉一篇飞书文档:lark-cli docs +fetch -> 正文落盘 + 记进清单。 */
|
|
1848
|
+
async function fetchFeishuDoc(config, body) {
|
|
1849
|
+
const input = String(body?.input ?? '').trim()
|
|
1850
|
+
const parsed = parseDocInput(input)
|
|
1851
|
+
if (!parsed.doc) return { ok: false, error: '请粘贴飞书文档链接(/docx/ 或 /wiki/),或直接给文档 token' }
|
|
1852
|
+
const scope = DOC_SCOPES.includes(body?.scope) ? body.scope : 'full'
|
|
1853
|
+
const identity = String(body?.identity ?? '').trim() || config.identity || 'user'
|
|
1854
|
+
const larkCli = await resolveLarkCli(config.larkCli)
|
|
1855
|
+
const wrapper = shellWrapper(larkCli)
|
|
1856
|
+
const args = ['docs', '+fetch', '--doc', parsed.doc, '--doc-format', 'markdown', '--scope', scope, '--as', identity]
|
|
1857
|
+
if (scope === 'keyword' && body?.keyword) args.push('--keyword', String(body.keyword))
|
|
1858
|
+
const command = `lark-cli docs +fetch --doc ${parsed.doc} --doc-format markdown --scope ${scope} --as ${identity}`
|
|
1859
|
+
const result = await runLark(wrapper, args)
|
|
1860
|
+
// 授权/权限类的 JSON 走 stderr,业务成功走 stdout:两边都试一遍再决定报错。
|
|
1861
|
+
const payload = parseDocPayload(result.stdout).ok ? parseDocPayload(result.stdout) : parseDocPayload(result.stderr)
|
|
1862
|
+
if (!payload.ok) {
|
|
1863
|
+
if (!result.ok && /not JSON|没返回可解析/.test(String(payload.error))) {
|
|
1864
|
+
return { ok: false, error: '读取飞书文档失败', detail: (result.stderr || result.stdout || '').trim().slice(0, 1200), command }
|
|
1865
|
+
}
|
|
1866
|
+
return { ok: false, error: payload.error, detail: payload.detail, hint: payload.hint, command }
|
|
1867
|
+
}
|
|
1868
|
+
if (!payload.text) {
|
|
1869
|
+
return { ok: false, error: '这篇文档没读到正文(可能是空文档或没有权限)', command, revision: payload.revision }
|
|
1870
|
+
}
|
|
1871
|
+
const id = payload.documentId || parsed.doc
|
|
1872
|
+
const dir = docsContentDir(config)
|
|
1873
|
+
try {
|
|
1874
|
+
await mkdir(dir, { recursive: true })
|
|
1875
|
+
await writeFile(join(dir, `${safeFilePart(id)}.md`), `${payload.text}\n`, 'utf8')
|
|
1876
|
+
} catch (error) {
|
|
1877
|
+
return { ok: false, error: `文档正文落盘失败:${String(error?.message ?? error)}` }
|
|
1878
|
+
}
|
|
1879
|
+
const item = {
|
|
1880
|
+
id,
|
|
1881
|
+
title: payload.title || input.slice(0, 60),
|
|
1882
|
+
url: parsed.url || input,
|
|
1883
|
+
kind: parsed.kind,
|
|
1884
|
+
revision: payload.revision,
|
|
1885
|
+
chars: payload.chars,
|
|
1886
|
+
addedAt: new Date().toISOString(),
|
|
1887
|
+
}
|
|
1888
|
+
const items = await readDocs(config)
|
|
1889
|
+
const next = [item, ...items.filter((entry) => entry.id !== id)]
|
|
1890
|
+
await writeDocs(config, next)
|
|
1891
|
+
return { ok: true, item, items: next, text: payload.text, chars: payload.chars, revision: payload.revision, scope, command }
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
async function readDocContent(config, id) {
|
|
1895
|
+
const wanted = String(id ?? '').trim()
|
|
1896
|
+
if (!wanted) return { ok: false, error: '缺少文档 id' }
|
|
1897
|
+
const items = await readDocs(config)
|
|
1898
|
+
const item = items.find((entry) => entry.id === wanted)
|
|
1899
|
+
if (!item) return { ok: false, error: '这篇文档不在已拉取清单里' }
|
|
1900
|
+
const text = await readFile(join(docsContentDir(config), `${safeFilePart(item.id)}.md`), 'utf8').catch(() => null)
|
|
1901
|
+
if (text === null) return { ok: false, error: '正文文件读不到,重新拉取一次即可' }
|
|
1902
|
+
return { ok: true, item, text }
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
async function removeDoc(config, id) {
|
|
1906
|
+
const wanted = String(id ?? '').trim()
|
|
1907
|
+
const items = await readDocs(config)
|
|
1908
|
+
const next = items.filter((entry) => entry.id !== wanted)
|
|
1909
|
+
await rm(join(docsContentDir(config), `${safeFilePart(wanted)}.md`), { force: true }).catch(() => {})
|
|
1910
|
+
await writeDocs(config, next)
|
|
1911
|
+
return { ok: true, items: next }
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
/* ----------------------------------------- 专家团全流程(需求→开发→评审→QA) */
|
|
1915
|
+
|
|
1916
|
+
/**
|
|
1917
|
+
* 四段固定流程;role 是本机已有的专家角色标识(DSH_HOME/agents/<role>.md)。
|
|
1918
|
+
* needsEvidence:这一段必须能落成凭据,界面上会提示;没凭据也能完成,但会记成 done_unverified。
|
|
1919
|
+
* required:v4.2 恒为 true,等 v4.3 做「阶段可裁剪」时才会真正参与完成度分母。
|
|
1920
|
+
*/
|
|
1921
|
+
export const FLOW_STAGES = [
|
|
1922
|
+
{ id: 'analyze', name: '需求分析', role: 'product-requirement-expert', needsEvidence: true, required: true },
|
|
1923
|
+
{ id: 'develop', name: '代码开发', role: 'fullstack-architect', needsEvidence: true, required: true },
|
|
1924
|
+
{ id: 'review', name: '代码评审', role: 'code-review-expert', needsEvidence: true, required: true },
|
|
1925
|
+
{ id: 'qa', name: 'QA 测试', role: 'qa-test-expert', needsEvidence: true, required: true },
|
|
1926
|
+
]
|
|
1927
|
+
|
|
1928
|
+
export const FLOW_STATUS = [
|
|
1929
|
+
{ id: 'pending', label: '待开始' },
|
|
1930
|
+
{ id: 'running', label: '进行中' },
|
|
1931
|
+
{ id: 'done', label: '已完成' },
|
|
1932
|
+
{ id: 'done_unverified', label: '已完成 · 无凭据' },
|
|
1933
|
+
{ id: 'blocked', label: '受阻' },
|
|
1934
|
+
]
|
|
1935
|
+
|
|
1936
|
+
/**
|
|
1937
|
+
* 凭据的种类。刻意把「备注」排除在外:一句「已完成」不是凭据,一段人写的说明也不是。
|
|
1938
|
+
* 只有命令输出 / 文件清单 / 测试结果 / 链接 / spec 文档路径算。
|
|
1939
|
+
*/
|
|
1940
|
+
export const FLOW_EVIDENCE_KINDS = [
|
|
1941
|
+
{ id: 'command', label: '命令', hint: '跑过的命令 + 输出摘要' },
|
|
1942
|
+
{ id: 'files', label: '文件', hint: '改动的文件清单(如 git diff --stat)' },
|
|
1943
|
+
{ id: 'test', label: '测试', hint: '用例数 / 通过失败条数' },
|
|
1944
|
+
{ id: 'url', label: '链接', hint: 'PR / CI / 构建结果链接' },
|
|
1945
|
+
{ id: 'spec', label: '规格', hint: '项目里 skill 产出的 spec 文档路径' },
|
|
1946
|
+
]
|
|
1947
|
+
|
|
1948
|
+
const FLOW_STATUS_IDS = FLOW_STATUS.map((entry) => entry.id)
|
|
1949
|
+
const FLOW_EVIDENCE_KIND_IDS = FLOW_EVIDENCE_KINDS.map((entry) => entry.id)
|
|
1950
|
+
const EVIDENCE_MAX_CHARS = 200
|
|
1951
|
+
|
|
1952
|
+
export function flowStageName(stageId) {
|
|
1953
|
+
return FLOW_STAGES.find((entry) => entry.id === stageId)?.name ?? String(stageId ?? '')
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
/** 「已完成 · 无凭据」也推进进度,但它不是有证据的完成 —— 台账里要分开数。 */
|
|
1957
|
+
export function isStageDone(stage) {
|
|
1958
|
+
return stage?.status === 'done' || stage?.status === 'done_unverified'
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
/** 一条流水线的阶段完成度(已完成 / 全部)。 */
|
|
1962
|
+
export function flowPercent(flow) {
|
|
1963
|
+
const stages = flow?.stages ?? []
|
|
1964
|
+
if (!stages.length) return 0
|
|
1965
|
+
const done = stages.filter(isStageDone).length
|
|
1966
|
+
return Math.round((done / stages.length) * 100)
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
/** 台账口径:这条流水线有几条凭据、几个阶段是「无凭据完成」的。 */
|
|
1970
|
+
export function flowEvidenceStats(flow) {
|
|
1971
|
+
const stages = flow?.stages ?? []
|
|
1972
|
+
const evidence = stages.reduce((sum, stage) => sum + (Array.isArray(stage.evidence) ? stage.evidence.length : 0), 0)
|
|
1973
|
+
const unverified = stages.filter((stage) => stage.status === 'done_unverified').length
|
|
1974
|
+
const done = stages.filter(isStageDone).length
|
|
1975
|
+
return { evidence, unverified, done, stages: stages.length }
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
/** 事件流 -> 最新流水线(每个 id 一条,附各阶段状态)。 */
|
|
1979
|
+
export function foldFlows(events) {
|
|
1980
|
+
const map = new Map()
|
|
1981
|
+
for (const event of events) {
|
|
1982
|
+
if (!event || typeof event !== 'object' || !event.id) continue
|
|
1983
|
+
if (event.type === 'create') {
|
|
1984
|
+
const ids = (Array.isArray(event.stages) && event.stages.length ? event.stages : FLOW_STAGES.map((stage) => stage.id)).map(String)
|
|
1985
|
+
map.set(String(event.id), {
|
|
1986
|
+
id: String(event.id),
|
|
1987
|
+
at: String(event.at ?? ''),
|
|
1988
|
+
title: String(event.title ?? ''),
|
|
1989
|
+
recordId: String(event.recordId ?? ''),
|
|
1990
|
+
tableKey: String(event.tableKey ?? ''),
|
|
1991
|
+
team: String(event.team ?? ''),
|
|
1992
|
+
teamName: String(event.teamName ?? ''),
|
|
1993
|
+
// v4.4:老流水线没有这个字段,一律按「单会话执行」;只有显式 true 才走 AgentTeams。
|
|
1994
|
+
teamMode: event.teamMode === true || event.teamMode === 'true',
|
|
1995
|
+
stages: ids.map((id) => ({ id, status: 'pending', note: '', at: '', evidence: [] })),
|
|
1996
|
+
})
|
|
1997
|
+
continue
|
|
1998
|
+
}
|
|
1999
|
+
const flow = map.get(String(event.id))
|
|
2000
|
+
if (!flow) continue
|
|
2001
|
+
if (event.type === 'stage') {
|
|
2002
|
+
const stage = flow.stages.find((entry) => entry.id === event.stage)
|
|
2003
|
+
if (!stage) continue
|
|
2004
|
+
if (FLOW_STATUS_IDS.includes(event.status)) stage.status = event.status
|
|
2005
|
+
if (event.note !== undefined) stage.note = String(event.note)
|
|
2006
|
+
stage.at = String(event.at ?? '')
|
|
2007
|
+
flow.updatedAt = String(event.at ?? '')
|
|
2008
|
+
}
|
|
2009
|
+
if (event.type === 'evidence') {
|
|
2010
|
+
// 凭据是追加式的:先贴凭据再标完成、或反过来都行。老事件没有 evidence 字段就当没贴。
|
|
2011
|
+
const stage = flow.stages.find((entry) => entry.id === event.stage)
|
|
2012
|
+
if (!stage) continue
|
|
2013
|
+
const kind = FLOW_EVIDENCE_KIND_IDS.includes(event.kind) ? event.kind : 'command'
|
|
2014
|
+
const summary = String(event.summary ?? '').trim().slice(0, EVIDENCE_MAX_CHARS)
|
|
2015
|
+
if (!summary) continue
|
|
2016
|
+
stage.evidence = [
|
|
2017
|
+
...(stage.evidence ?? []),
|
|
2018
|
+
{ kind, summary, ref: String(event.ref ?? '').slice(0, 300), at: String(event.at ?? '') },
|
|
2019
|
+
]
|
|
2020
|
+
flow.updatedAt = String(event.at ?? '')
|
|
2021
|
+
}
|
|
2022
|
+
if (event.type === 'evidence-remove') {
|
|
2023
|
+
const stage = flow.stages.find((entry) => entry.id === event.stage)
|
|
2024
|
+
if (!stage) continue
|
|
2025
|
+
const targetAt = String(event.targetAt ?? '')
|
|
2026
|
+
stage.evidence = (stage.evidence ?? []).filter((entry) => entry.at !== targetAt)
|
|
2027
|
+
flow.updatedAt = String(event.at ?? '')
|
|
2028
|
+
}
|
|
2029
|
+
if (event.type === 'remove') flow.removed = true
|
|
2030
|
+
}
|
|
2031
|
+
return [...map.values()]
|
|
2032
|
+
.filter((flow) => !flow.removed)
|
|
2033
|
+
.sort((a, b) => String(b.updatedAt ?? b.at).localeCompare(String(a.updatedAt ?? a.at)))
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
function flowsFile(config) {
|
|
2037
|
+
return join(config.root, 'flows.jsonl')
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
async function readFlows(config) {
|
|
2041
|
+
const text = await readFile(flowsFile(config), 'utf8').catch(() => '')
|
|
2042
|
+
const events = text
|
|
2043
|
+
.split(/\r?\n/)
|
|
2044
|
+
.filter(Boolean)
|
|
2045
|
+
.map((line) => {
|
|
2046
|
+
try {
|
|
2047
|
+
return JSON.parse(line)
|
|
2048
|
+
} catch {
|
|
2049
|
+
return null
|
|
2050
|
+
}
|
|
2051
|
+
})
|
|
2052
|
+
.filter(Boolean)
|
|
2053
|
+
return foldFlows(events)
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
async function appendFlow(config, event) {
|
|
2057
|
+
await mkdir(dirname(flowsFile(config)), { recursive: true })
|
|
2058
|
+
await appendFile(flowsFile(config), `${JSON.stringify(event)}\n`, 'utf8')
|
|
2059
|
+
return event
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2062
|
+
/* --------------------------------- 项目里的 spec 文档(开发 skill 产出,工作台只认不造) */
|
|
2063
|
+
|
|
2064
|
+
/**
|
|
2065
|
+
* spec 不由本工作台生成 —— 它来自项目里的开发 skill 流程(dev-task-sync 的 .dev-tasks/、
|
|
2066
|
+
* OpenSpec 的 openspec/changes/、Spec Kit 的 specs/ 等)。工作台做三件事:
|
|
2067
|
+
* 认出来、允许作为「规格」类凭据引用、对验收标准做一次「能不能失败」的机械检查。
|
|
2068
|
+
*/
|
|
2069
|
+
const SPEC_DIRS = [
|
|
2070
|
+
{ dir: 'specs', label: 'specs/' },
|
|
2071
|
+
{ dir: 'openspec/specs', label: 'openspec/specs/' },
|
|
2072
|
+
{ dir: 'openspec/changes', label: 'openspec/changes/' },
|
|
2073
|
+
{ dir: '.dev-tasks', label: '.dev-tasks/(dev-task-sync 产出)' },
|
|
2074
|
+
{ dir: 'doc/specs', label: 'doc/specs/' },
|
|
2075
|
+
{ dir: 'docs/specs', label: 'docs/specs/' },
|
|
2076
|
+
]
|
|
2077
|
+
|
|
2078
|
+
const SPEC_ROOT_PATTERNS = [/\.spec\.md$/i, /^requirements\.md$/i, /^spec\.md$/i]
|
|
2079
|
+
const SPEC_MAX_DEPTH = 4
|
|
2080
|
+
const SPEC_MAX_FILES = 120
|
|
2081
|
+
const SPEC_MAX_BYTES = 200 * 1024
|
|
2082
|
+
const SPEC_SKIP_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage', 'target', 'vendor'])
|
|
2083
|
+
|
|
2084
|
+
async function collectSpecFiles(rootDir, items, depth = 0) {
|
|
2085
|
+
if (depth > SPEC_MAX_DEPTH || items.length >= SPEC_MAX_FILES) return
|
|
2086
|
+
const entries = await readdir(rootDir, { withFileTypes: true }).catch(() => [])
|
|
2087
|
+
for (const entry of entries) {
|
|
2088
|
+
if (items.length >= SPEC_MAX_FILES) return
|
|
2089
|
+
const name = String(entry.name ?? '')
|
|
2090
|
+
if (!name) continue
|
|
2091
|
+
if (entry.isDirectory()) {
|
|
2092
|
+
if (name.startsWith('.') || SPEC_SKIP_DIRS.has(name)) continue
|
|
2093
|
+
await collectSpecFiles(join(rootDir, name), items, depth + 1)
|
|
2094
|
+
continue
|
|
2095
|
+
}
|
|
2096
|
+
if (!entry.isFile() || !/\.md$/i.test(name)) continue
|
|
2097
|
+
const path = join(rootDir, name)
|
|
2098
|
+
const info = await stat(path).catch(() => null)
|
|
2099
|
+
if (!info || info.size > SPEC_MAX_BYTES) continue
|
|
2100
|
+
if (items.some((item) => resolve(item.path) === resolve(path))) continue
|
|
2101
|
+
items.push({ path, name, bytes: info.size, mtime: info.mtime.toISOString() })
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
export async function listSpecFiles(config, settings) {
|
|
2106
|
+
const projectDir = String(settings?.projectDir ?? '').trim()
|
|
2107
|
+
if (!projectDir) {
|
|
2108
|
+
return { ok: false, error: '先在设置里选项目目录,才能扫项目里 skill 产出的 spec 文档', items: [], roots: [] }
|
|
2109
|
+
}
|
|
2110
|
+
const items = []
|
|
2111
|
+
const roots = []
|
|
2112
|
+
for (const entry of SPEC_DIRS) {
|
|
2113
|
+
const dir = join(projectDir, entry.dir)
|
|
2114
|
+
const before = items.length
|
|
2115
|
+
if (existsSync(dir)) {
|
|
2116
|
+
await collectSpecFiles(dir, items)
|
|
2117
|
+
roots.push({ dir: entry.dir, label: entry.label, exists: true, files: items.length - before })
|
|
2118
|
+
} else {
|
|
2119
|
+
roots.push({ dir: entry.dir, label: entry.label, exists: false, files: 0 })
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
// 项目根下的 *.spec.md / requirements.md / spec.md(skill 常把 spec 放在根上)
|
|
2123
|
+
const rootEntries = await readdir(projectDir, { withFileTypes: true }).catch(() => [])
|
|
2124
|
+
for (const entry of rootEntries) {
|
|
2125
|
+
if (!entry.isFile()) continue
|
|
2126
|
+
const name = String(entry.name ?? '')
|
|
2127
|
+
if (!SPEC_ROOT_PATTERNS.some((pattern) => pattern.test(name))) continue
|
|
2128
|
+
const path = join(projectDir, name)
|
|
2129
|
+
const info = await stat(path).catch(() => null)
|
|
2130
|
+
if (!info || info.size > SPEC_MAX_BYTES) continue
|
|
2131
|
+
if (items.some((item) => resolve(item.path) === resolve(path))) continue
|
|
2132
|
+
items.push({ path, name, bytes: info.size, mtime: info.mtime.toISOString() })
|
|
2133
|
+
}
|
|
2134
|
+
items.sort((a, b) => String(b.mtime).localeCompare(String(a.mtime)))
|
|
2135
|
+
return { ok: true, projectDir, items, roots }
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
const ACCEPTANCE_HEADING = /(验收标准|验收条件|验收准则|acceptance\s*criteria|acceptance)/i
|
|
2139
|
+
const CONDITION_RULES = [
|
|
2140
|
+
/当[^。;]{1,40}?(时|后)/,
|
|
2141
|
+
/如果/,
|
|
2142
|
+
/假如/,
|
|
2143
|
+
/若[^。;]{1,30}?(则|就)/,
|
|
2144
|
+
/一旦/,
|
|
2145
|
+
/在[^。;]{1,40}?时/,
|
|
2146
|
+
/\bwhen\b/i,
|
|
2147
|
+
/\bgiven\b/i,
|
|
2148
|
+
/\bif\b/i,
|
|
2149
|
+
]
|
|
2150
|
+
const DECIDABLE_RULES = [
|
|
2151
|
+
/返回/,
|
|
2152
|
+
/拒绝/,
|
|
2153
|
+
/提示/,
|
|
2154
|
+
/显示/,
|
|
2155
|
+
/保存/,
|
|
2156
|
+
/写入/,
|
|
2157
|
+
/跳转/,
|
|
2158
|
+
/抛出/,
|
|
2159
|
+
/不允许/,
|
|
2160
|
+
/禁止/,
|
|
2161
|
+
/失败/,
|
|
2162
|
+
/成功/,
|
|
2163
|
+
/变更为|改为/,
|
|
2164
|
+
/等于|大于|小于/,
|
|
2165
|
+
/不得|必须|应当/,
|
|
2166
|
+
/校验|拦截/,
|
|
2167
|
+
/记录|生成|删除|创建|更新|提交/,
|
|
2168
|
+
/\breturn\b|\breject\b|\bshow\b|\bsave\b|\bwrite\b|\bthrow\b|\bfail\b|\bmust\b|\bshould\b/i,
|
|
2169
|
+
]
|
|
2170
|
+
const MAX_CRITERION_CHARS = 60
|
|
2171
|
+
|
|
2172
|
+
/**
|
|
2173
|
+
* 验收标准的「能不能失败」机械检查(纯规则,不调模型)。
|
|
2174
|
+
* 「注册功能正常工作」无法失败;「当邮箱已注册时,接口返回 409」可以失败 —— 后者在成为代码
|
|
2175
|
+
* 之前就已经是一条测试。只标黄、不阻断:误报的代价是没人再看黄条。
|
|
2176
|
+
*/
|
|
2177
|
+
export function checkAcceptanceCriteria(text) {
|
|
2178
|
+
const lines = String(text ?? '').split(/\r?\n/)
|
|
2179
|
+
const criteria = []
|
|
2180
|
+
let inSection = false
|
|
2181
|
+
let headingLevel = 0
|
|
2182
|
+
for (const raw of lines) {
|
|
2183
|
+
const line = raw.trim()
|
|
2184
|
+
const heading = /^(#{1,6})\s+(.*)$/.exec(line)
|
|
2185
|
+
if (heading) {
|
|
2186
|
+
const level = heading[1].length
|
|
2187
|
+
if (ACCEPTANCE_HEADING.test(heading[2])) {
|
|
2188
|
+
inSection = true
|
|
2189
|
+
headingLevel = level
|
|
2190
|
+
continue
|
|
2191
|
+
}
|
|
2192
|
+
if (inSection && level <= headingLevel) inSection = false
|
|
2193
|
+
continue
|
|
2194
|
+
}
|
|
2195
|
+
if (!inSection) continue
|
|
2196
|
+
const bullet = /^(?:[-*+]|\d+[.)])\s+(.*)$/.exec(line)
|
|
2197
|
+
if (!bullet) continue
|
|
2198
|
+
const item = bullet[1].trim()
|
|
2199
|
+
if (item) criteria.push(item)
|
|
2200
|
+
}
|
|
2201
|
+
if (!criteria.length) return { found: false, total: 0, weak: [] }
|
|
2202
|
+
const weak = []
|
|
2203
|
+
for (const [index, item] of criteria.entries()) {
|
|
2204
|
+
const reasons = []
|
|
2205
|
+
if (!CONDITION_RULES.some((rule) => rule.test(item))) reasons.push('没有触发条件(当…时 / 如果…)')
|
|
2206
|
+
if (!DECIDABLE_RULES.some((rule) => rule.test(item))) reasons.push('没有可判定的结果(返回 / 拒绝 / 显示…)')
|
|
2207
|
+
const length = [...item].length
|
|
2208
|
+
if (length > MAX_CRITERION_CHARS) reasons.push(`太长(${length} 字 > ${MAX_CRITERION_CHARS} 字,拆成几条)`)
|
|
2209
|
+
if (reasons.length) weak.push({ index: index + 1, text: item.slice(0, 160), reasons })
|
|
2210
|
+
}
|
|
2211
|
+
return { found: true, total: criteria.length, weak }
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/* --------------------------------------- 更新日志(包内 CHANGELOG.md) */
|
|
2215
|
+
|
|
2216
|
+
/**
|
|
2217
|
+
* 读包自带的 CHANGELOG.md,交给界面「版本号 → 更新日志」弹窗渲染。
|
|
2218
|
+
* 只读包内文件,不接受任何外部路径;文件缺失就返回空,不当成错误。
|
|
2219
|
+
*/
|
|
2220
|
+
async function readChangelog() {
|
|
2221
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
2222
|
+
const candidates = [join(here, '..', 'CHANGELOG.md'), join(here, 'CHANGELOG.md')]
|
|
2223
|
+
for (const file of candidates) {
|
|
2224
|
+
const text = await readFile(file, 'utf8').catch(() => null)
|
|
2225
|
+
if (text === null) continue
|
|
2226
|
+
return { found: true, path: file, text, sections: parseChangelog(text) }
|
|
2227
|
+
}
|
|
2228
|
+
return { found: false, path: '', text: '', sections: [] }
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
/**
|
|
2232
|
+
* 把 CHANGELOG 拆成 `[{ version, date, items: string[] }]`。
|
|
2233
|
+
* 只认 `## vX.Y.Z — 日期` 形式的标题(兼容 `–`/`-` 破折号),
|
|
2234
|
+
* 正文里以 `- ` 开头的是条目;其它说明性文字丢掉,界面只展示条目。
|
|
2235
|
+
*/
|
|
2236
|
+
export function parseChangelog(text) {
|
|
2237
|
+
const sections = []
|
|
2238
|
+
let current = null
|
|
2239
|
+
for (const rawLine of String(text ?? '').split(/\r?\n/)) {
|
|
2240
|
+
const line = rawLine.trim()
|
|
2241
|
+
const heading = /^##\s+v?(\d+\.\d+\.\d+)\s*(?:[—–-]+\s*(\d{4}-\d{2}-\d{2}))?/u.exec(line)
|
|
2242
|
+
if (heading) {
|
|
2243
|
+
current = { version: heading[1], date: heading[2] ?? '', items: [] }
|
|
2244
|
+
sections.push(current)
|
|
2245
|
+
continue
|
|
2246
|
+
}
|
|
2247
|
+
if (!current) continue
|
|
2248
|
+
if (/^#{2,}\s/u.test(line)) {
|
|
2249
|
+
current = null
|
|
2250
|
+
continue
|
|
2251
|
+
}
|
|
2252
|
+
const item = /^[-*]\s+(.*)$/u.exec(line)
|
|
2253
|
+
if (item && item[1]) current.items.push(item[1])
|
|
2254
|
+
}
|
|
2255
|
+
return sections.filter((section) => section.items.length > 0)
|
|
2256
|
+
}
|
|
2257
|
+
|
|
2258
|
+
async function readSpecFile(config, settings, target) {
|
|
2259
|
+
const wanted = String(target ?? '').trim()
|
|
2260
|
+
if (!wanted) return { ok: false, error: '缺少 spec 文件路径' }
|
|
2261
|
+
const listing = await listSpecFiles(config, settings)
|
|
2262
|
+
if (!listing.ok) return { ok: false, error: listing.error }
|
|
2263
|
+
// 白名单:只读扫描结果里的文件,别的一律拒绝(路径由客户端传,不能全信)。
|
|
2264
|
+
const hit = listing.items.find((item) => resolve(item.path) === resolve(wanted))
|
|
2265
|
+
if (!hit) return { ok: false, error: '该路径不在本工作台可读的 spec 范围内(先刷新 spec 扫描)' }
|
|
2266
|
+
const text = await readFile(hit.path, 'utf8').catch((error) => {
|
|
2267
|
+
return `__READ_ERROR__${String(error?.message ?? error)}`
|
|
2268
|
+
})
|
|
2269
|
+
if (text.startsWith('__READ_ERROR__')) return { ok: false, error: text.slice('__READ_ERROR__'.length) }
|
|
2270
|
+
const checks = checkAcceptanceCriteria(text)
|
|
2271
|
+
return {
|
|
2272
|
+
ok: true,
|
|
2273
|
+
path: hit.path,
|
|
2274
|
+
name: hit.name,
|
|
2275
|
+
bytes: hit.bytes,
|
|
2276
|
+
truncated: text.length > 40_000,
|
|
2277
|
+
text: text.length > 40_000 ? `${text.slice(0, 40_000)}\n\n…(已截断,共 ${text.length} 字)` : text,
|
|
2278
|
+
checks,
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
/* ------------------------------------------------ 页面内 AI 直接创建(不走对话) */
|
|
2283
|
+
|
|
2284
|
+
/** 模型可能把 JSON 包在代码围栏或解释文字里:剥掉围栏、截取最外层大括号再试。 */
|
|
2285
|
+
export function parseJsonLoose(text) {
|
|
2286
|
+
const raw = String(text ?? '').trim()
|
|
2287
|
+
if (!raw) return null
|
|
2288
|
+
const fenced = raw
|
|
2289
|
+
.replace(/^```[a-zA-Z]*\s*/, '')
|
|
2290
|
+
.replace(/```\s*$/, '')
|
|
2291
|
+
.trim()
|
|
2292
|
+
const candidates = [fenced]
|
|
2293
|
+
const start = fenced.indexOf('{')
|
|
2294
|
+
const end = fenced.lastIndexOf('}')
|
|
2295
|
+
if (start >= 0 && end > start) candidates.push(fenced.slice(start, end + 1))
|
|
2296
|
+
for (const candidate of candidates) {
|
|
2297
|
+
try {
|
|
2298
|
+
const parsed = JSON.parse(candidate)
|
|
2299
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
|
|
2300
|
+
} catch {
|
|
2301
|
+
/* 试下一种截法 */
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
return null
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
/** 取当前默认模型路由:优先会话默认,其次插件配置里的显式指定。 */
|
|
2308
|
+
export function resolveLlmRoute(ctx, settings) {
|
|
2309
|
+
const explicitProvider = String(settings?.aiProvider ?? '').trim()
|
|
2310
|
+
const explicitModel = String(settings?.aiModel ?? '').trim()
|
|
2311
|
+
if (explicitProvider && explicitModel) return { provider: explicitProvider, model: explicitModel }
|
|
2312
|
+
const service = typeof ctx?.get === 'function' ? ctx.get('agentDefaultModel') : undefined
|
|
2313
|
+
let selection = null
|
|
2314
|
+
try {
|
|
2315
|
+
selection = typeof service?.currentSelection === 'function' ? service.currentSelection() : null
|
|
2316
|
+
} catch {
|
|
2317
|
+
selection = null
|
|
2318
|
+
}
|
|
2319
|
+
const provider = String(selection?.provider ?? selection?.providerId ?? selection?.route?.provider ?? '').trim()
|
|
2320
|
+
const model = String(selection?.model ?? selection?.modelId ?? selection?.route?.model ?? '').trim()
|
|
2321
|
+
if (!provider || !model) return null
|
|
2322
|
+
return { provider, model, reasoningEffort: selection?.reasoningEffort }
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
const AI_DRAFT_SYSTEM =
|
|
2326
|
+
'你是 DeepSeek Harness 的「专家架构师」,负责把用户一句粗略描述完善成能立刻上岗的专家角色定义。' +
|
|
2327
|
+
'你只输出一个 JSON 对象:不要解释、不要代码围栏、不要多余文字。描述里没写到的细节按专业判断补齐,不要反问用户、不要要求确认。'
|
|
2328
|
+
|
|
2329
|
+
const AI_FLOW_STEPS = [
|
|
2330
|
+
'定位与边界:属于哪条链路(前端 / 后端 / 数据 / 测试 / 评审 / 交付…)、和相邻角色怎么分工',
|
|
2331
|
+
'能力清单:从擅长的技术栈与场景倒推 4-6 项可独立交付的能力',
|
|
2332
|
+
'工作流程:按「读规范 → 理解需求 → 出方案 → 实现 → 自测 → 交付」写成固定动作',
|
|
2333
|
+
'输出规范:交付物形态(代码 / 文档 / 单测 / 评审意见)与必须给出的证据',
|
|
2334
|
+
'红线与自检:最容易出错的 3-5 个点,以及什么情况必须停下报告',
|
|
2335
|
+
'触发场景:写清「什么时候该请他」,让调度的人一眼能判断',
|
|
2336
|
+
]
|
|
2337
|
+
|
|
2338
|
+
/** 单个专家的 JSON 作业单。 */
|
|
2339
|
+
export function aiExpertPrompt({ description, id = '', displayName = '' }) {
|
|
2340
|
+
const lines = [
|
|
2341
|
+
'请按下面的专业流程,把用户这句粗略描述完善成一位能立刻上岗的专家,并以 JSON 返回。',
|
|
2342
|
+
'',
|
|
2343
|
+
'## 用户的原话(唯一输入)',
|
|
2344
|
+
'"""',
|
|
2345
|
+
String(description ?? '').trim(),
|
|
2346
|
+
'"""',
|
|
2347
|
+
'',
|
|
2348
|
+
'## 内部专业流程(照这个想,不要把过程写进 JSON)',
|
|
2349
|
+
...AI_FLOW_STEPS.map((step, index) => `${index + 1}. ${step}`),
|
|
2350
|
+
'',
|
|
2351
|
+
'## 只输出这个 JSON 对象(字段全部必填,数组元素是字符串)',
|
|
2352
|
+
'{',
|
|
2353
|
+
` "id": "${id || 'kebab-case 小写英文标识,例如 payment-reconcile-expert'}",`,
|
|
2354
|
+
` "displayName": "${displayName || '中文短名,2-4 字,如「老付」'}",`,
|
|
2355
|
+
' "profession": "职业定位,如「支付对账专家」",',
|
|
2356
|
+
' "description": "一句话:他负责什么、什么时候该请他",',
|
|
2357
|
+
' "abilities": ["4-6 条能独立交付的具体能力(不要空话)"],',
|
|
2358
|
+
' "flow": ["5-8 步他接到需求后的固定动作"],',
|
|
2359
|
+
' "outputs": ["3-5 条交付时给什么、必须附什么证据"],',
|
|
2360
|
+
' "cautions": ["3-5 条红线与必须停下报告的情况"],',
|
|
2361
|
+
' "assumptions": ["最多 5 条你替他做的假设"]',
|
|
2362
|
+
'}',
|
|
2363
|
+
]
|
|
2364
|
+
if (id || displayName) lines.push('', `用户已指定:${id ? `标识 \`${id}\`` : ''}${id && displayName ? '、' : ''}${displayName ? `显示名 \`${displayName}\`` : ''},请直接采用。`)
|
|
2365
|
+
return lines.join('\n')
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
/** 专家团的 JSON 作业单:一次把团长、成员分工和缺的成员定义都给全。 */
|
|
2369
|
+
export function aiTeamPrompt({ description, id = '', known = [] }) {
|
|
2370
|
+
const lines = [
|
|
2371
|
+
'请按下面的专业流程,把用户这句粗略描述完善成一个能立刻开工的专家团(团长 + 成员分工),并以 JSON 返回。',
|
|
2372
|
+
'',
|
|
2373
|
+
'## 用户的原话(唯一输入)',
|
|
2374
|
+
'"""',
|
|
2375
|
+
String(description ?? '').trim(),
|
|
2376
|
+
'"""',
|
|
2377
|
+
'',
|
|
2378
|
+
'## 内部专业流程(照这个想,不要把过程写进 JSON)',
|
|
2379
|
+
...AI_FLOW_STEPS.map((step, index) => `${index + 1}. ${step}`),
|
|
2380
|
+
'7. 团队编排:谁先动、谁拍板、谁验收,交接点交付什么',
|
|
2381
|
+
'',
|
|
2382
|
+
'## 只输出这个 JSON 对象(字段全部必填)',
|
|
2383
|
+
'{',
|
|
2384
|
+
` "id": "${id || 'kebab-case 小写英文标识,例如 fullstack-delivery-team'}",`,
|
|
2385
|
+
' "name": "中文团名,如「全栈交付一条龙专家团」",',
|
|
2386
|
+
' "profession": "这个团整体干什么,如「需求 → 架构 → 开发 → 评审 → 测试 一条龙交付」",',
|
|
2387
|
+
' "description": "一句话:什么时候该请这个团",',
|
|
2388
|
+
' "lead": "members 里最该拍板那位的 id",',
|
|
2389
|
+
' "flow": ["3-6 条协作步骤(谁做什么、交接什么)"],',
|
|
2390
|
+
' "members": [',
|
|
2391
|
+
' {',
|
|
2392
|
+
' "id": "成员的 kebab-case 标识",',
|
|
2393
|
+
' "displayName": "中文短名 2-4 字",',
|
|
2394
|
+
' "profession": "职业定位",',
|
|
2395
|
+
' "description": "一句话:他负责什么、什么时候该请他",',
|
|
2396
|
+
' "abilities": ["4-6 条能独立交付的具体能力"],',
|
|
2397
|
+
' "flow": ["5-8 步固定动作"],',
|
|
2398
|
+
' "outputs": ["3-5 条交付物与证据"],',
|
|
2399
|
+
' "cautions": ["3-5 条红线"]',
|
|
2400
|
+
' }',
|
|
2401
|
+
' ],',
|
|
2402
|
+
' "assumptions": ["最多 5 条你替用户做的假设"]',
|
|
2403
|
+
'}',
|
|
2404
|
+
'',
|
|
2405
|
+
'members 给 2-6 位(按描述里的角色拆,一个人能兼两件事就写一个更贴切的成员)。',
|
|
2406
|
+
known.length ? `已经有这些专家,能复用就把他的 id 直接放进 members,不要重复造:${known.join('、')}` : '目前还没有已存在的专家。',
|
|
2407
|
+
]
|
|
2408
|
+
return lines.join('\n')
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
/** 把模型返回的数组字段转成 createExpert 认的「一行一条」文本。 */
|
|
2412
|
+
function linesOf(value) {
|
|
2413
|
+
if (Array.isArray(value)) return value.map((line) => String(line ?? '').trim()).filter(Boolean).join('\n')
|
|
2414
|
+
return String(value ?? '')
|
|
2415
|
+
}
|
|
2416
|
+
|
|
2417
|
+
/** 把模型这次回答的文本收集起来(只要 text-delta,遇到 error 收尾就记下来)。 */
|
|
2418
|
+
async function llmCollectText(llm, route, system, userText, signal) {
|
|
2419
|
+
let text = ''
|
|
2420
|
+
let failure = null
|
|
2421
|
+
const stream = llm.stream({
|
|
2422
|
+
provider: route.provider,
|
|
2423
|
+
model: route.model,
|
|
2424
|
+
reasoningEffort: route.reasoningEffort,
|
|
2425
|
+
system,
|
|
2426
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: userText }] }],
|
|
2427
|
+
maxTokens: 4000,
|
|
2428
|
+
signal,
|
|
2429
|
+
})
|
|
2430
|
+
for await (const chunk of stream) {
|
|
2431
|
+
if (chunk?.type === 'text-delta') text += String(chunk.text ?? '')
|
|
2432
|
+
else if (chunk?.type === 'finish' && chunk.reason?.kind === 'error') failure = chunk.reason.failure
|
|
2433
|
+
else if (chunk?.type === 'finish' && chunk.reason?.kind === 'aborted') failure = chunk.reason.failure ?? { message: '模型调用被中断' }
|
|
2434
|
+
}
|
|
2435
|
+
return { text, failure }
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
const AI_TIMEOUT_MS = 120000
|
|
2439
|
+
|
|
2440
|
+
/**
|
|
2441
|
+
* 页面里「AI 直接创建」:调宿主 llm 服务拿结构化草稿,再由工作台按标准格式落盘。
|
|
2442
|
+
* 全程不经过对话、不需要复制任何提示词;失败一律返回 ok:false + 原因,由页面提示退路。
|
|
2443
|
+
*/
|
|
2444
|
+
async function aiCreateDraft(ctx, config, settings, body) {
|
|
2445
|
+
const llm = typeof ctx?.get === 'function' ? ctx.get('llm') : undefined
|
|
2446
|
+
if (!llm || typeof llm.stream !== 'function') {
|
|
2447
|
+
return { ok: false, error: '这个宿主没提供「直接调模型」的能力,点「发到对话里做」即可' }
|
|
2448
|
+
}
|
|
2449
|
+
const route = resolveLlmRoute(ctx, settings)
|
|
2450
|
+
if (!route) return { ok: false, error: '取不到当前默认模型,先在对话框里选一个模型再试' }
|
|
2451
|
+
const kind = body?.kind === 'team' ? 'team' : 'expert'
|
|
2452
|
+
const description = String(body?.description ?? '').trim()
|
|
2453
|
+
if (!description) return { ok: false, error: '先用一句话说清你要谁(AI 靠它完善细节)' }
|
|
2454
|
+
const scope = body?.scope === 'project' ? 'project' : 'harness'
|
|
2455
|
+
const listing = await listExperts(config, settings)
|
|
2456
|
+
const known = listing.experts.map((expert) => expert.agentId)
|
|
2457
|
+
const userText = kind === 'team'
|
|
2458
|
+
? aiTeamPrompt({ description, id: String(body?.id ?? ''), known })
|
|
2459
|
+
: aiExpertPrompt({ description, id: String(body?.id ?? ''), displayName: String(body?.displayName ?? '') })
|
|
2460
|
+
const controller = new AbortController()
|
|
2461
|
+
const timer = setTimeout(() => controller.abort(), AI_TIMEOUT_MS)
|
|
2462
|
+
let text = ''
|
|
2463
|
+
let failure = null
|
|
2464
|
+
try {
|
|
2465
|
+
const result = await llmCollectText(llm, route, AI_DRAFT_SYSTEM, userText, controller.signal)
|
|
2466
|
+
text = result.text
|
|
2467
|
+
failure = result.failure
|
|
2468
|
+
} catch (error) {
|
|
2469
|
+
return { ok: false, error: `调模型失败:${String(error?.message ?? error)}` }
|
|
2470
|
+
} finally {
|
|
2471
|
+
clearTimeout(timer)
|
|
2472
|
+
}
|
|
2473
|
+
if (failure) return { ok: false, error: `模型报错:${String(failure.message ?? '未知错误')}` }
|
|
2474
|
+
const draft = parseJsonLoose(text)
|
|
2475
|
+
if (!draft) return { ok: false, error: '模型这次没给出可用的 JSON,可以点「发到对话里做」让它用文件工具落盘', raw: String(text).slice(0, 400) }
|
|
2476
|
+
|
|
2477
|
+
const created = []
|
|
2478
|
+
if (kind === 'expert') {
|
|
2479
|
+
const result = await createExpert(config, settings, {
|
|
2480
|
+
id: String(body?.id ?? '') || draft.id,
|
|
2481
|
+
name: draft.name,
|
|
2482
|
+
displayName: String(body?.displayName ?? '') || draft.displayName,
|
|
2483
|
+
profession: draft.profession,
|
|
2484
|
+
description: draft.description || description,
|
|
2485
|
+
abilities: linesOf(draft.abilities),
|
|
2486
|
+
flow: linesOf(draft.flow),
|
|
2487
|
+
outputs: linesOf(draft.outputs),
|
|
2488
|
+
cautions: linesOf(draft.cautions),
|
|
2489
|
+
scope,
|
|
2490
|
+
overwrite: false,
|
|
2491
|
+
})
|
|
2492
|
+
if (!result.ok) return { ok: false, error: result.error, draft }
|
|
2493
|
+
created.push(result)
|
|
2494
|
+
} else {
|
|
2495
|
+
const members = Array.isArray(draft.members) ? draft.members.slice(0, 8) : []
|
|
2496
|
+
if (!members.length) return { ok: false, error: '模型没给出团队成员,重试或改用「发到对话里做」', draft }
|
|
2497
|
+
const memberIds = []
|
|
2498
|
+
for (const member of members) {
|
|
2499
|
+
const memberId = slugifySkillName(member?.id || member?.agentId || member?.name)
|
|
2500
|
+
if (!memberId) continue
|
|
2501
|
+
memberIds.push(memberId)
|
|
2502
|
+
if (known.includes(memberId)) continue
|
|
2503
|
+
const result = await createExpert(config, settings, {
|
|
2504
|
+
id: memberId,
|
|
2505
|
+
displayName: member?.displayName,
|
|
2506
|
+
profession: member?.profession,
|
|
2507
|
+
description: member?.description || `${memberId}(由 AI 按专家团分工补齐)`,
|
|
2508
|
+
abilities: linesOf(member?.abilities),
|
|
2509
|
+
flow: linesOf(member?.flow),
|
|
2510
|
+
outputs: linesOf(member?.outputs),
|
|
2511
|
+
cautions: linesOf(member?.cautions),
|
|
2512
|
+
scope,
|
|
2513
|
+
overwrite: false,
|
|
2514
|
+
})
|
|
2515
|
+
if (result.ok) created.push(result)
|
|
2516
|
+
else if (!result.exists) return { ok: false, error: `成员「${memberId}」没建成:${result.error}`, draft, created }
|
|
2517
|
+
}
|
|
2518
|
+
if (!memberIds.length) return { ok: false, error: '模型给出的成员标识都不可用,重试一次', draft }
|
|
2519
|
+
const teamResult = await createTeam(config, settings, {
|
|
2520
|
+
id: String(body?.id ?? '') || draft.id,
|
|
2521
|
+
name: draft.name,
|
|
2522
|
+
profession: draft.profession,
|
|
2523
|
+
description: draft.description || description,
|
|
2524
|
+
lead: draft.lead,
|
|
2525
|
+
members: memberIds,
|
|
2526
|
+
flow: linesOf(draft.flow),
|
|
2527
|
+
scope,
|
|
2528
|
+
})
|
|
2529
|
+
if (!teamResult.ok) return { ok: false, error: teamResult.error, draft, created }
|
|
2530
|
+
created.push(teamResult)
|
|
2531
|
+
}
|
|
2532
|
+
const last = created[created.length - 1]
|
|
2533
|
+
return {
|
|
2534
|
+
ok: true,
|
|
2535
|
+
kind,
|
|
2536
|
+
model: `${route.provider}/${route.model}`,
|
|
2537
|
+
created,
|
|
2538
|
+
id: String(last?.id ?? ''),
|
|
2539
|
+
path: String(last?.path ?? ''),
|
|
2540
|
+
name: kind === 'team' ? String(draft.name ?? last?.id ?? '') : String(draft.displayName ?? draft.name ?? last?.id ?? ''),
|
|
2541
|
+
members: kind === 'team' ? (last?.members ?? []) : undefined,
|
|
2542
|
+
assumptions: Array.isArray(draft.assumptions) ? draft.assumptions.map(String).slice(0, 5) : [],
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
/* -------------------------------------------------------------- HTTP 层 */
|
|
2547
|
+
|
|
2548
|
+
function sendJson(res, status, payload) {
|
|
2549
|
+
const body = JSON.stringify(payload)
|
|
2550
|
+
res.writeHead(status, {
|
|
2551
|
+
'content-type': 'application/json; charset=utf-8',
|
|
2552
|
+
'cache-control': 'no-store',
|
|
2553
|
+
})
|
|
2554
|
+
res.end(body)
|
|
2555
|
+
}
|
|
2556
|
+
|
|
2557
|
+
function readBody(req) {
|
|
2558
|
+
return new Promise((resolvePromise) => {
|
|
2559
|
+
let data = ''
|
|
2560
|
+
let settled = false
|
|
2561
|
+
const done = (payload) => {
|
|
2562
|
+
if (settled) return
|
|
2563
|
+
settled = true
|
|
2564
|
+
resolvePromise(payload)
|
|
2565
|
+
}
|
|
2566
|
+
const parse = () => {
|
|
2567
|
+
if (!data) return {}
|
|
2568
|
+
try {
|
|
2569
|
+
return JSON.parse(data)
|
|
2570
|
+
} catch {
|
|
2571
|
+
return {}
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
req.on('data', (chunk) => {
|
|
2575
|
+
data += chunk
|
|
2576
|
+
if (data.length > 1024 * 1024) req.destroy()
|
|
2577
|
+
})
|
|
2578
|
+
req.on('end', () => done(parse()))
|
|
2579
|
+
// 客户端半路断开时也别把请求挂死
|
|
2580
|
+
req.on('close', () => done(parse()))
|
|
2581
|
+
req.on('error', () => done({}))
|
|
2582
|
+
})
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
export function apply(ctx, config) {
|
|
2586
|
+
const handler = async (req, res) => {
|
|
2587
|
+
let url
|
|
2588
|
+
try {
|
|
2589
|
+
url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
2590
|
+
} catch {
|
|
2591
|
+
return sendJson(res, 400, { error: 'bad url' })
|
|
2592
|
+
}
|
|
2593
|
+
const route = url.pathname.slice(API_PREFIX.length) || '/'
|
|
2594
|
+
try {
|
|
2595
|
+
if (route === '/state' && req.method === 'GET') {
|
|
2596
|
+
const settings = await readSettings(config)
|
|
2597
|
+
const larkCli = await resolveLarkCli(config.larkCli)
|
|
2598
|
+
const resolved = await resolveRequirementsSource(config, settings)
|
|
2599
|
+
return sendJson(res, 200, {
|
|
2600
|
+
settings,
|
|
2601
|
+
larkCli,
|
|
2602
|
+
identity: config.identity || 'user',
|
|
2603
|
+
configured: resolved.configured,
|
|
2604
|
+
source: publicSource(resolved),
|
|
2605
|
+
})
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
// 界面自检上报:客户端把「详情分栏的实际布局」报上来,排障时直接读 GET /ui/metrics
|
|
2609
|
+
// 只存在内存里(不落盘、不含任何凭证),进程重启即清空。
|
|
2610
|
+
if (route === '/ui/metrics' && req.method === 'POST') {
|
|
2611
|
+
const body = await readBody(req)
|
|
2612
|
+
uiMetrics = { ...body, at: new Date().toISOString() }
|
|
2613
|
+
return sendJson(res, 200, { ok: true })
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
if (route === '/ui/metrics' && req.method === 'GET') {
|
|
2617
|
+
return sendJson(res, 200, { ok: true, metrics: uiMetrics })
|
|
2618
|
+
}
|
|
2619
|
+
|
|
2620
|
+
if (route === '/settings' && req.method === 'POST') {
|
|
2621
|
+
const body = await readBody(req)
|
|
2622
|
+
const next = { ...body }
|
|
2623
|
+
if (typeof next.baseInput === 'string' && next.baseInput.trim()) {
|
|
2624
|
+
const parsed = parseBaseInput(next.baseInput)
|
|
2625
|
+
if (parsed.baseToken) next.baseToken = parsed.baseToken
|
|
2626
|
+
if (parsed.tableId) next.tableId = parsed.tableId
|
|
2627
|
+
}
|
|
2628
|
+
delete next.baseInput
|
|
2629
|
+
const settings = await writeSettings(config, next)
|
|
2630
|
+
return sendJson(res, 200, { settings })
|
|
2631
|
+
}
|
|
2632
|
+
|
|
2633
|
+
if (route === '/sources' && req.method === 'GET') {
|
|
2634
|
+
const settings = await readSettings(config)
|
|
2635
|
+
const detected = await loadRequirementSources(settings.projectDir)
|
|
2636
|
+
const names = (detected?.sources ?? []).map((item) => item.name)
|
|
2637
|
+
return sendJson(res, 200, {
|
|
2638
|
+
found: Boolean(detected),
|
|
2639
|
+
path: detected?.path ?? '',
|
|
2640
|
+
defaultSource: detected?.defaultSource ?? '',
|
|
2641
|
+
selected: names.includes(settings.sourceName) ? settings.sourceName : detected?.defaultSource ?? '',
|
|
2642
|
+
sources: (detected?.sources ?? []).map((item) => ({
|
|
2643
|
+
name: item.name,
|
|
2644
|
+
tableName: item.tableName ?? '',
|
|
2645
|
+
baseUrl: item.baseUrl ?? '',
|
|
2646
|
+
identity: item.identity ?? '',
|
|
2647
|
+
fields: item.fields ?? null,
|
|
2648
|
+
filter: item.filter ?? null,
|
|
2649
|
+
})),
|
|
2650
|
+
})
|
|
2651
|
+
}
|
|
2652
|
+
|
|
2653
|
+
if (route === '/fields' && req.method === 'GET') {
|
|
2654
|
+
const settings = await readSettings(config)
|
|
2655
|
+
const tableKey = url.searchParams.get('table')
|
|
2656
|
+
if (tableKey) {
|
|
2657
|
+
const { table } = await findTable(config, settings, tableKey)
|
|
2658
|
+
if (!table) return sendJson(res, 404, { error: '没有找到这张表' })
|
|
2659
|
+
return sendJson(res, 200, await fetchFieldSchema(config, settings, table))
|
|
2660
|
+
}
|
|
2661
|
+
return sendJson(res, 200, await fetchFieldSchema(config, settings))
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2664
|
+
if (route === '/tables' && req.method === 'GET') {
|
|
2665
|
+
const settings = await readSettings(config)
|
|
2666
|
+
const { tables, dropped } = await listTables(config, settings)
|
|
2667
|
+
return sendJson(res, 200, {
|
|
2668
|
+
projectDir: settings.projectDir,
|
|
2669
|
+
dropped,
|
|
2670
|
+
tables: tables.map((table) => ({
|
|
2671
|
+
key: table.key,
|
|
2672
|
+
label: table.label,
|
|
2673
|
+
kind: table.kind,
|
|
2674
|
+
sourceName: table.sourceName,
|
|
2675
|
+
tableName: table.tableName,
|
|
2676
|
+
tableId: table.tableId,
|
|
2677
|
+
identity: table.identity,
|
|
2678
|
+
configPath: table.configPath,
|
|
2679
|
+
fields: table.fieldMap,
|
|
2680
|
+
filter: table.filter,
|
|
2681
|
+
})),
|
|
2682
|
+
})
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
if (route === '/records' && req.method === 'GET') {
|
|
2686
|
+
const settings = await readSettings(config)
|
|
2687
|
+
const fresh = url.searchParams.get('fresh') === '1'
|
|
2688
|
+
const { table, tables } = await findTable(config, settings, url.searchParams.get('table'))
|
|
2689
|
+
if (!table) return sendJson(res, 200, { configured: false, items: [], message: '项目里还没有配到飞书表' })
|
|
2690
|
+
const payload = await fetchTableRecords(config, table, { fresh })
|
|
2691
|
+
if (!payload.ok) {
|
|
2692
|
+
return sendJson(res, 200, { configured: true, items: [], table: publicTable(table), error: payload.error, detail: payload.detail, command: payload.command })
|
|
2693
|
+
}
|
|
2694
|
+
const items = payload.records.map((record) => normalizeTableRecord(record, table.fieldMap))
|
|
2695
|
+
return sendJson(res, 200, {
|
|
2696
|
+
configured: true,
|
|
2697
|
+
table: publicTable(table),
|
|
2698
|
+
availableTables: tables.map((entry) => ({ key: entry.key, label: entry.label, kind: entry.kind })),
|
|
2699
|
+
items,
|
|
2700
|
+
count: items.length,
|
|
2701
|
+
fetchMode: payload.fetchMode,
|
|
2702
|
+
warning: payload.warning,
|
|
2703
|
+
})
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
if (route === '/overview' && req.method === 'GET') {
|
|
2707
|
+
const settings = await readSettings(config)
|
|
2708
|
+
const fresh = url.searchParams.get('fresh') === '1'
|
|
2709
|
+
const overview = await buildOverview(config, settings, { fresh })
|
|
2710
|
+
const runs = await readRuns(config)
|
|
2711
|
+
return sendJson(res, 200, { ...overview, runs })
|
|
2712
|
+
}
|
|
2713
|
+
|
|
2714
|
+
if (route === '/runs' && req.method === 'GET') {
|
|
2715
|
+
return sendJson(res, 200, { items: await readRuns(config) })
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
if (route === '/runs' && req.method === 'POST') {
|
|
2719
|
+
const body = await readBody(req)
|
|
2720
|
+
const title = String(body?.title ?? '').trim()
|
|
2721
|
+
if (!title) return sendJson(res, 400, { error: '缺少需求/任务标题' })
|
|
2722
|
+
const tableKey = String(body?.tableKey ?? '')
|
|
2723
|
+
const recordId = String(body?.recordId ?? '')
|
|
2724
|
+
const status = ['handed-off', 'in-progress', 'done', 'blocked'].includes(body?.status) ? body.status : 'handed-off'
|
|
2725
|
+
// 同一个任务只留一条:已经记过就更新那一条(刷新时间/项目/备注、次数 +1),不再追加新的。
|
|
2726
|
+
const existing = (await readRuns(config)).find((run) => runTaskKey(run) === runTaskKey({ tableKey, recordId, title, id: '' }))
|
|
2727
|
+
const event = existing
|
|
2728
|
+
? { type: 'regenerate', id: existing.id, at: new Date().toISOString(), title, projectDir: String(body?.projectDir ?? ''), note: String(body?.note ?? '') }
|
|
2729
|
+
: {
|
|
2730
|
+
type: 'create',
|
|
2731
|
+
id: `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
|
2732
|
+
at: new Date().toISOString(),
|
|
2733
|
+
tableKey,
|
|
2734
|
+
recordId,
|
|
2735
|
+
title,
|
|
2736
|
+
projectDir: String(body?.projectDir ?? ''),
|
|
2737
|
+
status,
|
|
2738
|
+
note: String(body?.note ?? ''),
|
|
2739
|
+
}
|
|
2740
|
+
await appendRun(config, event)
|
|
2741
|
+
const items = await readRuns(config)
|
|
2742
|
+
return sendJson(res, 200, {
|
|
2743
|
+
ok: true,
|
|
2744
|
+
regenerated: Boolean(existing),
|
|
2745
|
+
run: items.find((run) => run.id === (existing ? existing.id : event.id)) ?? event,
|
|
2746
|
+
items,
|
|
2747
|
+
})
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2750
|
+
if (route === '/runs/status' && req.method === 'POST') {
|
|
2751
|
+
const body = await readBody(req)
|
|
2752
|
+
const id = String(body?.id ?? '').trim()
|
|
2753
|
+
const status = String(body?.status ?? '').trim()
|
|
2754
|
+
if (!id || !['handed-off', 'in-progress', 'done', 'blocked'].includes(status)) {
|
|
2755
|
+
return sendJson(res, 400, { error: '缺少执行记录 id 或状态不合法' })
|
|
2756
|
+
}
|
|
2757
|
+
await appendRun(config, { type: 'update', id, at: new Date().toISOString(), status, note: String(body?.note ?? '') })
|
|
2758
|
+
return sendJson(res, 200, { ok: true, items: await readRuns(config) })
|
|
2759
|
+
}
|
|
2760
|
+
|
|
2761
|
+
if (route === '/view' && req.method === 'GET') {
|
|
2762
|
+
return sendJson(res, 200, { view: await readView(config) })
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2765
|
+
if (route === '/view' && req.method === 'POST') {
|
|
2766
|
+
const body = await readBody(req)
|
|
2767
|
+
return sendJson(res, 200, { view: await writeView(config, body) })
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
if (route === '/requirements' && req.method === 'GET') {
|
|
2771
|
+
const settings = await readSettings(config)
|
|
2772
|
+
const tableKey = url.searchParams.get('table')
|
|
2773
|
+
if (!tableKey) return sendJson(res, 200, await fetchRequirements(config, settings))
|
|
2774
|
+
const fresh = url.searchParams.get('fresh') === '1'
|
|
2775
|
+
const { table, tables } = await findTable(config, settings, tableKey)
|
|
2776
|
+
if (!table) return sendJson(res, 200, { configured: false, items: [], message: '没有找到这张表(项目里还没配到)' })
|
|
2777
|
+
const payload = await fetchTableRecords(config, table, { fresh })
|
|
2778
|
+
if (!payload.ok) {
|
|
2779
|
+
return sendJson(res, 200, { configured: true, items: [], source: publicTable(table), error: payload.error, detail: payload.detail, command: payload.command })
|
|
2780
|
+
}
|
|
2781
|
+
const items = payload.records.map((record) => normalizeTableRecord(record, table.fieldMap))
|
|
2782
|
+
return sendJson(res, 200, {
|
|
2783
|
+
configured: true,
|
|
2784
|
+
source: publicTable(table),
|
|
2785
|
+
availableTables: tables.map((entry) => ({ key: entry.key, label: entry.label, kind: entry.kind })),
|
|
2786
|
+
items,
|
|
2787
|
+
count: items.length,
|
|
2788
|
+
fetchMode: payload.fetchMode,
|
|
2789
|
+
warning: payload.warning,
|
|
2790
|
+
})
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
if (route === '/requirement/status' && req.method === 'POST') {
|
|
2794
|
+
const settings = await readSettings(config)
|
|
2795
|
+
const body = await readBody(req)
|
|
2796
|
+
const result = await updateRequirementStatus(config, settings, body)
|
|
2797
|
+
return sendJson(res, result.ok ? 200 : 502, result)
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
if (route === '/skills' && req.method === 'GET') {
|
|
2801
|
+
const settings = await readSettings(config)
|
|
2802
|
+
return sendJson(res, 200, await listSkills(config, settings))
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
if (route === '/skills/create' && req.method === 'POST') {
|
|
2806
|
+
const settings = await readSettings(config)
|
|
2807
|
+
const body = await readBody(req)
|
|
2808
|
+
const result = await createSkill(config, settings, body)
|
|
2809
|
+
return sendJson(res, result.ok ? 200 : 400, result)
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
if (route === '/experts' && req.method === 'GET') {
|
|
2813
|
+
const settings = await readSettings(config)
|
|
2814
|
+
return sendJson(res, 200, await listExperts(config, settings))
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
// 对话输入框那个「+ 专家」入口知道自己是哪个会话(宿主 slot 会给 sessionId),
|
|
2818
|
+
// 工作台要「把养专家的指令发进当前对话」就得先知道会话是谁:入口上报、面板取用。
|
|
2819
|
+
if (route === '/composer/session' && req.method === 'POST') {
|
|
2820
|
+
const body = await readBody(req)
|
|
2821
|
+
const sessionId = String(body?.sessionId ?? '').trim().slice(0, 200)
|
|
2822
|
+
if (sessionId) composerSession = { id: sessionId, at: Date.now() }
|
|
2823
|
+
return sendJson(res, 200, { ok: true, sessionId: composerSession.id })
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
if (route === '/composer/session' && req.method === 'GET') {
|
|
2827
|
+
return sendJson(res, 200, { ok: true, sessionId: composerSession.id, at: composerSession.at })
|
|
2828
|
+
}
|
|
2829
|
+
|
|
2830
|
+
if (route === '/expert/create' && req.method === 'POST') {
|
|
2831
|
+
const settings = await readSettings(config)
|
|
2832
|
+
const body = await readBody(req)
|
|
2833
|
+
const result = await createExpert(config, settings, body)
|
|
2834
|
+
return sendJson(res, result.ok ? 200 : 400, result)
|
|
2835
|
+
}
|
|
2836
|
+
|
|
2837
|
+
if (route === '/team/create' && req.method === 'POST') {
|
|
2838
|
+
const settings = await readSettings(config)
|
|
2839
|
+
const body = await readBody(req)
|
|
2840
|
+
const result = await createTeam(config, settings, body)
|
|
2841
|
+
return sendJson(res, result.ok ? 200 : 400, result)
|
|
2842
|
+
}
|
|
2843
|
+
|
|
2844
|
+
// 页面里「AI 直接创建」:调宿主 llm 服务拿结构化草稿,再由工作台落盘,不经过对话。
|
|
2845
|
+
if (route === '/ai/create' && req.method === 'POST') {
|
|
2846
|
+
const settings = await readSettings(config)
|
|
2847
|
+
const body = await readBody(req)
|
|
2848
|
+
const result = await aiCreateDraft(ctx, config, settings, body)
|
|
2849
|
+
return sendJson(res, result.ok ? 200 : 400, result)
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
if (route === '/skill' && req.method === 'GET') {
|
|
2853
|
+
const settings = await readSettings(config)
|
|
2854
|
+
const result = await readSkillFile(config, settings, url.searchParams.get('path'))
|
|
2855
|
+
return sendJson(res, result.ok ? 200 : 404, result)
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
/* ------------------------------------------- 飞书文档(文档信息) */
|
|
2859
|
+
|
|
2860
|
+
if (route === '/docs' && req.method === 'GET') {
|
|
2861
|
+
return sendJson(res, 200, { items: await readDocs(config) })
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
if (route === '/doc' && req.method === 'GET') {
|
|
2865
|
+
const result = await readDocContent(config, url.searchParams.get('id'))
|
|
2866
|
+
return sendJson(res, result.ok ? 200 : 404, result)
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
if (route === '/doc/fetch' && req.method === 'POST') {
|
|
2870
|
+
const body = await readBody(req)
|
|
2871
|
+
const result = await fetchFeishuDoc(config, body)
|
|
2872
|
+
return sendJson(res, result.ok ? 200 : 502, result)
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
if (route === '/doc/remove' && req.method === 'POST') {
|
|
2876
|
+
const body = await readBody(req)
|
|
2877
|
+
return sendJson(res, 200, await removeDoc(config, body?.id))
|
|
2878
|
+
}
|
|
2879
|
+
|
|
2880
|
+
/* --------------------------------------- 专家团全流程(流水线) */
|
|
2881
|
+
|
|
2882
|
+
if (route === '/flows' && req.method === 'GET') {
|
|
2883
|
+
return sendJson(res, 200, {
|
|
2884
|
+
items: await readFlows(config),
|
|
2885
|
+
stages: FLOW_STAGES,
|
|
2886
|
+
statuses: FLOW_STATUS,
|
|
2887
|
+
evidenceKinds: FLOW_EVIDENCE_KINDS,
|
|
2888
|
+
})
|
|
2889
|
+
}
|
|
2890
|
+
|
|
2891
|
+
if (route === '/flows' && req.method === 'POST') {
|
|
2892
|
+
const body = await readBody(req)
|
|
2893
|
+
const title = String(body?.title ?? '').trim()
|
|
2894
|
+
if (!title) return sendJson(res, 400, { error: '缺一条任务/需求,先选一条再开始全流程' })
|
|
2895
|
+
const team = String(body?.team ?? '').trim()
|
|
2896
|
+
const stages = (Array.isArray(body?.stages) && body.stages.length ? body.stages : FLOW_STAGES.map((stage) => stage.id)).map(String)
|
|
2897
|
+
const event = {
|
|
2898
|
+
type: 'create',
|
|
2899
|
+
id: `flow-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
|
|
2900
|
+
at: new Date().toISOString(),
|
|
2901
|
+
recordId: String(body?.recordId ?? ''),
|
|
2902
|
+
tableKey: String(body?.tableKey ?? ''),
|
|
2903
|
+
title,
|
|
2904
|
+
team,
|
|
2905
|
+
teamName: String(body?.teamName ?? ''),
|
|
2906
|
+
teamMode: body?.teamMode === true || body?.teamMode === 'true',
|
|
2907
|
+
stages,
|
|
2908
|
+
}
|
|
2909
|
+
await appendFlow(config, event)
|
|
2910
|
+
return sendJson(res, 200, { ok: true, flow: event, items: await readFlows(config) })
|
|
2911
|
+
}
|
|
2912
|
+
|
|
2913
|
+
if (route === '/flows/stage' && req.method === 'POST') {
|
|
2914
|
+
const body = await readBody(req)
|
|
2915
|
+
const id = String(body?.id ?? '').trim()
|
|
2916
|
+
const stage = String(body?.stage ?? '').trim()
|
|
2917
|
+
const status = String(body?.status ?? '').trim()
|
|
2918
|
+
if (!id || !stage) return sendJson(res, 400, { error: '缺少流水线 id 或阶段 id' })
|
|
2919
|
+
if (status && !FLOW_STATUS_IDS.includes(status)) return sendJson(res, 400, { error: `阶段状态不合法:${status}` })
|
|
2920
|
+
// 不变式:done 必然有凭据。前端漏判时这里兜底降级,免得台账里出现「没凭据的已完成」。
|
|
2921
|
+
let nextStatus = status
|
|
2922
|
+
if (status === 'done') {
|
|
2923
|
+
const current = (await readFlows(config)).find((flow) => flow.id === id)
|
|
2924
|
+
const target = current?.stages.find((entry) => entry.id === stage)
|
|
2925
|
+
if (!(target?.evidence?.length)) nextStatus = 'done_unverified'
|
|
2926
|
+
}
|
|
2927
|
+
await appendFlow(config, {
|
|
2928
|
+
type: 'stage',
|
|
2929
|
+
id,
|
|
2930
|
+
at: new Date().toISOString(),
|
|
2931
|
+
stage,
|
|
2932
|
+
status: nextStatus || undefined,
|
|
2933
|
+
note: body?.note === undefined ? undefined : String(body.note),
|
|
2934
|
+
})
|
|
2935
|
+
return sendJson(res, 200, { ok: true, downgraded: nextStatus !== status, items: await readFlows(config) })
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
if (route === '/flows/evidence' && req.method === 'POST') {
|
|
2939
|
+
const body = await readBody(req)
|
|
2940
|
+
const id = String(body?.id ?? '').trim()
|
|
2941
|
+
const stage = String(body?.stage ?? '').trim()
|
|
2942
|
+
const kind = String(body?.kind ?? '').trim() || 'command'
|
|
2943
|
+
const summary = String(body?.summary ?? '').trim()
|
|
2944
|
+
if (!id || !stage) return sendJson(res, 400, { error: '缺少流水线 id 或阶段 id' })
|
|
2945
|
+
if (!FLOW_EVIDENCE_KIND_IDS.includes(kind)) return sendJson(res, 400, { error: `凭据类型不合法:${kind}` })
|
|
2946
|
+
if (!summary) {
|
|
2947
|
+
return sendJson(res, 400, {
|
|
2948
|
+
error: '凭据不能为空:一句「已完成」不算凭据,写清楚改了什么 / 跑了什么命令 / 结果如何',
|
|
2949
|
+
})
|
|
2950
|
+
}
|
|
2951
|
+
await appendFlow(config, {
|
|
2952
|
+
type: 'evidence',
|
|
2953
|
+
id,
|
|
2954
|
+
at: new Date().toISOString(),
|
|
2955
|
+
stage,
|
|
2956
|
+
kind,
|
|
2957
|
+
summary: summary.slice(0, EVIDENCE_MAX_CHARS),
|
|
2958
|
+
ref: String(body?.ref ?? '').slice(0, 300),
|
|
2959
|
+
})
|
|
2960
|
+
return sendJson(res, 200, { ok: true, items: await readFlows(config) })
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
if (route === '/flows/evidence/remove' && req.method === 'POST') {
|
|
2964
|
+
const body = await readBody(req)
|
|
2965
|
+
const id = String(body?.id ?? '').trim()
|
|
2966
|
+
const stage = String(body?.stage ?? '').trim()
|
|
2967
|
+
const targetAt = String(body?.at ?? '').trim()
|
|
2968
|
+
if (!id || !stage || !targetAt) return sendJson(res, 400, { error: '缺少流水线 id、阶段 id 或凭据时间' })
|
|
2969
|
+
await appendFlow(config, { type: 'evidence-remove', id, at: new Date().toISOString(), stage, targetAt })
|
|
2970
|
+
return sendJson(res, 200, { ok: true, items: await readFlows(config) })
|
|
2971
|
+
}
|
|
2972
|
+
|
|
2973
|
+
if (route === '/flows/remove' && req.method === 'POST') {
|
|
2974
|
+
const body = await readBody(req)
|
|
2975
|
+
const id = String(body?.id ?? '').trim()
|
|
2976
|
+
if (!id) return sendJson(res, 400, { error: '缺少流水线 id' })
|
|
2977
|
+
await appendFlow(config, { type: 'remove', id, at: new Date().toISOString() })
|
|
2978
|
+
return sendJson(res, 200, { ok: true, items: await readFlows(config) })
|
|
2979
|
+
}
|
|
2980
|
+
|
|
2981
|
+
/* --------------------------------------- 本机目录浏览(选项目目录) */
|
|
2982
|
+
|
|
2983
|
+
if (route === '/fs/list' && req.method === 'GET') {
|
|
2984
|
+
const target = String(url.searchParams.get('path') ?? '').trim()
|
|
2985
|
+
return sendJson(res, 200, await listDirectories(target))
|
|
2986
|
+
}
|
|
2987
|
+
|
|
2988
|
+
/* --------------------------------------- 项目里 skill 产出的 spec 文档 */
|
|
2989
|
+
|
|
2990
|
+
if (route === '/spec-scan' && req.method === 'GET') {
|
|
2991
|
+
const settings = await readSettings(config)
|
|
2992
|
+
const listing = await listSpecFiles(config, settings)
|
|
2993
|
+
return sendJson(res, 200, listing)
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
if (route === '/spec-read' && req.method === 'POST') {
|
|
2997
|
+
const body = await readBody(req)
|
|
2998
|
+
const settings = await readSettings(config)
|
|
2999
|
+
const target = String(body?.path ?? '').trim()
|
|
3000
|
+
if (!target) return sendJson(res, 400, { error: '缺少 spec 文件路径' })
|
|
3001
|
+
const result = await readSpecFile(config, settings, target)
|
|
3002
|
+
return sendJson(res, result.ok ? 200 : 400, result)
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
/* --------------------------------------- 更新日志(包内 CHANGELOG.md) */
|
|
3006
|
+
|
|
3007
|
+
if (route === '/changelog' && req.method === 'GET') {
|
|
3008
|
+
return sendJson(res, 200, await readChangelog())
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
return sendJson(res, 404, { error: `未知接口 ${route}` })
|
|
3012
|
+
} catch (error) {
|
|
3013
|
+
return sendJson(res, 500, { error: String(error?.message ?? error) })
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: API_PREFIX, handler }))
|
|
3018
|
+
}
|