lantern-harness 0.1.13 → 0.1.15

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 (149) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/builtin/session/lh-nav-groups.mjs +141 -30
  3. package/cli/server.mjs +7 -0
  4. package/config/app.defaults.json +5 -1
  5. package/dist/500.html +5 -5
  6. package/dist/_astro/Base.VCz1UVxQ.css +1 -0
  7. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.CpzwEBjx.js +1 -0
  8. package/dist/_astro/CaseExecBoard.cBdsZU9e.js +1 -0
  9. package/dist/_astro/CaseGenerateApp.D2ftaUXT.js +9 -0
  10. package/dist/_astro/CasesLibrary.DWXEje9u.js +19 -0
  11. package/dist/_astro/ChatApp.7piDha-y.js +226 -0
  12. package/dist/_astro/ColumnResize.BgYkV9Iy.js +1 -0
  13. package/dist/_astro/{DashboardBoard.uPjTYpJZ.js → DashboardBoard.BIP9es-t.js} +1 -1
  14. package/dist/_astro/DocsFileBrowser.-dkkxR4X.js +1 -0
  15. package/dist/_astro/{DocsPager.EPT5-oEx.js → DocsPager.v4kQH163.js} +1 -1
  16. package/dist/_astro/{DrawerField.DqvXFCFh.js → DrawerField.C0ehOlDt.js} +1 -1
  17. package/dist/_astro/ExcelFieldTags.ytbpKt-Z.js +5 -0
  18. package/dist/_astro/KnowledgeLibrary.Dw-IX3Zt.js +1 -0
  19. package/dist/_astro/NavLibraries.D1J9BwYo.js +1 -0
  20. package/dist/_astro/OverflowHint.pvo2Xc8R.js +1 -0
  21. package/dist/_astro/PluginsPage.DMTsFl_R.js +7 -0
  22. package/dist/_astro/PluginsPage.DMxVKmiY.js +1 -0
  23. package/dist/_astro/PmBugsBoard.BTtm1lki.js +1 -0
  24. package/dist/_astro/PmIterationsBoard.Dm67iXe_.js +1 -0
  25. package/dist/_astro/{PmProjectDetail.BDKXOQJD.js → PmProjectDetail.B7oWL7y-.js} +1 -1
  26. package/dist/_astro/PmProjectsBoard.8QI44RlE.js +1 -0
  27. package/dist/_astro/PmRequirementsBoard.DMJVLCqz.js +1 -0
  28. package/dist/_astro/PmRequirementsBoard.X98441HZ.js +1 -0
  29. package/dist/_astro/{PmShared.D69sPvec.js → PmShared.DbDseTcc.js} +1 -1
  30. package/dist/_astro/PromptMountDialog.YH2odDZx.js +58 -0
  31. package/dist/_astro/PromptsLibrary.B_qFbQGi.js +1 -0
  32. package/dist/_astro/{ReportsPage.N1EaH8E-.js → ReportsPage.BjcajHR6.js} +1 -1
  33. package/dist/_astro/ReqAnalysisBoard.hwNqRyim.js +28 -0
  34. package/dist/_astro/RequirementsLibrary.CGCNnQQG.js +1 -0
  35. package/dist/_astro/SearchableSelect.mvcBwegf.js +1 -0
  36. package/dist/_astro/SelectDropdown.Cb-QtC-D.js +1 -0
  37. package/dist/_astro/SettingsDialog.CnBZRaWE.js +1 -0
  38. package/dist/_astro/SpaceSwitcher.DMoqOVpS.js +7 -0
  39. package/dist/_astro/TasksBoard.DvfyDL76.js +1 -0
  40. package/dist/_astro/TemplatesLibrary.B5KmjjFw.js +1 -0
  41. package/dist/_astro/TestStatsBoard.EIDxmU_8.js +1 -0
  42. package/dist/_astro/Toast.BO2NFckG.js +1 -0
  43. package/dist/_astro/TodosBoard.7IptYUFY.js +1 -0
  44. package/dist/_astro/UiAutoBoard.DJljpjXT.js +9 -0
  45. package/dist/_astro/app-config.CF1xVPmo.js +1 -0
  46. package/dist/_astro/app-version.YyNOCGCb.js +1 -0
  47. package/dist/_astro/bash-tools.CPS0ZiKi.js +25 -0
  48. package/dist/_astro/case-review.DYyZat83.js +3 -0
  49. package/dist/_astro/case-types.DS1EQ5yP.js +1 -0
  50. package/dist/_astro/composer-task.DJmluzPT.js +5 -0
  51. package/dist/_astro/export.joBT53eb.js +148 -0
  52. package/dist/_astro/fs-tools.3F9MFrLf.js +9 -0
  53. package/dist/_astro/{hydrate-cache.zljz1n5X.js → hydrate-cache.CmC22o_H.js} +1 -1
  54. package/dist/_astro/i18n.B3BVhlok.js +7 -0
  55. package/dist/_astro/index.astro_astro_type_script_index_0_lang.CM78W1qz.js +1 -0
  56. package/dist/_astro/jszip.min.Bh2Mgo40.js +2 -0
  57. package/dist/_astro/{lib.BQbwbnfE.js → lib.S37S0T6S.js} +1 -1
  58. package/dist/_astro/{open-docs-in-session.LWVC43xp.js → open-docs-in-session.B6uyOxPn.js} +1 -1
  59. package/dist/_astro/plugins.DYyAjBXb.js +1 -0
  60. package/dist/_astro/prompts-meta.C_MeYq8G.js +2 -0
  61. package/dist/_astro/{req-analysis.C1uUndMm.js → req-analysis.CkLx8c9E.js} +2 -2
  62. package/dist/_astro/{settings.HM3DiNh0.js → settings.BvxRxdqa.js} +2 -2
  63. package/dist/_astro/{spaces-client.CWqBZccW.js → spaces-client.Dy3tSPta.js} +1 -1
  64. package/dist/_astro/story-review.CGcusNKf.js +10 -0
  65. package/dist/_astro/{ui-auto-prompt.B09MVaTI.js → ui-auto-prompt.QcLCZoV6.js} +1 -1
  66. package/dist/_astro/update.DXCPfU4a.js +1 -0
  67. package/dist/_astro/{view-prefs.7wGuDpzi.js → view-prefs.D1snIG5o.js} +1 -1
  68. package/dist/case-exec/index.html +6 -6
  69. package/dist/cases/generate/index.html +5 -5
  70. package/dist/cases/library/index.html +6 -6
  71. package/dist/dashboard/index.html +6 -6
  72. package/dist/docs/changelog/index.html +58 -6
  73. package/dist/docs/install/index.html +5 -5
  74. package/dist/docs/manual/index.html +86 -50
  75. package/dist/index.html +1 -1
  76. package/dist/knowledge/index.html +6 -6
  77. 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 +5 -5
  78. package/dist/plugins/index.html +5 -5
  79. package/dist/pm/bugs/index.html +6 -6
  80. package/dist/pm/iterations/index.html +6 -6
  81. package/dist/pm/projects/detail/index.html +6 -6
  82. package/dist/pm/projects/index.html +6 -6
  83. package/dist/pm/requirements/index.html +6 -6
  84. package/dist/prompts/index.html +6 -6
  85. package/dist/reports/index.html +6 -6
  86. package/dist/requirement-analysis/index.html +6 -6
  87. package/dist/requirements/index.html +6 -6
  88. package/dist/tasks/index.html +6 -6
  89. package/dist/templates/index.html +6 -6
  90. 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 +5 -5
  91. 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 +5 -5
  92. 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 +5 -5
  93. 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 +5 -5
  94. 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 +5 -5
  95. package/dist/test-automation/index.html +6 -6
  96. package/dist/test-stats/index.html +6 -6
  97. package/dist/todos/index.html +6 -6
  98. package/dist/workbench/index.html +5 -5
  99. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +47 -30
  100. package/lh-plugins/case-review-prompt.mjs +181 -0
  101. package/lh-plugins/lh-case-review.mjs +627 -0
  102. package/lh-plugins/lh-pm.mjs +21 -7
  103. package/lh-plugins/lh-req-analysis.mjs +63 -3
  104. package/lh-plugins/lh-story-review.mjs +98 -0
  105. package/lh-plugins/lh-test-points.mjs +98 -0
  106. package/lh-plugins/plugin-prompts.mjs +8 -0
  107. package/lh-plugins/req-analysis-prompt.mjs +8 -37
  108. package/lh-plugins/story-review-prompt.mjs +97 -0
  109. package/lh-plugins/test-points-prompt.mjs +88 -0
  110. package/package.json +1 -1
  111. package/dist/_astro/Base.UUIdmKid.css +0 -1
  112. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.DSWudA4D.js +0 -1
  113. package/dist/_astro/CaseExecBoard.D8K4NzrB.js +0 -1
  114. package/dist/_astro/CaseGenerateApp.bZ_K72NQ.js +0 -9
  115. package/dist/_astro/CasesLibrary.Dhg2pdwU.js +0 -1
  116. package/dist/_astro/ChatApp.B6I3gGKI.js +0 -221
  117. package/dist/_astro/ColumnResize.BEkEW7qw.js +0 -1
  118. package/dist/_astro/DocsFileBrowser.DvBPLCEp.js +0 -1
  119. package/dist/_astro/ExcelFieldTags.De-C3dqn.js +0 -152
  120. package/dist/_astro/KnowledgeLibrary.BzFTmNwA.js +0 -1
  121. package/dist/_astro/NavLibraries.CVdolwYy.js +0 -1
  122. package/dist/_astro/OverflowHint.D6v4Uj2N.js +0 -1
  123. package/dist/_astro/PluginsPage.B8U4uvD2.js +0 -39
  124. package/dist/_astro/PluginsPage.v6afs984.js +0 -1
  125. package/dist/_astro/PmBugsBoard.CSIGq0wz.js +0 -1
  126. package/dist/_astro/PmIterationsBoard.BmBc90as.js +0 -1
  127. package/dist/_astro/PmProjectsBoard.DIVs_xJu.js +0 -1
  128. package/dist/_astro/PmRequirementsBoard.DcLiUhBe.js +0 -1
  129. package/dist/_astro/PmRequirementsBoard.N0LM5jHo.js +0 -1
  130. package/dist/_astro/PromptsLibrary.B1RVZqj8.js +0 -1
  131. package/dist/_astro/ReqAnalysisBoard.BIIUqGVh.js +0 -25
  132. package/dist/_astro/RequirementsLibrary.BZhxG9VU.js +0 -1
  133. package/dist/_astro/SearchableSelect.BIjXzTPD.js +0 -1
  134. package/dist/_astro/SelectDropdown.B3-XpBpn.js +0 -1
  135. package/dist/_astro/SettingsDialog.DILea5eO.js +0 -1
  136. package/dist/_astro/SpaceSwitcher.BeCumAuj.js +0 -7
  137. package/dist/_astro/TasksBoard.B3SzQ5bR.js +0 -1
  138. package/dist/_astro/TemplatesLibrary.Ci3yHQTr.js +0 -1
  139. package/dist/_astro/TestStatsBoard.CgVvwMzN.js +0 -1
  140. package/dist/_astro/Toast.R8_2OWRX.js +0 -1
  141. package/dist/_astro/TodosBoard.BNDF1iVZ.js +0 -1
  142. package/dist/_astro/UiAutoBoard.BNLRrunE.js +0 -9
  143. package/dist/_astro/app-config.Cq_F8I0l.js +0 -1
  144. package/dist/_astro/i18n.DPw-aTIZ.js +0 -7
  145. package/dist/_astro/index.astro_astro_type_script_index_0_lang.B9YrqBHf.js +0 -1
  146. package/dist/_astro/markdown-client.DRva7DS9.js +0 -58
  147. package/dist/_astro/plugins.CKkgnq4r.js +0 -1
  148. package/dist/_astro/prompts-meta.D_2wiFiH.js +0 -2
  149. package/dist/_astro/update.BSnBvaFF.js +0 -1
@@ -0,0 +1,627 @@
1
+ /**
2
+ * 用例质量评审 / 场景遗漏补全(空间级)。
3
+ *
4
+ * 两个插件共用一份数据:`<当前数据空间>/用例评审/用例评审.json`,按用例文件路径分条,
5
+ * 一条里装 `review`(质量评审)与 `blindspot`(场景补全)两份报告。
6
+ * 目录跟着导航分组走:读写统一走 resolveContentRoot。
7
+ *
8
+ * 路由:
9
+ * - `/__tb_casereview?health=1`、`/__tb_casereview/prompt`、`/__tb_casereview/prompt/sync`
10
+ * - `GET /__tb_casereview/summaries`、`GET|PUT /__tb_casereview/report`、`POST /__tb_casereview/append`
11
+ * - `/__tb_caseblindspot?health=1`、`/__tb_caseblindspot/prompt`、`POST /__tb_caseblindspot/prompt/sync`
12
+ */
13
+ import crypto from 'node:crypto';
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+
17
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
18
+ import { resolveContentRoot, spaceLocalFile } from '../builtin/session/space-layout.mjs';
19
+ import { ensurePluginPrompt, isPluginOnInSpace, readPluginPrompt } from './plugin-prompts.mjs';
20
+ import {
21
+ BLINDSPOT_PROMPT_FILE,
22
+ BLINDSPOT_PROMPT_TEMPLATE,
23
+ CASE_REVIEW_PROMPT_FILE,
24
+ CASE_REVIEW_PROMPT_TEMPLATE,
25
+ parseBlindspotPromptSections,
26
+ parseCaseReviewPromptSections,
27
+ } from './case-review-prompt.mjs';
28
+
29
+ const REVIEW_PREFIX = '/__tb_casereview';
30
+ const BLINDSPOT_PREFIX = '/__tb_caseblindspot';
31
+ const VERSION = 1;
32
+
33
+ /** 固定数据目录:与导航分组同名时靠改名避免冲突,需登记到 lh-nav-groups 的 SKIP_DIR_NAMES */
34
+ export const CASE_REVIEW_DIR_NAME = '用例评审';
35
+ export const CASE_REVIEW_STORE_FILE = '用例评审.json';
36
+
37
+ /** 用例文件根目录(与 lh-project-docs 的 DOC_ROOT_DIRS.cases.dirName 一致) */
38
+ const CASES_DIR_NAME = '用例管理';
39
+
40
+ const VERDICTS = ['usable', 'revise', 'invalid'];
41
+ const DIMENSION_KEYS = ['coverage', 'steps', 'expected', 'data', 'convention'];
42
+ const BLINDSPOT_CATEGORIES = ['nonfunctional', 'security', 'compatibility', 'business'];
43
+ const SEVERITIES = ['high', 'medium', 'low'];
44
+ const PRIORITIES = ['P0', 'P1', 'P2', 'P3'];
45
+ const MAX_CASES = 800;
46
+ const MAX_BLINDSPOTS = 300;
47
+
48
+ /** 数据文件路径:只算路径,不建目录。分组即物理归档,目录可能被搬进分组文件夹 */
49
+ export function caseReviewStorePath(spaceDir) {
50
+ const dir = resolveContentRoot(spaceDir, CASE_REVIEW_DIR_NAME).abs;
51
+ return path.join(dir, CASE_REVIEW_STORE_FILE);
52
+ }
53
+
54
+ /** 用例文件绝对路径(越界直接抛 403) */
55
+ function caseFileAbs(root, rel) {
56
+ const raw = String(rel ?? '')
57
+ .replace(/\\/g, '/')
58
+ .trim();
59
+ if (!raw || raw.includes('\0') || raw.split('/').includes('..')) {
60
+ throw Object.assign(new Error('非法的用例文件路径'), { statusCode: 400 });
61
+ }
62
+ const base = resolveContentRoot(root, CASES_DIR_NAME).abs;
63
+ const abs = path.resolve(base, raw);
64
+ if (abs !== base && !abs.startsWith(base + path.sep)) {
65
+ throw Object.assign(new Error('用例文件越界'), { statusCode: 403 });
66
+ }
67
+ return abs;
68
+ }
69
+
70
+ function hashOfFile(abs) {
71
+ try {
72
+ return crypto.createHash('sha256').update(fs.readFileSync(abs)).digest('hex').slice(0, 32);
73
+ } catch {
74
+ return '';
75
+ }
76
+ }
77
+
78
+ /* ------------------------------ 归一化 ------------------------------ */
79
+
80
+ function text(value, max = 2000) {
81
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
82
+ }
83
+
84
+ function oneOf(value, allowed, fallback) {
85
+ const s = text(value, 40);
86
+ return allowed.includes(s) ? s : fallback;
87
+ }
88
+
89
+ function int(value, min, max, fallback = 0) {
90
+ const n = Number(value);
91
+ if (!Number.isFinite(n)) return fallback;
92
+ return Math.min(max, Math.max(min, Math.round(n)));
93
+ }
94
+
95
+ function strList(value, max = 20, itemMax = 1000) {
96
+ if (!Array.isArray(value)) return [];
97
+ return value
98
+ .map((x) => text(x, itemMax))
99
+ .filter(Boolean)
100
+ .slice(0, max);
101
+ }
102
+
103
+ function normalizeDeduction(raw) {
104
+ if (!raw || typeof raw !== 'object') return null;
105
+ const reason = text(raw.reason, 1000);
106
+ if (!reason) return null;
107
+ return {
108
+ dimension: oneOf(raw.dimension, DIMENSION_KEYS, 'expected'),
109
+ points: int(raw.points, 0, 100, 0),
110
+ reason,
111
+ suggestion: text(raw.suggestion, 1000),
112
+ };
113
+ }
114
+
115
+ function normalizeCaseVerdict(raw) {
116
+ if (!raw || typeof raw !== 'object') return null;
117
+ const no = text(raw.no, 80);
118
+ const title = text(raw.title, 300);
119
+ if (!no && !title) return null;
120
+ const dims = raw.dimensions && typeof raw.dimensions === 'object' ? raw.dimensions : {};
121
+ const dimensions = {};
122
+ for (const key of DIMENSION_KEYS) dimensions[key] = int(dims[key], 0, 100, 0);
123
+ return {
124
+ no,
125
+ title,
126
+ verdict: oneOf(raw.verdict, VERDICTS, 'revise'),
127
+ score: int(raw.score, 0, 100, 0),
128
+ dimensions,
129
+ deductions: (Array.isArray(raw.deductions) ? raw.deductions : [])
130
+ .map(normalizeDeduction)
131
+ .filter(Boolean)
132
+ .slice(0, 20),
133
+ };
134
+ }
135
+
136
+ function normalizeReview(raw) {
137
+ if (!raw || typeof raw !== 'object') return null;
138
+ const cases = (Array.isArray(raw.cases) ? raw.cases : [])
139
+ .map(normalizeCaseVerdict)
140
+ .filter(Boolean)
141
+ .slice(0, MAX_CASES);
142
+ const counts = { usable: 0, revise: 0, invalid: 0 };
143
+ for (const c of cases) counts[c.verdict] += 1;
144
+ return {
145
+ at: text(raw.at, 40) || new Date().toISOString(),
146
+ score: int(raw.score, 0, 100, 0),
147
+ counts,
148
+ dimensions: Array.isArray(raw.dimensions)
149
+ ? raw.dimensions.slice(0, 8).map((d) => ({
150
+ key: oneOf(d?.key, DIMENSION_KEYS, 'coverage'),
151
+ label: text(d?.label, 40),
152
+ score: int(d?.score, 0, 100, 0),
153
+ weight: int(d?.weight, 0, 100, 0),
154
+ }))
155
+ : [],
156
+ metrics: Array.isArray(raw.metrics)
157
+ ? raw.metrics.slice(0, 12).map((m) => ({
158
+ key: text(m?.key, 40),
159
+ label: text(m?.label, 40),
160
+ value: Number.isFinite(Number(m?.value)) ? Number(m.value) : 0,
161
+ text: text(m?.text, 40),
162
+ }))
163
+ : [],
164
+ cases,
165
+ summary: text(raw.summary, 2000),
166
+ /** 模型给过语义结论吗;false 表示只有规则结果 */
167
+ modeled: raw.modeled === true,
168
+ };
169
+ }
170
+
171
+ function normalizeBlindspotItem(raw) {
172
+ if (!raw || typeof raw !== 'object') return null;
173
+ const title = text(raw.title, 300);
174
+ if (!title) return null;
175
+ return {
176
+ id: /^bs_[A-Za-z0-9_-]{4,40}$/.test(String(raw.id ?? '')) ? String(raw.id) : newId('bs'),
177
+ category: oneOf(raw.category, BLINDSPOT_CATEGORIES, 'business'),
178
+ severity: oneOf(raw.severity, SEVERITIES, 'medium'),
179
+ title,
180
+ why: text(raw.why, 1000),
181
+ precondition: text(raw.precondition, 1000),
182
+ steps: strList(raw.steps, 20, 1000),
183
+ expected: text(raw.expected, 1000),
184
+ priority: oneOf(raw.priority, PRIORITIES, 'P1'),
185
+ added: raw.added === true,
186
+ caseNo: text(raw.caseNo, 80),
187
+ };
188
+ }
189
+
190
+ function normalizeBlindspot(raw) {
191
+ if (!raw || typeof raw !== 'object') return null;
192
+ const items = (Array.isArray(raw.items) ? raw.items : [])
193
+ .map(normalizeBlindspotItem)
194
+ .filter(Boolean)
195
+ .slice(0, MAX_BLINDSPOTS);
196
+ const ctx = raw.context && typeof raw.context === 'object' ? raw.context : {};
197
+ return {
198
+ at: text(raw.at, 40) || new Date().toISOString(),
199
+ context: {
200
+ reqRef: text(ctx.reqRef, 400),
201
+ reqTitle: text(ctx.reqTitle, 200),
202
+ },
203
+ items,
204
+ summary: text(raw.summary, 2000),
205
+ };
206
+ }
207
+
208
+ function newId(prefix) {
209
+ return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
210
+ }
211
+
212
+ function emptyStore() {
213
+ return { version: VERSION, files: [] };
214
+ }
215
+
216
+ function normalizeEntry(raw) {
217
+ if (!raw || typeof raw !== 'object') return null;
218
+ const rel = text(raw.path, 400);
219
+ if (!rel) return null;
220
+ return {
221
+ path: rel,
222
+ hash: text(raw.hash, 64),
223
+ updatedAt: text(raw.updatedAt, 40) || new Date().toISOString(),
224
+ review: normalizeReview(raw.review),
225
+ blindspot: normalizeBlindspot(raw.blindspot),
226
+ };
227
+ }
228
+
229
+ function normalizeStore(raw) {
230
+ const base = emptyStore();
231
+ if (!raw || typeof raw !== 'object') return base;
232
+ base.files = (Array.isArray(raw.files) ? raw.files : []).map(normalizeEntry).filter(Boolean);
233
+ return base;
234
+ }
235
+
236
+ function readStore(root) {
237
+ try {
238
+ const raw = JSON.parse(fs.readFileSync(caseReviewStorePath(root), 'utf8'));
239
+ return normalizeStore(raw);
240
+ } catch {
241
+ return emptyStore();
242
+ }
243
+ }
244
+
245
+ /** 先写临时文件再 rename:中途失败也不会留下半份 JSON */
246
+ function writeStore(root, store) {
247
+ const fp = caseReviewStorePath(root);
248
+ fs.mkdirSync(path.dirname(fp), { recursive: true });
249
+ const tmp = `${fp}.${process.pid}.tmp`;
250
+ fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
251
+ fs.renameSync(tmp, fp);
252
+ }
253
+
254
+ /* ------------------------------ 追加写回 ------------------------------ */
255
+
256
+ function csvCell(v) {
257
+ const s = String(v ?? '');
258
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
259
+ }
260
+
261
+ function mdCell(v) {
262
+ return String(v ?? '')
263
+ .replace(/\|/g, '\\|')
264
+ .replace(/\n+/g, '<br>');
265
+ }
266
+
267
+ function backupCaseFile(root, abs) {
268
+ const dir = spaceLocalFile(root, 'case-review/backup');
269
+ fs.mkdirSync(dir, { recursive: true });
270
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
271
+ const name = path.basename(abs);
272
+ const dest = path.join(dir, `${stamp}-${name}`);
273
+ fs.copyFileSync(abs, dest);
274
+ return dest;
275
+ }
276
+
277
+ /** md / csv 纯文本追加:原文件一个字节都不改,只在用例表末尾补行(导出仅为便于自测) */
278
+ export function appendTextRows(abs, ext, rows, headers) {
279
+ const raw = fs.readFileSync(abs, 'utf8');
280
+ const sep = raw.includes('\r\n') ? '\r\n' : '\n';
281
+ const body = rows
282
+ .map((r) =>
283
+ ext === '.md'
284
+ ? `| ${headers.map((h) => mdCell(r[h])).join(' | ')} |`
285
+ : headers.map((h) => csvCell(r[h])).join(','),
286
+ )
287
+ .join(sep);
288
+
289
+ if (ext !== '.md') {
290
+ const trimmed = raw.replace(/[\r\n]+$/, '');
291
+ // 空文件(或只有 BOM)先补表头,否则追加的行没有列名
292
+ if (!trimmed.trim() || trimmed === '\uFEFF') {
293
+ fs.writeFileSync(abs, `${headers.map(csvCell).join(',')}${sep}${body}${sep}`, 'utf8');
294
+ return;
295
+ }
296
+ fs.writeFileSync(abs, `${trimmed}${sep}${body}${sep}`, 'utf8');
297
+ return;
298
+ }
299
+
300
+ // md 可能还有「## 备注」这类段落:找到用例表,插在表格最后一行之后,别把行加到文档末尾
301
+ const lines = raw.split(/\r?\n/);
302
+ let insertAt = -1;
303
+ let inTable = false;
304
+ for (let i = 0; i < lines.length; i++) {
305
+ const line = lines[i];
306
+ if (!inTable && line.includes('|') && line.includes('用例')) {
307
+ inTable = true;
308
+ continue;
309
+ }
310
+ if (inTable) {
311
+ if (line.trim().startsWith('|')) insertAt = i + 1;
312
+ else break;
313
+ }
314
+ }
315
+ if (insertAt < 0) {
316
+ // 没有用例表:补一张表头 + 对齐行,再把新用例接上
317
+ const head = `| ${headers.map(mdCell).join(' | ')} |`;
318
+ const align = `| ${headers.map(() => '---').join(' | ')} |`;
319
+ const trimmed = raw.replace(/[\r\n]+$/, '');
320
+ const prefix = trimmed.trim() ? `${trimmed}${sep}${sep}` : '';
321
+ fs.writeFileSync(abs, `${prefix}${head}${sep}${align}${sep}${body}${sep}`, 'utf8');
322
+ return;
323
+ }
324
+ const next = [...lines.slice(0, insertAt), ...body.split(sep), ...lines.slice(insertAt)];
325
+ fs.writeFileSync(abs, next.join(sep), 'utf8');
326
+ }
327
+
328
+ /** xlsx / xls:读出首个工作表尾部行号,追加后整本写回(样式会被 SheetJS 重写,已提前备份) */
329
+ export async function appendSheetRows(abs, rows, headers) {
330
+ const mod = await import('xlsx');
331
+ const xlsx = mod.default ?? mod;
332
+ const book = xlsx.read(fs.readFileSync(abs), { type: 'buffer', cellDates: true });
333
+ const sheetName = book.SheetNames[0];
334
+ if (!sheetName) throw Object.assign(new Error('用例文件里没有工作表'), { statusCode: 422 });
335
+ const sheet = book.Sheets[sheetName];
336
+ const range = xlsx.utils.decode_range(sheet['!ref'] ?? 'A1:A1');
337
+ let row = range.e.r + 1;
338
+ for (const r of rows) {
339
+ headers.forEach((h, c) => {
340
+ const addr = xlsx.utils.encode_cell({ r: row, c });
341
+ sheet[addr] = { t: 's', v: String(r[h] ?? '') };
342
+ });
343
+ row += 1;
344
+ }
345
+ sheet['!ref'] = xlsx.utils.encode_range({
346
+ s: { r: 0, c: 0 },
347
+ e: { r: rows.length ? row - 1 : range.e.r, c: Math.max(range.e.c, headers.length - 1) },
348
+ });
349
+ const out = xlsx.write(book, { bookType: 'xlsx', type: 'buffer' });
350
+ fs.writeFileSync(abs, out);
351
+ }
352
+
353
+ /* ------------------------------ HTTP ------------------------------ */
354
+
355
+ function sendJson(res, status, body) {
356
+ res.statusCode = status;
357
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
358
+ res.setHeader('Cache-Control', 'no-store');
359
+ res.end(JSON.stringify(body));
360
+ }
361
+
362
+ function readBody(req) {
363
+ return new Promise((resolve, reject) => {
364
+ const chunks = [];
365
+ let size = 0;
366
+ req.on('data', (c) => {
367
+ size += c.length;
368
+ if (size > 8 * 1024 * 1024) {
369
+ reject(Object.assign(new Error('提交内容太大(上限 8MB)'), { statusCode: 413 }));
370
+ req.destroy();
371
+ return;
372
+ }
373
+ chunks.push(c);
374
+ });
375
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
376
+ req.on('error', reject);
377
+ });
378
+ }
379
+
380
+ /** 提示词读取 + 播放种子;返回 { file, exists, ...sections } */
381
+ function promptPayload(root, pluginId, file, template, parse) {
382
+ if (isPluginOnInSpace(pluginId, root)) ensurePluginPrompt(file, template, root);
383
+ const content = readPluginPrompt(file, root);
384
+ return { file, exists: Boolean(content.trim()), ...parse(content) };
385
+ }
386
+
387
+ function promptSyncPayload(root, enabled, file, template) {
388
+ if (enabled !== true) {
389
+ return {
390
+ ok: true,
391
+ enabled: false,
392
+ removed: false,
393
+ exists: Boolean(readPluginPrompt(file, root).trim()),
394
+ file,
395
+ };
396
+ }
397
+ return { ok: true, enabled: true, ...ensurePluginPrompt(file, template, root) };
398
+ }
399
+
400
+ async function reviewRoutes(req, res, root, tail, query) {
401
+ const method = req.method || 'GET';
402
+
403
+ if (method === 'GET' && query.get('health') === '1') {
404
+ return sendJson(res, 200, {
405
+ ok: true,
406
+ files: { store: caseReviewStorePath(root) },
407
+ version: VERSION,
408
+ });
409
+ }
410
+
411
+ if (method === 'GET' && tail === '/prompt') {
412
+ return sendJson(res, 200, {
413
+ ok: true,
414
+ ...promptPayload(
415
+ root,
416
+ 'caseReview',
417
+ CASE_REVIEW_PROMPT_FILE,
418
+ CASE_REVIEW_PROMPT_TEMPLATE,
419
+ parseCaseReviewPromptSections,
420
+ ),
421
+ });
422
+ }
423
+
424
+ if (method === 'POST' && tail === '/prompt/sync') {
425
+ const body = JSON.parse((await readBody(req)) || '{}');
426
+ return sendJson(
427
+ res,
428
+ 200,
429
+ promptSyncPayload(
430
+ root,
431
+ body.enabled === true,
432
+ CASE_REVIEW_PROMPT_FILE,
433
+ CASE_REVIEW_PROMPT_TEMPLATE,
434
+ ),
435
+ );
436
+ }
437
+
438
+ // 列表页一次拿全部摘要:判定 / 分数 / 补全条数 / 是否已过期
439
+ if (method === 'GET' && tail === '/summaries') {
440
+ const store = readStore(root);
441
+ const files = store.files.map((entry) => {
442
+ const abs = caseFileAbs(root, entry.path);
443
+ const hash = hashOfFile(abs);
444
+ return {
445
+ path: entry.path,
446
+ exists: Boolean(hash),
447
+ stale: Boolean(entry.hash && hash && entry.hash !== hash),
448
+ at: entry.review?.at ?? '',
449
+ score: entry.review?.score ?? null,
450
+ counts: entry.review?.counts ?? null,
451
+ modeled: entry.review?.modeled === true,
452
+ blindspotCount: entry.blindspot?.items.length ?? 0,
453
+ addedCount: entry.blindspot?.items.filter((x) => x.added).length ?? 0,
454
+ };
455
+ });
456
+ return sendJson(res, 200, { ok: true, files });
457
+ }
458
+
459
+ if (method === 'GET' && tail === '/report') {
460
+ const rel = text(query.get('path'), 400);
461
+ if (!rel) return sendJson(res, 400, { ok: false, error: '缺少用例文件路径' });
462
+ const store = readStore(root);
463
+ const entry = store.files.find((x) => x.path === rel) ?? null;
464
+ const hash = hashOfFile(caseFileAbs(root, rel));
465
+ return sendJson(res, 200, {
466
+ ok: true,
467
+ entry,
468
+ hash,
469
+ stale: Boolean(entry?.hash && hash && entry.hash !== hash),
470
+ });
471
+ }
472
+
473
+ if (method === 'PUT' && (tail === '/report' || tail === '')) {
474
+ const body = JSON.parse((await readBody(req)) || '{}');
475
+ const rel = text(body.path, 400);
476
+ if (!rel) return sendJson(res, 400, { ok: false, error: '缺少用例文件路径' });
477
+ const abs = caseFileAbs(root, rel);
478
+ const store = readStore(root);
479
+ const idx = store.files.findIndex((x) => x.path === rel);
480
+ const base =
481
+ idx >= 0
482
+ ? store.files[idx]
483
+ : { path: rel, hash: '', updatedAt: '', review: null, blindspot: null };
484
+ const next = {
485
+ ...base,
486
+ path: rel,
487
+ hash: hashOfFile(abs) || base.hash,
488
+ updatedAt: new Date().toISOString(),
489
+ };
490
+ // review / blindspot 传 null 表示清掉这一份结果,字段缺省表示不动
491
+ if ('review' in body) next.review = normalizeReview(body.review);
492
+ if ('blindspot' in body) next.blindspot = normalizeBlindspot(body.blindspot);
493
+ if (idx >= 0) store.files[idx] = next;
494
+ else store.files.push(next);
495
+ writeStore(root, store);
496
+ return sendJson(res, 200, { ok: true, entry: next });
497
+ }
498
+
499
+ // 勾选的补全用例追加到原文件;写前备份,写后把条目标成已补全
500
+ if (method === 'POST' && tail === '/append') {
501
+ const body = JSON.parse((await readBody(req)) || '{}');
502
+ const rel = text(body.path, 400);
503
+ if (!rel) return sendJson(res, 400, { ok: false, error: '缺少用例文件路径' });
504
+ const headers = strList(body.headers, 40, 60);
505
+ if (!headers.length) return sendJson(res, 400, { ok: false, error: '缺少用例字段' });
506
+ const rows = (Array.isArray(body.rows) ? body.rows : []).slice(0, 200).map((r) => {
507
+ const out = {};
508
+ for (const h of headers) out[h] = typeof r?.[h] === 'string' ? r[h] : String(r?.[h] ?? '');
509
+ return out;
510
+ });
511
+ if (!rows.length) return sendJson(res, 400, { ok: false, error: '没有要写入的用例' });
512
+
513
+ const abs = caseFileAbs(root, rel);
514
+ if (!fs.existsSync(abs))
515
+ return sendJson(res, 404, { ok: false, error: `用例文件不存在:${rel}` });
516
+ const ext = path.extname(abs).toLowerCase();
517
+ if (!['.md', '.markdown', '.csv', '.xlsx', '.xls'].includes(ext)) {
518
+ return sendJson(res, 415, { ok: false, error: `暂不支持写回 ${ext || '(无扩展名)'} 文件` });
519
+ }
520
+
521
+ const backup = backupCaseFile(root, abs);
522
+ if (ext === '.xlsx' || ext === '.xls') await appendSheetRows(abs, rows, headers);
523
+ else appendTextRows(abs, ext === '.csv' ? '.csv' : '.md', rows, headers);
524
+
525
+ // 标记已补全:按 id 回写 caseNo,界面上就不会再重复勾选
526
+ const store = readStore(root);
527
+ const idx = store.files.findIndex((x) => x.path === rel);
528
+ if (idx >= 0 && store.files[idx].blindspot) {
529
+ const marks = body.marks && typeof body.marks === 'object' ? body.marks : {};
530
+ store.files[idx].blindspot.items = store.files[idx].blindspot.items.map((item) => {
531
+ const no = typeof marks[item.id] === 'string' ? marks[item.id] : '';
532
+ return no ? { ...item, added: true, caseNo: no } : item;
533
+ });
534
+ store.files[idx].hash = hashOfFile(abs) || store.files[idx].hash;
535
+ store.files[idx].updatedAt = new Date().toISOString();
536
+ writeStore(root, store);
537
+ }
538
+
539
+ return sendJson(res, 200, {
540
+ ok: true,
541
+ path: rel,
542
+ appended: rows.length,
543
+ backup: path.relative(root, backup).split(path.sep).join('/'),
544
+ });
545
+ }
546
+
547
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
548
+ }
549
+
550
+ async function blindspotRoutes(req, res, root, tail, query) {
551
+ const method = req.method || 'GET';
552
+
553
+ if (method === 'GET' && query.get('health') === '1') {
554
+ return sendJson(res, 200, {
555
+ ok: true,
556
+ files: { store: caseReviewStorePath(root) },
557
+ version: VERSION,
558
+ });
559
+ }
560
+
561
+ if (method === 'GET' && tail === '/prompt') {
562
+ return sendJson(res, 200, {
563
+ ok: true,
564
+ ...promptPayload(
565
+ root,
566
+ 'caseBlindspot',
567
+ BLINDSPOT_PROMPT_FILE,
568
+ BLINDSPOT_PROMPT_TEMPLATE,
569
+ parseBlindspotPromptSections,
570
+ ),
571
+ });
572
+ }
573
+
574
+ if (method === 'POST' && tail === '/prompt/sync') {
575
+ const body = JSON.parse((await readBody(req)) || '{}');
576
+ return sendJson(
577
+ res,
578
+ 200,
579
+ promptSyncPayload(
580
+ root,
581
+ body.enabled === true,
582
+ BLINDSPOT_PROMPT_FILE,
583
+ BLINDSPOT_PROMPT_TEMPLATE,
584
+ ),
585
+ );
586
+ }
587
+
588
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
589
+ }
590
+
591
+ function middleware(prefix, handler) {
592
+ return (server) => {
593
+ server.middlewares.use(async (req, res, next) => {
594
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
595
+ if (!parsed.pathname.startsWith(prefix)) return next();
596
+ // 数据根惰性读取:切换数据空间后无需重启
597
+ const root = getDataRoot();
598
+ const tail = parsed.pathname.slice(prefix.length) || '/';
599
+ try {
600
+ return await handler(req, res, root, tail, parsed.searchParams);
601
+ } catch (err) {
602
+ const status = Number(err?.statusCode) || 500;
603
+ return sendJson(res, status, { ok: false, error: String(err?.message ?? err) });
604
+ }
605
+ });
606
+ };
607
+ }
608
+
609
+ /**
610
+ * @returns {import('vite').Plugin}
611
+ */
612
+ export function lhCaseReviewPlugin() {
613
+ return {
614
+ name: 'lh-case-review',
615
+ configureServer: middleware(REVIEW_PREFIX, reviewRoutes),
616
+ };
617
+ }
618
+
619
+ /**
620
+ * @returns {import('vite').Plugin}
621
+ */
622
+ export function lhCaseBlindspotPlugin() {
623
+ return {
624
+ name: 'lh-case-blindspot',
625
+ configureServer: middleware(BLINDSPOT_PREFIX, blindspotRoutes),
626
+ };
627
+ }
@@ -13,6 +13,7 @@ import fs from 'node:fs';
13
13
  import path from 'node:path';
14
14
 
15
15
  import { getDataRoot } from '../builtin/session/space-context.mjs';
16
+ import { resolveContentRoot } from '../builtin/session/space-layout.mjs';
16
17
 
17
18
  const PREFIX = '/__tb_pm';
18
19
  const VERSION = 1;
@@ -65,11 +66,12 @@ export const PM_ENTITIES = ['projects', 'iterations', 'requirements', 'bugs'];
65
66
 
66
67
  const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
67
68
 
68
- /** 某个实体的数据文件路径:只算路径,不建目录 */
69
+ /** 某个实体的数据文件路径:只算路径,不建目录。分组即物理归档,目录可能被搬进分组文件夹 */
69
70
  export function pmEntityPath(spaceDir, entity) {
70
71
  const meta = PM_ENTITY_META[entity];
71
72
  if (!meta) throw badRequest(`未知实体:${entity}`);
72
- return path.join(path.resolve(spaceDir), meta.dir, meta.file);
73
+ const dir = resolveContentRoot(spaceDir, meta.dir).abs;
74
+ return path.join(dir, meta.file);
73
75
  }
74
76
 
75
77
  /** 四个数据文件路径(health 探测用,不建目录) */
@@ -439,8 +441,13 @@ const MIME_BY_EXT = {
439
441
  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
440
442
  };
441
443
 
444
+ /** 附件根目录(缺陷管理)在磁盘上的实际位置:被归进分组文件夹时就在分组里 */
445
+ function attachmentBase(root) {
446
+ return resolveContentRoot(root, ATTACHMENT_DIR).abs;
447
+ }
448
+
442
449
  function attachmentDir(root) {
443
- return path.join(path.resolve(root), ATTACHMENT_DIR, ATTACHMENT_SUBDIR);
450
+ return path.join(attachmentBase(root), ATTACHMENT_SUBDIR);
444
451
  }
445
452
 
446
453
  /** 只留安全字符;空名兜底为 attachment */
@@ -481,7 +488,12 @@ function saveUpload(root, raw) {
481
488
  };
482
489
  }
483
490
 
484
- /** 把地址解析回空间内的附件路径;越界或不在附件目录里返回空 */
491
+ /**
492
+ * 把地址解析回空间内的附件路径;越界或不在附件目录里返回空。
493
+ *
494
+ * 记录里存的是稳定相对路径(`缺陷管理/附件/xxx`),而缺陷管理目录可能被归进分组
495
+ * (分组 = 物理归档),所以先把第一层目录名摘掉,再拼到解析出来的实际目录上。
496
+ */
485
497
  function attachmentPath(root, url) {
486
498
  let rel = '';
487
499
  try {
@@ -490,9 +502,11 @@ function attachmentPath(root, url) {
490
502
  return '';
491
503
  }
492
504
  if (!rel) return '';
493
- const base = path.resolve(root);
494
- const target = path.resolve(base, rel);
495
- const allowed = path.resolve(base, ATTACHMENT_DIR, ATTACHMENT_SUBDIR);
505
+ const normalized = path.posix.normalize(rel.replace(/\\/g, '/')).replace(/^\/+/, '');
506
+ const prefix = `${ATTACHMENT_DIR}/`;
507
+ const sub = normalized.startsWith(prefix) ? normalized.slice(prefix.length) : normalized;
508
+ const allowed = path.resolve(attachmentBase(root), ATTACHMENT_SUBDIR);
509
+ const target = path.resolve(allowed, sub);
496
510
  if (target !== allowed && !target.startsWith(`${allowed}${path.sep}`)) return '';
497
511
  return target;
498
512
  }