lantern-harness 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/builtin/session/lh-nav-groups.mjs +55 -17
  3. package/cli/server.mjs +2 -0
  4. package/config/app.defaults.json +1 -0
  5. package/dist/500.html +52 -4
  6. package/dist/_astro/Base.UUIdmKid.css +1 -0
  7. package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.CvbRi7Tl.js → Base.astro_astro_type_script_index_0_lang.DSWudA4D.js} +1 -1
  8. package/dist/_astro/{CaseExecBoard.Dttqp0wg.js → CaseExecBoard.D8K4NzrB.js} +1 -1
  9. package/dist/_astro/CaseGenerateApp.bZ_K72NQ.js +9 -0
  10. package/dist/_astro/{CasesLibrary.8aMUUGp_.js → CasesLibrary.Dhg2pdwU.js} +1 -1
  11. package/dist/_astro/ChatApp.B6I3gGKI.js +221 -0
  12. package/dist/_astro/{ConfirmDialog.BZzZWDci.js → ConfirmDialog.CsMwWevK.js} +1 -1
  13. package/dist/_astro/{DashboardBoard.CkSbhEDI.js → DashboardBoard.uPjTYpJZ.js} +1 -1
  14. package/dist/_astro/{DocsFileBrowser.MKVCfZrE.js → DocsFileBrowser.DvBPLCEp.js} +1 -1
  15. package/dist/_astro/{DocsPager.DJY4foYL.js → DocsPager.EPT5-oEx.js} +1 -1
  16. package/dist/_astro/{DrawerField.CHRg77LG.js → DrawerField.DqvXFCFh.js} +1 -1
  17. package/dist/_astro/{ExcelFieldTags.DXMeaDa5.js → ExcelFieldTags.De-C3dqn.js} +1 -1
  18. package/dist/_astro/{KnowledgeLibrary.B-p1aoQN.js → KnowledgeLibrary.BzFTmNwA.js} +1 -1
  19. package/dist/_astro/{NamePromptDialog.Wa9O530a.js → NamePromptDialog.CS1pTTVl.js} +1 -1
  20. package/dist/_astro/{NavLibraries.C6LImMO_.js → NavLibraries.CVdolwYy.js} +1 -1
  21. package/dist/_astro/PluginsPage.B8U4uvD2.js +39 -0
  22. package/dist/_astro/{PluginsPage.DkmRPfbU.js → PluginsPage.v6afs984.js} +1 -1
  23. package/dist/_astro/{PmBugsBoard.CMT4-eoB.js → PmBugsBoard.CSIGq0wz.js} +1 -1
  24. package/dist/_astro/{PmIterationsBoard.BQM_dzdZ.js → PmIterationsBoard.BmBc90as.js} +1 -1
  25. package/dist/_astro/{PmProjectDetail.CzU80pat.js → PmProjectDetail.BDKXOQJD.js} +1 -1
  26. package/dist/_astro/{PmProjectsBoard.Cxsa7SYQ.js → PmProjectsBoard.DIVs_xJu.js} +1 -1
  27. package/dist/_astro/{PmRequirementsBoard.4_JMDDN0.js → PmRequirementsBoard.DcLiUhBe.js} +1 -1
  28. package/dist/_astro/PmRequirementsBoard.N0LM5jHo.js +1 -0
  29. package/dist/_astro/PmShared.D69sPvec.js +1 -0
  30. package/dist/_astro/PromptsLibrary.B1RVZqj8.js +1 -0
  31. package/dist/_astro/{ReportsPage.Fh5DRKLT.js → ReportsPage.N1EaH8E-.js} +1 -1
  32. package/dist/_astro/ReqAnalysisBoard.BIIUqGVh.js +25 -0
  33. package/dist/_astro/{RequirementsLibrary.CBkuWE8X.js → RequirementsLibrary.BZhxG9VU.js} +1 -1
  34. package/dist/_astro/SearchableSelect.BIjXzTPD.js +1 -0
  35. package/dist/_astro/SelectDropdown.B3-XpBpn.js +1 -0
  36. package/dist/_astro/{SettingsDialog.CVB5Gtk4.js → SettingsDialog.DILea5eO.js} +1 -1
  37. package/dist/_astro/SlideOverDrawer.HqVYaIjP.js +1 -0
  38. package/dist/_astro/{SpaceSwitcher.BVQLt_tL.js → SpaceSwitcher.BeCumAuj.js} +1 -1
  39. package/dist/_astro/{TasksBoard.Bu-fpIZ7.js → TasksBoard.B3SzQ5bR.js} +1 -1
  40. package/dist/_astro/{TemplatesLibrary.DSylQGlN.js → TemplatesLibrary.Ci3yHQTr.js} +1 -1
  41. package/dist/_astro/{TestStatsBoard.CPyKW4wc.js → TestStatsBoard.CgVvwMzN.js} +1 -1
  42. package/dist/_astro/{TodosBoard.8kvRTEW-.js → TodosBoard.BNDF1iVZ.js} +1 -1
  43. package/dist/_astro/UiAutoBoard.BNLRrunE.js +9 -0
  44. package/dist/_astro/app-config.Cq_F8I0l.js +1 -0
  45. package/dist/_astro/dialog.DZHZCe_T.js +1 -0
  46. package/dist/_astro/{hydrate-cache.BXX604Bw.js → hydrate-cache.zljz1n5X.js} +1 -1
  47. package/dist/_astro/i18n.DPw-aTIZ.js +7 -0
  48. package/dist/_astro/index.astro_astro_type_script_index_0_lang.B9YrqBHf.js +1 -0
  49. package/dist/_astro/{lib.CgXLzMMd.js → lib.BQbwbnfE.js} +1 -1
  50. package/dist/_astro/listbox.DNxAJmEo.js +1 -0
  51. package/dist/_astro/menu.Dnrpz489.js +1 -0
  52. package/dist/_astro/{open-docs-in-session.CyFNgh1I.js → open-docs-in-session.LWVC43xp.js} +1 -1
  53. package/dist/_astro/{plugins.C2BMfzv1.js → plugins.CKkgnq4r.js} +1 -1
  54. package/dist/_astro/{portal.C0hAhXDF.js → portal.Chh6O5xk.js} +2 -2
  55. package/dist/_astro/prompts-meta.D_2wiFiH.js +2 -0
  56. package/dist/_astro/req-analysis.C1uUndMm.js +6 -0
  57. package/dist/_astro/{settings.Ceefeil5.js → settings.HM3DiNh0.js} +2 -2
  58. package/dist/_astro/{spaces-client.BocUabwy.js → spaces-client.CWqBZccW.js} +1 -1
  59. package/dist/_astro/ui-auto-prompt.B09MVaTI.js +4 -0
  60. package/dist/_astro/{update.CtF8vsag.js → update.BSnBvaFF.js} +1 -1
  61. package/dist/_astro/{use-text-value.DBQvHeNl.js → use-text-value.B3mOiuGb.js} +1 -1
  62. package/dist/_astro/{view-prefs.BEAZRcxF.js → view-prefs.7wGuDpzi.js} +1 -1
  63. package/dist/case-exec/index.html +83 -5
  64. package/dist/cases/generate/index.html +53 -5
  65. package/dist/cases/library/index.html +83 -5
  66. package/dist/dashboard/index.html +83 -5
  67. package/dist/docs/changelog/index.html +86 -5
  68. package/dist/docs/install/index.html +52 -4
  69. package/dist/docs/manual/index.html +82 -6
  70. package/dist/index.html +1 -1
  71. package/dist/knowledge/index.html +83 -5
  72. package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +52 -4
  73. package/dist/plugins/index.html +53 -5
  74. package/dist/pm/bugs/index.html +83 -5
  75. package/dist/pm/iterations/index.html +83 -5
  76. package/dist/pm/projects/detail/index.html +83 -5
  77. package/dist/pm/projects/index.html +83 -5
  78. package/dist/pm/requirements/index.html +83 -5
  79. package/dist/prompts/index.html +83 -5
  80. package/dist/reports/index.html +83 -5
  81. package/dist/requirement-analysis/index.html +795 -0
  82. package/dist/requirements/index.html +83 -5
  83. package/dist/tasks/index.html +83 -5
  84. package/dist/templates/index.html +83 -5
  85. package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +52 -4
  86. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +52 -4
  87. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +52 -4
  88. package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +52 -4
  89. package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +52 -4
  90. package/dist/test-automation/index.html +83 -5
  91. package/dist/test-stats/index.html +83 -5
  92. package/dist/todos/index.html +83 -5
  93. package/dist/workbench/index.html +53 -5
  94. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +24 -2
  95. package/lh-plugins/lh-req-analysis.mjs +672 -0
  96. package/lh-plugins/plugin-prompts.mjs +2 -0
  97. package/lh-plugins/req-analysis-prompt.mjs +118 -0
  98. package/package.json +1 -1
  99. package/dist/_astro/Base.Bgxs1QQl.css +0 -1
  100. package/dist/_astro/CaseGenerateApp.DqW_nWMc.js +0 -9
  101. package/dist/_astro/ChatApp.BLxf0h1d.js +0 -219
  102. package/dist/_astro/PluginsPage.-97n3x2U.js +0 -39
  103. package/dist/_astro/PmRequirementsBoard.B8HL07cw.js +0 -1
  104. package/dist/_astro/PmShared.Ca2Ao7v_.js +0 -1
  105. package/dist/_astro/PromptsLibrary.C9BcIxKK.js +0 -1
  106. package/dist/_astro/SearchableSelect.DnjoSslK.js +0 -1
  107. package/dist/_astro/SelectDropdown.CuuDHa8s.js +0 -1
  108. package/dist/_astro/SlideOverDrawer.B7B5Wu8I.js +0 -1
  109. package/dist/_astro/UiAutoBoard.DFTiDqCp.js +0 -9
  110. package/dist/_astro/active-element-history.CED-m1Zp.js +0 -1
  111. package/dist/_astro/app-config.BUPzGl9f.js +0 -1
  112. package/dist/_astro/dialog.BAPTk9a_.js +0 -1
  113. package/dist/_astro/i18n.BGPnP1Bg.js +0 -7
  114. package/dist/_astro/index.astro_astro_type_script_index_0_lang.LPL9mPQY.js +0 -1
  115. package/dist/_astro/listbox.C96OCanh.js +0 -1
  116. package/dist/_astro/menu.IPWdRoNM.js +0 -1
  117. package/dist/_astro/prompts-meta.Bua-j14I.js +0 -2
  118. package/dist/_astro/ui-auto-prompt.CX8fju7r.js +0 -3
  119. package/dist/_astro/use-tree-walker.DFU2AaAP.js +0 -1
@@ -0,0 +1,672 @@
1
+ /**
2
+ * 需求分析存储(空间级):`<当前数据空间>/需求分析/需求分析.json`。
3
+ *
4
+ * 一次分析 = 一份文档:来源需求文档的路径 / 指纹、抽出的需求条目、拆出的用户故事、
5
+ * 最近一次体检报告。目录只在真的有数据时创建(第一次保存时),与其它空间插件一致。
6
+ *
7
+ * 编号(US-001)由服务端按 `storySeq` 递增分配,删除后不回收;
8
+ * 需求条目(RO-1)由前端按批次生成,服务端只做去重与合法性校验。
9
+ * 所有枚举与字段白名单都在这里做一次,前端与 AI 工具只提交白名单字段。
10
+ */
11
+ import crypto from 'node:crypto';
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
16
+ import { resolveContentRoot } from '../builtin/session/space-layout.mjs';
17
+ import { ensurePluginPrompt, isPluginOnInSpace, readPluginPrompt } from './plugin-prompts.mjs';
18
+ import {
19
+ REQ_ANALYSIS_PROMPT_FILE,
20
+ REQ_ANALYSIS_PROMPT_TEMPLATE,
21
+ parseReqPromptSections,
22
+ } from './req-analysis-prompt.mjs';
23
+
24
+ const PREFIX = '/__tb_reqanalysis';
25
+ const VERSION = 1;
26
+
27
+ /** 固定数据目录:与导航分组同名时会被改名,需登记到 lh-nav-groups 的 SKIP_DIR_NAMES */
28
+ export const REQ_ANALYSIS_DIR_NAME = '需求分析';
29
+ export const REQ_ANALYSIS_STORE_FILE = '需求分析.json';
30
+
31
+ export const REQ_DOC_STATUSES = ['draft', 'decomposed', 'checked', 'accepted'];
32
+ export const STORY_PRIORITIES = ['P0', 'P1', 'P2'];
33
+ /** 体检缺口类型:规则侧与模型侧共用同一套 */
34
+ export const GAP_TYPES = [
35
+ 'uncovered-outline',
36
+ 'missing-field',
37
+ 'missing-scenario',
38
+ 'missing-dimension',
39
+ 'untestable-acceptance',
40
+ 'conflict',
41
+ 'over-split',
42
+ 'other',
43
+ ];
44
+ export const GAP_SEVERITIES = ['high', 'medium', 'low'];
45
+ export const GAP_ORIGINS = ['rule', 'model'];
46
+ export const CHECK_STAGES = ['idle', 'outline', 'stories', 'audit', 'done'];
47
+
48
+ /** 数据文件路径:只算路径,不建目录 */
49
+ export function reqAnalysisStorePath(spaceDir) {
50
+ return path.join(path.resolve(spaceDir), REQ_ANALYSIS_DIR_NAME, REQ_ANALYSIS_STORE_FILE);
51
+ }
52
+
53
+ /* ------------------------ 来源需求文档(只读) ------------------------ */
54
+
55
+ /** 需求文档库目录名:来源文档都从这里读,不写回 */
56
+ const REQ_DOCS_DIR_NAME = '需求文档库';
57
+
58
+ /** 能直接当正文读的纯文本格式 */
59
+ export const REQ_SOURCE_TEXT_EXTS = ['.md', '.markdown', '.txt', '.csv'];
60
+ /** 需要抽文本的格式(Word / Excel) */
61
+ export const REQ_SOURCE_OFFICE_EXTS = ['.docx', '.xlsx', '.xls'];
62
+ /** 页面里会列出来、但暂时不能拆解的格式(只给提示) */
63
+ export const REQ_SOURCE_UNSUPPORTED_EXTS = ['.doc', '.pdf', '.pptx', '.ppt'];
64
+ export const REQ_SOURCE_EXTS = [
65
+ ...REQ_SOURCE_TEXT_EXTS,
66
+ ...REQ_SOURCE_OFFICE_EXTS,
67
+ ...REQ_SOURCE_UNSUPPORTED_EXTS,
68
+ ];
69
+
70
+ /** 单份来源文档抽取后的正文字数上限:超长文档按章节切批,没必要把整本塞进来 */
71
+ const MAX_SOURCE_CHARS = 600_000;
72
+
73
+ function sourceExt(rel) {
74
+ return path.extname(String(rel ?? '')).toLowerCase();
75
+ }
76
+
77
+ /** 需求文档库的绝对目录(只算路径,可能还不存在) */
78
+ export function reqDocsDir(spaceDir) {
79
+ return resolveContentRoot(spaceDir, REQ_DOCS_DIR_NAME).abs;
80
+ }
81
+
82
+ /**
83
+ * Word(docx)正文抽取:按段落 + 表格拼成纯文本。
84
+ * 标题层级压成 `#` / `##`,方便前端按 `^## ` 切分章节。
85
+ */
86
+ async function extractDocx(fileAbs) {
87
+ const { default: mammoth } = await import('mammoth');
88
+ // 传 buffer 而不是路径:数据空间路径常带中文,交给库自己拼路径容易读不到
89
+ const { value } = await mammoth.extractRawText({ buffer: fs.readFileSync(fileAbs) });
90
+ const lines = String(value ?? '')
91
+ .replace(/\r\n?/g, '\n')
92
+ .split('\n')
93
+ .map((line) => line.trim())
94
+ .filter((line, index, all) => line || all[index - 1]);
95
+ return lines.join('\n').trim();
96
+ }
97
+
98
+ /** Excel 正文抽取:每个工作表一个 `## 工作表名` 章节 + CSV 正文 */
99
+ async function extractSheet(fileAbs) {
100
+ const { default: xlsx } = await import('xlsx');
101
+ const book = xlsx.read(fs.readFileSync(fileAbs), { type: 'buffer', cellDates: true });
102
+ const parts = [];
103
+ for (const name of book.SheetNames) {
104
+ const csv = xlsx.utils.sheet_to_csv(book.Sheets[name], { blankrows: false });
105
+ const body = String(csv ?? '').trim();
106
+ if (!body) continue;
107
+ parts.push(`## ${name}\n\n${body}`);
108
+ }
109
+ return parts.join('\n\n').trim();
110
+ }
111
+
112
+ /**
113
+ * 读一份来源需求文档的正文。
114
+ * 只读:不落 .extracted.md、不改需求文档库;返回 `{ content, format }`。
115
+ */
116
+ export async function readReqSourceFile(spaceDir, rel) {
117
+ const raw = String(rel ?? '')
118
+ .replace(/\\/g, '/')
119
+ .trim();
120
+ if (!raw || raw.includes('\0') || raw.split('/').includes('..')) {
121
+ throw Object.assign(new Error('非法的来源文档路径'), { statusCode: 400 });
122
+ }
123
+ const root = path.resolve(reqDocsDir(spaceDir));
124
+ const abs = path.resolve(root, raw);
125
+ if (abs !== root && !abs.startsWith(root + path.sep)) {
126
+ throw Object.assign(new Error('来源文档越界'), { statusCode: 403 });
127
+ }
128
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
129
+ throw Object.assign(new Error(`来源文档不存在:${raw}`), { statusCode: 404 });
130
+ }
131
+ const ext = sourceExt(abs);
132
+ if (REQ_SOURCE_UNSUPPORTED_EXTS.includes(ext)) {
133
+ throw Object.assign(
134
+ new Error(`${ext} 暂不支持拆解,请先另存为 Word(.docx)/ Excel(.xlsx)或 Markdown`),
135
+ { statusCode: 415 },
136
+ );
137
+ }
138
+ let content = '';
139
+ try {
140
+ if (REQ_SOURCE_OFFICE_EXTS.includes(ext)) {
141
+ content = ext === '.docx' ? await extractDocx(abs) : await extractSheet(abs);
142
+ } else if (REQ_SOURCE_TEXT_EXTS.includes(ext)) {
143
+ content = fs.readFileSync(abs, 'utf8');
144
+ } else {
145
+ throw Object.assign(new Error(`不支持的来源格式:${ext || '(无扩展名)'}`), {
146
+ statusCode: 415,
147
+ });
148
+ }
149
+ } catch (err) {
150
+ if (err?.statusCode) throw err;
151
+ throw Object.assign(new Error(`读取来源文档失败:${err?.message ?? err}`), { statusCode: 500 });
152
+ }
153
+ const trimmed = String(content ?? '')
154
+ .replace(/\r\n?/g, '\n')
155
+ .trim();
156
+ if (!trimmed) {
157
+ throw Object.assign(new Error('来源文档没有可读文本(可能是扫描件或空文件)'), {
158
+ statusCode: 422,
159
+ });
160
+ }
161
+ return {
162
+ content: trimmed.length > MAX_SOURCE_CHARS ? trimmed.slice(0, MAX_SOURCE_CHARS) : trimmed,
163
+ format: ext.replace(/^\./, ''),
164
+ chars: trimmed.length,
165
+ truncated: trimmed.length > MAX_SOURCE_CHARS,
166
+ };
167
+ }
168
+
169
+ function sendJson(res, status, body) {
170
+ res.statusCode = status;
171
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
172
+ res.end(JSON.stringify(body));
173
+ }
174
+
175
+ function readBody(req) {
176
+ return new Promise((resolve, reject) => {
177
+ const chunks = [];
178
+ let size = 0;
179
+ req.on('data', (c) => {
180
+ size += c.length;
181
+ // 需求正文 / 故事集可能不小,但 8MB 足够;超出直接拒绝,避免把内存撑爆
182
+ if (size > 8 * 1024 * 1024) {
183
+ reject(badRequest('提交内容太大(上限 8MB)'));
184
+ req.destroy();
185
+ return;
186
+ }
187
+ chunks.push(c);
188
+ });
189
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
190
+ req.on('error', reject);
191
+ });
192
+ }
193
+
194
+ function badRequest(message) {
195
+ const err = new Error(message);
196
+ err.statusCode = 400;
197
+ return err;
198
+ }
199
+
200
+ function newId(prefix) {
201
+ return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
202
+ }
203
+
204
+ function text(value, max = 2000) {
205
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
206
+ }
207
+
208
+ function oneOf(value, allowed, fallback) {
209
+ const s = text(value, 40);
210
+ return allowed.includes(s) ? s : fallback;
211
+ }
212
+
213
+ function list(value, max = 30, itemMax = 500) {
214
+ if (!Array.isArray(value)) return [];
215
+ return value
216
+ .map((x) => text(x, itemMax))
217
+ .filter(Boolean)
218
+ .slice(0, max);
219
+ }
220
+
221
+ /* ------------------------------ 故事 ------------------------------ */
222
+
223
+ function mainFlowSteps(raw) {
224
+ if (!Array.isArray(raw)) return [];
225
+ const out = [];
226
+ for (const item of raw.slice(0, 40)) {
227
+ if (!item || typeof item !== 'object') continue;
228
+ const action = text(item.action, 500);
229
+ if (!action) continue;
230
+ out.push({ actor: text(item.actor, 80), action, result: text(item.result, 500) });
231
+ }
232
+ return out;
233
+ }
234
+
235
+ function altFlows(raw) {
236
+ if (!Array.isArray(raw)) return [];
237
+ const out = [];
238
+ for (const item of raw.slice(0, 20)) {
239
+ if (!item || typeof item !== 'object') continue;
240
+ const name = text(item.name, 120);
241
+ const steps = list(item.steps, 20, 500);
242
+ if (!name && !steps.length) continue;
243
+ out.push({ name: name || '替代流程', trigger: text(item.trigger, 500), steps });
244
+ }
245
+ return out;
246
+ }
247
+
248
+ function exceptions(raw) {
249
+ if (!Array.isArray(raw)) return [];
250
+ const out = [];
251
+ for (const item of raw.slice(0, 30)) {
252
+ if (!item || typeof item !== 'object') continue;
253
+ const scenario = text(item.scenario, 500);
254
+ if (!scenario) continue;
255
+ out.push({ scenario, expected: text(item.expected, 500) });
256
+ }
257
+ return out;
258
+ }
259
+
260
+ function acceptance(raw) {
261
+ if (!Array.isArray(raw)) return [];
262
+ const out = [];
263
+ for (const item of raw.slice(0, 30)) {
264
+ if (!item || typeof item !== 'object') continue;
265
+ const given = text(item.given, 500);
266
+ const when = text(item.when, 500);
267
+ const then = text(item.then, 500);
268
+ if (!given && !when && !then) continue;
269
+ out.push({ given, when, then });
270
+ }
271
+ return out;
272
+ }
273
+
274
+ /** 故事白名单;id 不合法或重复时置空,由调用方按 seq 分配 */
275
+ function normalizeStory(raw) {
276
+ if (!raw || typeof raw !== 'object') return null;
277
+ const title = text(raw.title, 200);
278
+ if (!title) return null;
279
+ const id = /^US-\d{1,4}$/.test(String(raw.id ?? '')) ? String(raw.id) : '';
280
+ return {
281
+ id,
282
+ title,
283
+ role: text(raw.role, 120),
284
+ goal: text(raw.goal, 500),
285
+ value: text(raw.value, 500),
286
+ sourceRefs: list(raw.sourceRefs, 20, 40),
287
+ priority: oneOf(raw.priority, STORY_PRIORITIES, 'P1'),
288
+ preconditions: list(raw.preconditions, 20, 500),
289
+ mainFlow: mainFlowSteps(raw.mainFlow),
290
+ altFlows: altFlows(raw.altFlows),
291
+ exceptions: exceptions(raw.exceptions),
292
+ postconditions: list(raw.postconditions, 20, 500),
293
+ acceptance: acceptance(raw.acceptance),
294
+ dimensions: list(raw.dimensions, 12, 40),
295
+ };
296
+ }
297
+
298
+ /* ------------------------------ 需求条目 ------------------------------ */
299
+
300
+ function normalizeOutlineItem(raw, fallbackId) {
301
+ if (!raw || typeof raw !== 'object') return null;
302
+ const title = text(raw.title, 200);
303
+ const quote = text(raw.quote, 500);
304
+ if (!title && !quote) return null;
305
+ const id = /^[A-Za-z0-9_-]{1,24}$/.test(String(raw.id ?? '')) ? String(raw.id) : fallbackId;
306
+ return { id, title: title || quote.slice(0, 80), quote };
307
+ }
308
+
309
+ /* ------------------------------ 体检报告 ------------------------------ */
310
+
311
+ function normalizeGap(raw) {
312
+ if (!raw || typeof raw !== 'object') return null;
313
+ const title = text(raw.title, 200);
314
+ if (!title) return null;
315
+ const type = oneOf(raw.type, GAP_TYPES, 'other');
316
+ const storyId = /^US-\d{1,4}$/.test(String(raw.storyId ?? '')) ? String(raw.storyId) : '';
317
+ return {
318
+ id: /^g_[A-Za-z0-9_-]{3,40}$/.test(String(raw.id ?? '')) ? String(raw.id) : newId('g'),
319
+ storyId,
320
+ type,
321
+ severity: oneOf(raw.severity, GAP_SEVERITIES, 'medium'),
322
+ title,
323
+ detail: text(raw.detail, 1000),
324
+ suggestion: text(raw.suggestion, 1000),
325
+ origin: oneOf(raw.origin, GAP_ORIGINS, 'rule'),
326
+ selected: raw.selected === true,
327
+ };
328
+ }
329
+
330
+ function normalizeCheck(raw) {
331
+ if (!raw || typeof raw !== 'object') return null;
332
+ const gaps = (Array.isArray(raw.gaps) ? raw.gaps : []).map(normalizeGap).filter(Boolean);
333
+ const coverage = raw.coverage && typeof raw.coverage === 'object' ? raw.coverage : {};
334
+ const total = Math.max(0, Number(coverage.total) || 0);
335
+ const covered = Math.min(total, Math.max(0, Number(coverage.covered) || 0));
336
+ return {
337
+ at: text(raw.at, 40) || new Date().toISOString(),
338
+ summary: text(raw.summary, 2000),
339
+ coverage: { total, covered, rate: total ? covered / total : 0 },
340
+ dimensions: (Array.isArray(raw.dimensions) ? raw.dimensions : []).slice(0, 24).map((d) => ({
341
+ key: text(d?.key, 40),
342
+ label: text(d?.label, 60),
343
+ covered: d?.covered === true,
344
+ stories: list(d?.stories, 50, 20),
345
+ })),
346
+ gaps: gaps.slice(0, 200),
347
+ };
348
+ }
349
+
350
+ /* ------------------------------ 文档 ------------------------------ */
351
+
352
+ function normalizeProgress(raw) {
353
+ if (!raw || typeof raw !== 'object') return null;
354
+ const total = Math.max(0, Number(raw.total) || 0);
355
+ return {
356
+ stage: oneOf(raw.stage, CHECK_STAGES, 'idle'),
357
+ done: Math.min(total || 999, Math.max(0, Number(raw.done) || 0)),
358
+ total,
359
+ message: text(raw.message, 500),
360
+ at: text(raw.at, 40) || new Date().toISOString(),
361
+ };
362
+ }
363
+
364
+ function normalizeDoc(raw) {
365
+ if (!raw || typeof raw !== 'object') return null;
366
+ const sourcePath = text(raw.sourcePath, 1000);
367
+ const now = new Date().toISOString();
368
+ const doc = {
369
+ id: text(raw.id, 64) || newId('ra'),
370
+ title: text(raw.title, 200) || sourcePath.split('/').pop() || '未命名分析',
371
+ sourcePath,
372
+ sourceTitle: text(raw.sourceTitle, 200),
373
+ sourceHash: text(raw.sourceHash, 64),
374
+ status: oneOf(raw.status, REQ_DOC_STATUSES, 'draft'),
375
+ outline: [],
376
+ stories: [],
377
+ check: normalizeCheck(raw.check),
378
+ progress: normalizeProgress(raw.progress),
379
+ storySeq: Math.max(0, Number(raw.storySeq) || 0),
380
+ createdAt: text(raw.createdAt, 40) || now,
381
+ updatedAt: text(raw.updatedAt, 40) || now,
382
+ };
383
+
384
+ const seenOutline = new Set();
385
+ const outline = (Array.isArray(raw.outline) ? raw.outline : [])
386
+ .map((item, i) => normalizeOutlineItem(item, `RO-${i + 1}`))
387
+ .filter(Boolean);
388
+ let outlineSeq = 0;
389
+ for (const item of outline) {
390
+ outlineSeq += 1;
391
+ if (seenOutline.has(item.id)) item.id = `RO-${item.id}-${outlineSeq}`;
392
+ seenOutline.add(item.id);
393
+ doc.outline.push(item);
394
+ }
395
+
396
+ const seenStory = new Set();
397
+ for (const item of (Array.isArray(raw.stories) ? raw.stories : []).map(normalizeStory)) {
398
+ if (!item) continue;
399
+ // 空 id / 重复 id 按已有最大编号补一个
400
+ if (!item.id || seenStory.has(item.id)) {
401
+ doc.storySeq += 1;
402
+ item.id = `US-${String(doc.storySeq).padStart(3, '0')}`;
403
+ } else {
404
+ const n = Number(item.id.slice(3));
405
+ doc.storySeq = Math.max(doc.storySeq, n);
406
+ }
407
+ seenStory.add(item.id);
408
+ doc.stories.push(item);
409
+ }
410
+ return doc;
411
+ }
412
+
413
+ function emptyStore() {
414
+ return { version: VERSION, docs: [] };
415
+ }
416
+
417
+ function normalizeStore(raw) {
418
+ const base = emptyStore();
419
+ if (!raw || typeof raw !== 'object') return base;
420
+ base.docs = (Array.isArray(raw.docs) ? raw.docs : []).map(normalizeDoc).filter(Boolean);
421
+ return base;
422
+ }
423
+
424
+ function readStore(root) {
425
+ const fp = reqAnalysisStorePath(root);
426
+ try {
427
+ const raw = JSON.parse(fs.readFileSync(fp, 'utf8'));
428
+ if (Array.isArray(raw)) return normalizeStore({ docs: raw });
429
+ return normalizeStore(raw);
430
+ } catch {
431
+ return emptyStore();
432
+ }
433
+ }
434
+
435
+ /** 先写临时文件再 rename:中途失败也不会留下半份 JSON */
436
+ function writeStore(root, store) {
437
+ const fp = reqAnalysisStorePath(root);
438
+ fs.mkdirSync(path.dirname(fp), { recursive: true });
439
+ const tmp = `${fp}.${process.pid}.tmp`;
440
+ fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
441
+ fs.renameSync(tmp, fp);
442
+ }
443
+
444
+ /** 覆盖故事集:保留仍存在的 id,新故事按 seq 分配;`replace` 时重新从 US-001 开始 */
445
+ function applyStories(doc, rawStories, replace = false) {
446
+ const incoming = (Array.isArray(rawStories) ? rawStories : [])
447
+ .map(normalizeStory)
448
+ .filter(Boolean);
449
+ if (replace) {
450
+ doc.storySeq = 0;
451
+ }
452
+ const existing = new Set(doc.stories.map((s) => s.id));
453
+ const used = new Set();
454
+ const out = [];
455
+ for (const story of incoming) {
456
+ let id = story.id && existing.has(story.id) && !used.has(story.id) ? story.id : '';
457
+ if (!id) {
458
+ doc.storySeq += 1;
459
+ id = `US-${String(doc.storySeq).padStart(3, '0')}`;
460
+ }
461
+ used.add(id);
462
+ out.push({ ...story, id });
463
+ }
464
+ doc.stories = out;
465
+ }
466
+
467
+ function applyOutline(doc, rawOutline) {
468
+ doc.outline = (Array.isArray(rawOutline) ? rawOutline : [])
469
+ .map((item, i) => normalizeOutlineItem(item, `RO-${i + 1}`))
470
+ .filter(Boolean)
471
+ .filter((item, i, arr) => arr.findIndex((x) => x.id === item.id) === i);
472
+ }
473
+
474
+ function buildDoc(raw) {
475
+ const now = new Date().toISOString();
476
+ const sourcePath = text(raw.sourcePath, 1000);
477
+ if (!sourcePath) throw badRequest('缺少来源文档路径');
478
+ const doc = {
479
+ id: newId('ra'),
480
+ title:
481
+ text(raw.title, 200) ||
482
+ text(raw.sourceTitle, 200) ||
483
+ sourcePath.split('/').pop() ||
484
+ '未命名分析',
485
+ sourcePath,
486
+ sourceTitle: text(raw.sourceTitle, 200),
487
+ sourceHash: text(raw.sourceHash, 64),
488
+ status: 'draft',
489
+ outline: [],
490
+ stories: [],
491
+ check: null,
492
+ progress: null,
493
+ storySeq: 0,
494
+ createdAt: now,
495
+ updatedAt: now,
496
+ };
497
+ applyOutline(doc, raw.outline);
498
+ applyStories(doc, raw.stories, true);
499
+ return doc;
500
+ }
501
+
502
+ function normalizePatch(base, raw) {
503
+ const patch = {};
504
+ if ('title' in raw) patch.title = text(raw.title, 200) || base.title;
505
+ if ('sourcePath' in raw) patch.sourcePath = text(raw.sourcePath, 1000);
506
+ if ('sourceTitle' in raw) patch.sourceTitle = text(raw.sourceTitle, 200);
507
+ if ('sourceHash' in raw) patch.sourceHash = text(raw.sourceHash, 64);
508
+ if ('status' in raw) patch.status = oneOf(raw.status, REQ_DOC_STATUSES, base.status);
509
+ if ('summary' in raw) patch.summary = text(raw.summary, 2000);
510
+ if ('progress' in raw) patch.progress = normalizeProgress(raw.progress);
511
+ if ('check' in raw) patch.check = normalizeCheck(raw.check);
512
+ return patch;
513
+ }
514
+
515
+ /**
516
+ * @returns {import('vite').Plugin}
517
+ */
518
+ export function lhReqAnalysisPlugin() {
519
+ return {
520
+ name: 'lh-req-analysis',
521
+ configureServer(server) {
522
+ server.middlewares.use(async (req, res, next) => {
523
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
524
+ if (!parsed.pathname.startsWith(PREFIX)) return next();
525
+ // 数据根惰性读取:切换数据空间后无需重启
526
+ const root = getDataRoot();
527
+ const tail = parsed.pathname.slice(PREFIX.length) || '/';
528
+
529
+ try {
530
+ const method = req.method || 'GET';
531
+
532
+ if (method === 'GET' && parsed.searchParams.get('health') === '1') {
533
+ // 探测不算读写:只算路径,不建目录
534
+ return sendJson(res, 200, {
535
+ ok: true,
536
+ files: { store: reqAnalysisStorePath(root) },
537
+ version: VERSION,
538
+ });
539
+ }
540
+
541
+ if (method === 'GET' && tail === '/prompt') {
542
+ // 插件还开着但文件被删(外部删除 / 换空间)时自动补种子:
543
+ // 「重新打开插件会重新生成」不能只靠开关那一下,这里也兜一层
544
+ if (isPluginOnInSpace('reqAnalysis', root)) {
545
+ ensurePluginPrompt(REQ_ANALYSIS_PROMPT_FILE, REQ_ANALYSIS_PROMPT_TEMPLATE, root);
546
+ }
547
+ const content = readPluginPrompt(REQ_ANALYSIS_PROMPT_FILE, root);
548
+ const sections = parseReqPromptSections(content);
549
+ return sendJson(res, 200, {
550
+ ok: true,
551
+ file: REQ_ANALYSIS_PROMPT_FILE,
552
+ exists: Boolean(content.trim()),
553
+ ...sections,
554
+ });
555
+ }
556
+
557
+ if (method === 'POST' && tail === '/prompt/sync') {
558
+ const body = JSON.parse((await readBody(req)) || '{}');
559
+ if (body.enabled !== true) {
560
+ // 关闭只停用:文件保留,再打开仍引用同一份
561
+ return sendJson(res, 200, {
562
+ ok: true,
563
+ enabled: false,
564
+ removed: false,
565
+ exists: Boolean(readPluginPrompt(REQ_ANALYSIS_PROMPT_FILE, root).trim()),
566
+ file: REQ_ANALYSIS_PROMPT_FILE,
567
+ });
568
+ }
569
+ const out = ensurePluginPrompt(
570
+ REQ_ANALYSIS_PROMPT_FILE,
571
+ REQ_ANALYSIS_PROMPT_TEMPLATE,
572
+ root,
573
+ );
574
+ return sendJson(res, 200, { ok: true, enabled: true, ...out });
575
+ }
576
+
577
+ if (method === 'GET' && tail === '/list') {
578
+ const store = readStore(root);
579
+ return sendJson(res, 200, { ok: true, docs: store.docs });
580
+ }
581
+
582
+ /** 来源需求库清单:只给路径 + 格式,正文按需再取(word / excel 不预抽) */
583
+ if (method === 'GET' && tail === '/sources') {
584
+ const dir = reqDocsDir(root);
585
+ const files = [];
586
+ const walk = (absDir, relDir) => {
587
+ let entries = [];
588
+ try {
589
+ entries = fs.readdirSync(absDir, { withFileTypes: true });
590
+ } catch {
591
+ return;
592
+ }
593
+ for (const entry of entries) {
594
+ if (entry.name.startsWith('.')) continue;
595
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
596
+ const abs = path.join(absDir, entry.name);
597
+ if (entry.isDirectory()) {
598
+ walk(abs, rel);
599
+ continue;
600
+ }
601
+ if (!entry.isFile()) continue;
602
+ const ext = sourceExt(entry.name);
603
+ if (!REQ_SOURCE_EXTS.includes(ext)) continue;
604
+ files.push({
605
+ path: rel,
606
+ name: entry.name,
607
+ format: ext.replace(/^\./, ''),
608
+ supported: !REQ_SOURCE_UNSUPPORTED_EXTS.includes(ext),
609
+ });
610
+ }
611
+ };
612
+ walk(dir, '');
613
+ files.sort((a, b) => a.path.localeCompare(b.path, 'zh'));
614
+ return sendJson(res, 200, { ok: true, files });
615
+ }
616
+
617
+ /** 读一份来源文档正文(md / txt / csv 直读,docx / xlsx 抽文本) */
618
+ if (method === 'GET' && tail === '/source') {
619
+ const rel = text(parsed.searchParams.get('path'), 400);
620
+ if (!rel) return sendJson(res, 400, { ok: false, error: '缺少来源文档路径' });
621
+ const out = await readReqSourceFile(root, rel);
622
+ return sendJson(res, 200, { ok: true, path: rel, ...out });
623
+ }
624
+
625
+ if (method === 'POST' && tail === '/create') {
626
+ const body = JSON.parse((await readBody(req)) || '{}');
627
+ const store = readStore(root);
628
+ const doc = buildDoc(body);
629
+ store.docs.push(doc);
630
+ writeStore(root, store);
631
+ return sendJson(res, 200, { ok: true, doc });
632
+ }
633
+
634
+ if (method === 'PUT' && (tail === '/' || tail === '')) {
635
+ const body = JSON.parse((await readBody(req)) || '{}');
636
+ const id = text(body.id, 64);
637
+ if (!id) return sendJson(res, 400, { ok: false, error: '缺少文档 id' });
638
+ const store = readStore(root);
639
+ const idx = store.docs.findIndex((x) => x.id === id);
640
+ if (idx < 0) return sendJson(res, 404, { ok: false, error: '分析文档不存在' });
641
+ const base = store.docs[idx];
642
+ const next = { ...base, ...normalizePatch(base, body) };
643
+ if ('outline' in body) applyOutline(next, body.outline);
644
+ if ('stories' in body) applyStories(next, body.stories, body.replaceStories === true);
645
+ next.updatedAt = new Date().toISOString();
646
+ store.docs[idx] = next;
647
+ writeStore(root, store);
648
+ return sendJson(res, 200, { ok: true, doc: next });
649
+ }
650
+
651
+ if (method === 'POST' && tail === '/delete') {
652
+ const body = JSON.parse((await readBody(req)) || '{}');
653
+ const ids = (Array.isArray(body.ids) ? body.ids : [body.id])
654
+ .map((x) => text(x, 64))
655
+ .filter(Boolean);
656
+ if (!ids.length) return sendJson(res, 400, { ok: false, error: '缺少文档 id' });
657
+ const store = readStore(root);
658
+ const before = store.docs.length;
659
+ store.docs = store.docs.filter((x) => !ids.includes(x.id));
660
+ writeStore(root, store);
661
+ return sendJson(res, 200, { ok: true, removed: before - store.docs.length });
662
+ }
663
+
664
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
665
+ } catch (err) {
666
+ const status = Number(err?.statusCode) || 500;
667
+ return sendJson(res, status, { ok: false, error: String(err?.message ?? err) });
668
+ }
669
+ });
670
+ },
671
+ };
672
+ }
@@ -56,9 +56,11 @@ function writeSeedState(spaceDir, state) {
56
56
  export const PLUGIN_PROMPT_FILES = Object.freeze({
57
57
  '工作汇报提示词.md': 'reports',
58
58
  'Playwright提示词.md': 'uiAuto',
59
+ '需求分析提示词.md': 'reqAnalysis',
59
60
  });
60
61
 
61
62
  export const UI_AUTO_PROMPT_FILE = 'Playwright提示词.md';
63
+ export const REQ_ANALYSIS_PROMPT_FILE = '需求分析提示词.md';
62
64
 
63
65
  /** 当前空间的提示词目录(可能被归进分组文件夹) */
64
66
  export function promptsDir(spaceDir = getDataRoot()) {