lantern-harness 0.1.34 → 0.1.35

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 (113) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +2 -2
  3. package/builtin/session/lh-nav-groups.mjs +9 -0
  4. package/cli/server.mjs +2 -0
  5. package/config/app.defaults.json +2 -1
  6. package/dist/500.html +72 -9
  7. package/dist/_astro/Base.DjXU-4S_.css +1 -0
  8. package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.CuCwv2e7.js → Base.astro_astro_type_script_index_0_lang.CiZNg228.js} +1 -1
  9. package/dist/_astro/{CaseExecBoard.CTVdi8MV.js → CaseExecBoard.DzNtPCwr.js} +1 -1
  10. package/dist/_astro/{CaseGenerateApp.BONj-skB.js → CaseGenerateApp.BvRwwxhs.js} +1 -1
  11. package/dist/_astro/{CasesLibrary.e6nFqhN3.js → CasesLibrary.B9I31b7C.js} +1 -1
  12. package/dist/_astro/{ChatApp.XcaVtt7c.js → ChatApp.79JSgx7d.js} +2 -2
  13. package/dist/_astro/ColumnResize.CkE59sGq.js +1 -0
  14. package/dist/_astro/{DashboardBoard.BaJyXPXA.js → DashboardBoard.BuyuI8WW.js} +1 -1
  15. package/dist/_astro/{DocsFileBrowser.D2Cff2LP.js → DocsFileBrowser.9WTBumS5.js} +1 -1
  16. package/dist/_astro/{DocsPager.CnXEnQqa.js → DocsPager.BS20yicJ.js} +1 -1
  17. package/dist/_astro/{DrawerField.C0MkN-LW.js → DrawerField.CiHAvXHQ.js} +1 -1
  18. package/dist/_astro/{KnowledgeLibrary.CWxIHa8I.js → KnowledgeLibrary.CQ8ULHI5.js} +1 -1
  19. package/dist/_astro/LifeKrTasksBoard.BWoB442i.js +1 -0
  20. package/dist/_astro/LifeKrTodosBoard.rDbG9XcJ.js +1 -0
  21. package/dist/_astro/LifeObjectivesBoard.DUDQg_RD.js +1 -0
  22. package/dist/_astro/LifePlanTypeSelect.BtXnXOkz.js +1 -0
  23. package/dist/_astro/LifeReviewsBoard.p-dp_NXl.js +5 -0
  24. package/dist/_astro/LifeShared.Di9sdb_T.js +3 -0
  25. package/dist/_astro/LifeStagesBoard.BSvhzmp_.js +1 -0
  26. package/dist/_astro/LifeYearCycleSelect.Q4VvLY8X.js +1 -0
  27. package/dist/_astro/LifeYearPlansBoard.CYN2gZKp.js +1 -0
  28. package/dist/_astro/MultiSelectDropdown.y8JMbCxO.js +1 -0
  29. package/dist/_astro/{NavLibraries.CZlA6Z1w.js → NavLibraries.D9EKoN80.js} +1 -1
  30. package/dist/_astro/{PluginsPage.DOGWQcVc.js → PluginsPage.DE3qbeY5.js} +1 -1
  31. package/dist/_astro/PluginsPage.r98lZChB.js +1 -0
  32. package/dist/_astro/{PmBugsBoard.ChL0RBVn.js → PmBugsBoard.Cu1uf0TC.js} +1 -1
  33. package/dist/_astro/{PmIterationsBoard.hTKVnMgh.js → PmIterationsBoard.RzRKkAH0.js} +1 -1
  34. package/dist/_astro/{PmProjectDetail.Saj76lNM.js → PmProjectDetail.DH8Z3nHb.js} +1 -1
  35. package/dist/_astro/{PmProjectsBoard.CCtClGM1.js → PmProjectsBoard.Dokaj4V1.js} +1 -1
  36. package/dist/_astro/{PmRequirementsBoard.DGXYC1Te.js → PmRequirementsBoard.DET5YIVX.js} +1 -1
  37. package/dist/_astro/PmRequirementsBoard.i203nmYC.js +1 -0
  38. package/dist/_astro/{PmShared.BuhrL7Gb.js → PmShared.BJpoEYvk.js} +1 -1
  39. package/dist/_astro/{PromptsLibrary.C9F9RVpz.js → PromptsLibrary.Dp1S_lHQ.js} +1 -1
  40. package/dist/_astro/{ReportsPage.BjD8w0zS.js → ReportsPage.C8uufWVb.js} +1 -1
  41. package/dist/_astro/{ReqAnalysisBoard.JfmIK2Bb.js → ReqAnalysisBoard.B3bhMWmE.js} +1 -1
  42. package/dist/_astro/{RequirementsLibrary.WxAFCP3X.js → RequirementsLibrary.BnY7_YXU.js} +1 -1
  43. package/dist/_astro/{SearchableSelect.D3ODywC4.js → SearchableSelect.5SfNLwNW.js} +1 -1
  44. package/dist/_astro/SelectDropdown.TgxIOKMD.js +1 -0
  45. package/dist/_astro/{SettingsDialog.BpKHIbID.js → SettingsDialog.BzGBZlo2.js} +1 -1
  46. package/dist/_astro/{SpaceSwitcher.BCZbiL7o.js → SpaceSwitcher.Cy4UrzbH.js} +1 -1
  47. package/dist/_astro/TasksBoard.CWkx5cD1.js +1 -0
  48. package/dist/_astro/{TemplatesLibrary.y_RtSjYC.js → TemplatesLibrary.phzK5kho.js} +1 -1
  49. package/dist/_astro/{TestStatsBoard.C3vkF9vc.js → TestStatsBoard.Dp1TWEf7.js} +1 -1
  50. package/dist/_astro/TodosBoard.Bkuw_LDW.js +1 -0
  51. package/dist/_astro/{UiAutoBoard._og5jRon.js → UiAutoBoard.Cpb_EF46.js} +1 -1
  52. package/dist/_astro/app-config.C4rpn1Ix.js +1 -0
  53. package/dist/_astro/app-version.CXqYg1a3.js +1 -0
  54. package/dist/_astro/{bash-tools.cciCC33C.js → bash-tools.RQcI4_42.js} +1 -1
  55. package/dist/_astro/{case-gen-run.BSJ0o4Zq.js → case-gen-run.CH0ldlsU.js} +1 -1
  56. package/dist/_astro/{case-types.CJ5PHz59.js → case-types.CprZTsyX.js} +1 -1
  57. package/dist/_astro/{hydrate-cache.B7--LFB_.js → hydrate-cache.DI6vqM0o.js} +1 -1
  58. package/dist/_astro/i18n.BJeTr39S.js +7 -0
  59. package/dist/_astro/{open-docs-in-session.DQ2_5fkC.js → open-docs-in-session.BdihMTEh.js} +1 -1
  60. package/dist/_astro/plugins.C0NrHGZv.js +1 -0
  61. package/dist/_astro/{req-analysis.D-dTIxXF.js → req-analysis.CjhgP3jI.js} +1 -1
  62. package/dist/_astro/{settings.Cu00if4D.js → settings.NTeTjmxg.js} +2 -2
  63. package/dist/_astro/{spaces-client.Czm-VPh5.js → spaces-client.CMGNsQJ-.js} +1 -1
  64. package/dist/_astro/{story-review.CvXvtZ90.js → story-review.BBfB1qYF.js} +1 -1
  65. package/dist/_astro/tasks.DefXqRfI.js +1 -0
  66. package/dist/_astro/{view-prefs.SdItxolG.js → view-prefs.8MPl3A7e.js} +1 -1
  67. package/dist/case-exec/index.html +141 -15
  68. package/dist/cases/generate/index.html +73 -10
  69. package/dist/cases/library/index.html +141 -15
  70. package/dist/dashboard/index.html +141 -15
  71. package/dist/docs/changelog/index.html +129 -45
  72. package/dist/docs/install/index.html +77 -9
  73. package/dist/docs/manual/index.html +137 -14
  74. package/dist/knowledge/index.html +141 -15
  75. package/dist/life/kr-tasks/index.html +921 -0
  76. package/dist/life/kr-todos/index.html +921 -0
  77. package/dist/life/objectives/index.html +921 -0
  78. package/dist/life/reviews/index.html +921 -0
  79. package/dist/life/stages/index.html +921 -0
  80. package/dist/life/year-plans/index.html +921 -0
  81. package/dist/plugins/index.html +73 -10
  82. package/dist/pm/bugs/index.html +141 -15
  83. package/dist/pm/iterations/index.html +141 -15
  84. package/dist/pm/projects/detail/index.html +141 -15
  85. package/dist/pm/projects/index.html +141 -15
  86. package/dist/pm/requirements/index.html +141 -15
  87. package/dist/prompts/index.html +141 -15
  88. package/dist/reports/index.html +141 -15
  89. package/dist/requirement-analysis/index.html +141 -15
  90. package/dist/requirements/index.html +141 -15
  91. package/dist/tasks/index.html +141 -15
  92. package/dist/templates/index.html +141 -15
  93. package/dist/test-automation/index.html +141 -15
  94. package/dist/test-stats/index.html +141 -15
  95. package/dist/todos/index.html +141 -15
  96. package/dist/workbench/index.html +73 -10
  97. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +1 -0
  98. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +31 -4
  99. package/lh-plugins/lh-life.mjs +1130 -0
  100. package/package.json +1 -1
  101. package/dist/_astro/Base.huFPH3Mp.css +0 -1
  102. package/dist/_astro/ColumnResize._Iq05ix_.js +0 -1
  103. package/dist/_astro/MultiSelectDropdown.BHxW9XLR.js +0 -1
  104. package/dist/_astro/PluginsPage.Ch3rrYRF.js +0 -1
  105. package/dist/_astro/PmRequirementsBoard.BNNq671Z.js +0 -1
  106. package/dist/_astro/SelectDropdown.apWlFGbA.js +0 -1
  107. package/dist/_astro/TasksBoard.CdWQSwlg.js +0 -1
  108. package/dist/_astro/TodosBoard.CSupMlTp.js +0 -1
  109. package/dist/_astro/app-config.Bg6v8zQQ.js +0 -1
  110. package/dist/_astro/app-version.trTEbNVs.js +0 -1
  111. package/dist/_astro/i18n.CH6ZNsHf.js +0 -7
  112. package/dist/_astro/plugins.CVnHeKyf.js +0 -1
  113. package/dist/_astro/tasks.jfnSAEmg.js +0 -1
@@ -0,0 +1,1130 @@
1
+ /**
2
+ * 人生管理(空间级):六张关联表,一个插件开关。
3
+ *
4
+ * 六张表落在 `<空间>/<实体目录>/<实体目录>.json`(可进侧栏分组);目录只在首次写入时创建。
5
+ * 计划类型 / 年度周期 / 人生周期是共用目录配置,落在 `<空间>/.lantern/config/life/`,不单独建内容文件夹。
6
+ * 进度 / 待办数量 / 周期天数等派生值不落库,由前端根据关联计算。
7
+ */
8
+ import crypto from 'node:crypto';
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ import { getDataRoot } from '../builtin/session/space-context.mjs';
13
+ import { resolveContentRoot, spaceConfigFile } from '../builtin/session/space-layout.mjs';
14
+
15
+ const PREFIX = '/__tb_life';
16
+ const VERSION = 1;
17
+
18
+ /** 目录配置在空间配置下的子目录 */
19
+ const LIFE_CONFIG_DIR = 'life';
20
+
21
+ export const LIFE_ENTITY_META = {
22
+ krTodos: { dir: 'KR待办', file: 'KR待办.json', idPrefix: 'kt' },
23
+ krTasks: { dir: 'KR任务', file: 'KR任务.json', idPrefix: 'kr' },
24
+ objectives: { dir: 'Objective目标', file: 'Objective目标.json', idPrefix: 'ob' },
25
+ reviews: { dir: 'OKR复盘', file: 'OKR复盘.json', idPrefix: 'rv' },
26
+ yearPlans: { dir: '年度计划', file: '年度计划.json', idPrefix: 'yp' },
27
+ lifeStages: { dir: '人生阶段', file: '人生阶段.json', idPrefix: 'ls' },
28
+ planTypes: {
29
+ storage: 'config',
30
+ file: '计划类型.json',
31
+ idPrefix: 'pt',
32
+ legacyDir: '计划类型',
33
+ },
34
+ yearCycles: {
35
+ storage: 'config',
36
+ file: '年度周期.json',
37
+ idPrefix: 'yc',
38
+ legacyDir: '年度周期',
39
+ },
40
+ lifeCycles: {
41
+ storage: 'config',
42
+ file: '人生周期.json',
43
+ idPrefix: 'lc',
44
+ },
45
+ };
46
+
47
+ /** 侧栏 / 内容根目录名(不含 config 目录实体);含旧版内容目录名以便跳过当分组 */
48
+ export const LIFE_DIR_NAMES = [
49
+ ...Object.values(LIFE_ENTITY_META)
50
+ .filter((m) => m.storage !== 'config')
51
+ .map((m) => m.dir),
52
+ ...Object.values(LIFE_ENTITY_META)
53
+ .filter((m) => m.storage === 'config' && m.legacyDir)
54
+ .map((m) => m.legacyDir),
55
+ ];
56
+ export const LIFE_ENTITIES = Object.keys(LIFE_ENTITY_META);
57
+
58
+ /** KR 待办状态 */
59
+ export const KR_TODO_STATUSES = ['pending', 'in_progress', 'overdue', 'stalled', 'done', 'closed'];
60
+ /** KR 任务状态 */
61
+ export const KR_TASK_STATUSES = ['pool', 'in_progress', 'incomplete', 'done', 'closed'];
62
+ /** 年度计划状态 */
63
+ export const YEAR_PLAN_STATUSES = ['in_progress', 'incomplete', 'done'];
64
+ /** 重要紧急程度(与待办/任务同文案键) */
65
+ export const LIFE_PRIORITIES = ['urgent_important', 'urgent', 'important', 'normal', ''];
66
+ /** 旧版固定枚举 → 种子 id(读盘迁移) */
67
+ export const LEGACY_PLAN_TYPE_IDS = {
68
+ learning: 'pt_learning',
69
+ work: 'pt_work',
70
+ family: 'pt_family',
71
+ side: 'pt_side',
72
+ };
73
+ /** @deprecated 仅兼容旧数据;新数据以 planTypes 目录为准 */
74
+ export const PLAN_TYPES = ['learning', 'work', 'family', 'side', ''];
75
+ /** 季度 */
76
+ export const QUARTERS = ['Q1', 'Q2', 'Q3', 'Q4', ''];
77
+
78
+ const DEFAULT_PLAN_TYPES = [
79
+ { id: 'pt_learning', name: '学习成长' },
80
+ { id: 'pt_work', name: '工作管理' },
81
+ { id: 'pt_family', name: '家庭生活' },
82
+ { id: 'pt_side', name: '副业赚钱' },
83
+ ];
84
+
85
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
86
+
87
+ export function lifeEntityPath(spaceDir, entity) {
88
+ const meta = LIFE_ENTITY_META[entity];
89
+ if (!meta) throw badRequest(`未知实体:${entity}`);
90
+ if (meta.storage === 'config') {
91
+ return spaceConfigFile(spaceDir, LIFE_CONFIG_DIR, meta.file);
92
+ }
93
+ const dir = resolveContentRoot(spaceDir, meta.dir).abs;
94
+ return path.join(dir, meta.file);
95
+ }
96
+
97
+ /** 旧版内容目录路径(空间根或侧栏分组内):`<…>/计划类型/计划类型.json` */
98
+ export function lifeLegacyEntityPath(spaceDir, entity) {
99
+ const meta = LIFE_ENTITY_META[entity];
100
+ if (!meta?.legacyDir) return null;
101
+ const dir = resolveContentRoot(spaceDir, meta.legacyDir).abs;
102
+ return path.join(dir, meta.file);
103
+ }
104
+
105
+ export function lifeStorePaths(spaceDir) {
106
+ const out = {};
107
+ for (const entity of LIFE_ENTITIES) out[entity] = lifeEntityPath(spaceDir, entity);
108
+ return out;
109
+ }
110
+
111
+ function parseEntityPayload(raw) {
112
+ const items = Array.isArray(raw?.items) ? raw.items : Array.isArray(raw) ? raw : [];
113
+ return items;
114
+ }
115
+
116
+ /** 删掉旧版内容文件;目录空了(或只剩 .DS_Store)一并收掉 */
117
+ function removeLegacyEntityFile(fp) {
118
+ if (!fp || !fs.existsSync(fp)) return;
119
+ try {
120
+ fs.unlinkSync(fp);
121
+ } catch {
122
+ return;
123
+ }
124
+ const dir = path.dirname(fp);
125
+ try {
126
+ const left = fs.readdirSync(dir).filter((n) => n !== '.DS_Store');
127
+ if (left.length === 0) {
128
+ try {
129
+ fs.rmSync(dir, { recursive: true, force: true });
130
+ } catch {
131
+ // 忽略
132
+ }
133
+ }
134
+ } catch {
135
+ // 忽略
136
+ }
137
+ }
138
+
139
+ function sendJson(res, status, body) {
140
+ res.statusCode = status;
141
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
142
+ res.end(JSON.stringify(body));
143
+ }
144
+
145
+ function readBody(req) {
146
+ return new Promise((resolve, reject) => {
147
+ const chunks = [];
148
+ req.on('data', (c) => chunks.push(c));
149
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
150
+ req.on('error', reject);
151
+ });
152
+ }
153
+
154
+ function newId(prefix) {
155
+ return `${prefix}_${crypto.randomBytes(8).toString('hex')}`;
156
+ }
157
+
158
+ function text(value, max = 2000) {
159
+ return typeof value === 'string' ? value.trim().slice(0, max) : '';
160
+ }
161
+
162
+ function dateOrEmpty(value) {
163
+ const s = text(value, 10);
164
+ return DATE_RE.test(s) ? s : '';
165
+ }
166
+
167
+ function oneOf(value, allowed, fallback) {
168
+ const s = text(value, 40);
169
+ return allowed.includes(s) ? s : fallback;
170
+ }
171
+
172
+ function todayIso() {
173
+ const d = new Date();
174
+ const y = d.getFullYear();
175
+ const m = String(d.getMonth() + 1).padStart(2, '0');
176
+ const day = String(d.getDate()).padStart(2, '0');
177
+ return `${y}-${m}-${day}`;
178
+ }
179
+
180
+ function clampProgress(value) {
181
+ const n = Number(value);
182
+ if (!Number.isFinite(n)) return 0;
183
+ return Math.max(0, Math.min(100, Math.round(n)));
184
+ }
185
+
186
+ function idList(raw, known) {
187
+ if (!Array.isArray(raw)) return [];
188
+ const out = [];
189
+ const seen = new Set();
190
+ for (const x of raw) {
191
+ const id = text(x, 64);
192
+ if (!id || seen.has(id)) continue;
193
+ if (known && !known.has(id)) continue;
194
+ seen.add(id);
195
+ out.push(id);
196
+ }
197
+ return out;
198
+ }
199
+
200
+ function emptyStore() {
201
+ return {
202
+ version: VERSION,
203
+ krTodos: [],
204
+ krTasks: [],
205
+ objectives: [],
206
+ reviews: [],
207
+ yearPlans: [],
208
+ lifeStages: [],
209
+ planTypes: [],
210
+ yearCycles: [],
211
+ lifeCycles: [],
212
+ };
213
+ }
214
+
215
+ function normalizePlanType(raw) {
216
+ if (!raw || typeof raw !== 'object') return null;
217
+ const name = text(raw.name, 40);
218
+ if (!name) return null;
219
+ const now = new Date().toISOString();
220
+ return {
221
+ id: text(raw.id, 64) || newId('pt'),
222
+ name,
223
+ createdAt: text(raw.createdAt, 40) || now,
224
+ updatedAt: text(raw.updatedAt, 40) || now,
225
+ };
226
+ }
227
+
228
+ function normalizeYearCycle(raw) {
229
+ if (!raw || typeof raw !== 'object') return null;
230
+ const name = text(raw.name, 40);
231
+ if (!name) return null;
232
+ const now = new Date().toISOString();
233
+ return {
234
+ id: text(raw.id, 64) || newId('yc'),
235
+ name,
236
+ createdAt: text(raw.createdAt, 40) || now,
237
+ updatedAt: text(raw.updatedAt, 40) || now,
238
+ };
239
+ }
240
+
241
+ function normalizeLifeCycle(raw) {
242
+ if (!raw || typeof raw !== 'object') return null;
243
+ const name = text(raw.name, 60);
244
+ if (!name) return null;
245
+ const now = new Date().toISOString();
246
+ return {
247
+ id: text(raw.id, 64) || newId('lc'),
248
+ name,
249
+ createdAt: text(raw.createdAt, 40) || now,
250
+ updatedAt: text(raw.updatedAt, 40) || now,
251
+ };
252
+ }
253
+
254
+ /** 把旧枚举键或已有 id 归一成目录 id */
255
+ function resolvePlanTypeId(raw, planTypeIds) {
256
+ const s = text(raw, 64);
257
+ if (!s) return '';
258
+ if (planTypeIds.has(s)) return s;
259
+ const mapped = LEGACY_PLAN_TYPE_IDS[s];
260
+ if (mapped && planTypeIds.has(mapped)) return mapped;
261
+ return '';
262
+ }
263
+
264
+ /** 已有 id / 同名旧文案 → 年度周期目录 id */
265
+ function resolveYearCycleId(raw, yearCycles) {
266
+ const s = text(raw, 40);
267
+ if (!s) return '';
268
+ if (yearCycles.some((x) => x.id === s)) return s;
269
+ const byName = yearCycles.find((x) => x.name === s);
270
+ return byName ? byName.id : '';
271
+ }
272
+
273
+ /** 已有 id / 同名旧文案(含旧 ageRange)→ 人生周期目录 id */
274
+ function resolveLifeCycleId(raw, lifeCycles) {
275
+ const s = text(raw, 60);
276
+ if (!s) return '';
277
+ if (lifeCycles.some((x) => x.id === s)) return s;
278
+ const byName = lifeCycles.find((x) => x.name === s);
279
+ return byName ? byName.id : '';
280
+ }
281
+
282
+ function normalizeKrTodo(raw, krTaskIds) {
283
+ if (!raw || typeof raw !== 'object') return null;
284
+ const title = text(raw.title, 200);
285
+ if (!title) return null;
286
+ const now = new Date().toISOString();
287
+ const krTaskId = text(raw.krTaskId, 64);
288
+ return {
289
+ id: text(raw.id, 64) || newId('kt'),
290
+ title,
291
+ status: oneOf(raw.status, KR_TODO_STATUSES, 'pending'),
292
+ krTaskId: krTaskIds.has(krTaskId) ? krTaskId : '',
293
+ startDate: dateOrEmpty(raw.startDate),
294
+ dueDate: dateOrEmpty(raw.dueDate),
295
+ note: text(raw.note),
296
+ createdAt: text(raw.createdAt, 40) || now,
297
+ updatedAt: text(raw.updatedAt, 40) || now,
298
+ };
299
+ }
300
+
301
+ function normalizeKrTask(raw, objectiveIds, planTypeIds) {
302
+ if (!raw || typeof raw !== 'object') return null;
303
+ const title = text(raw.title, 200);
304
+ if (!title) return null;
305
+ const now = new Date().toISOString();
306
+ const objectiveId = text(raw.objectiveId, 64);
307
+ return {
308
+ id: text(raw.id, 64) || newId('kr'),
309
+ title,
310
+ status: oneOf(raw.status, KR_TASK_STATUSES, 'pool'),
311
+ priority: oneOf(raw.priority, LIFE_PRIORITIES, ''),
312
+ planType: resolvePlanTypeId(raw.planType, planTypeIds),
313
+ objectiveId: objectiveIds.has(objectiveId) ? objectiveId : '',
314
+ aiComment: text(raw.aiComment),
315
+ note: text(raw.note),
316
+ createdAt: text(raw.createdAt, 40) || now,
317
+ updatedAt: text(raw.updatedAt, 40) || now,
318
+ };
319
+ }
320
+
321
+ function normalizeObjective(raw, yearCycles, yearPlanIds) {
322
+ if (!raw || typeof raw !== 'object') return null;
323
+ const title = text(raw.title, 200);
324
+ if (!title) return null;
325
+ const now = new Date().toISOString();
326
+ const yearPlanId = text(raw.yearPlanId, 64);
327
+ return {
328
+ id: text(raw.id, 64) || newId('ob'),
329
+ title,
330
+ yearCycle: resolveYearCycleId(raw.yearCycle, yearCycles),
331
+ quarter: oneOf(raw.quarter, QUARTERS, ''),
332
+ yearPlanId: yearPlanIds && yearPlanIds.has(yearPlanId) ? yearPlanId : '',
333
+ createdAt: text(raw.createdAt, 40) || now,
334
+ updatedAt: text(raw.updatedAt, 40) || now,
335
+ };
336
+ }
337
+
338
+ /**
339
+ * Objective.yearPlanId ↔ YearPlan.objectiveIds 双向对齐。
340
+ * 读取时:旧数据仅有 objectiveIds 的,回填 yearPlanId;再按 yearPlanId 重建列表。
341
+ */
342
+ function syncObjectiveYearPlanLinks(objectives, yearPlans) {
343
+ const planById = new Map(yearPlans.map((p) => [p.id, p]));
344
+ for (const plan of yearPlans) {
345
+ for (const oid of Array.isArray(plan.objectiveIds) ? plan.objectiveIds : []) {
346
+ const o = objectives.find((x) => x.id === oid);
347
+ if (o && !o.yearPlanId) o.yearPlanId = plan.id;
348
+ }
349
+ }
350
+ for (const o of objectives) {
351
+ if (o.yearPlanId && !planById.has(o.yearPlanId)) o.yearPlanId = '';
352
+ }
353
+ for (const plan of yearPlans) {
354
+ plan.objectiveIds = objectives.filter((o) => o.yearPlanId === plan.id).map((o) => o.id);
355
+ }
356
+ }
357
+
358
+ /** 把目标挂到某年度计划(空则解绑);同步各计划的 objectiveIds,可选对齐年度周期 */
359
+ function assignObjectiveYearPlan(store, objectiveId, yearPlanId) {
360
+ const planIds = new Set(store.yearPlans.map((p) => p.id));
361
+ const nextPlanId = yearPlanId && planIds.has(yearPlanId) ? yearPlanId : '';
362
+ const obj = store.objectives.find((x) => x.id === objectiveId);
363
+ if (!obj) return false;
364
+ obj.yearPlanId = nextPlanId;
365
+ if (nextPlanId) {
366
+ const plan = store.yearPlans.find((p) => p.id === nextPlanId);
367
+ if (plan?.yearCycle) obj.yearCycle = plan.yearCycle;
368
+ }
369
+ syncObjectiveYearPlanLinks(store.objectives, store.yearPlans);
370
+ return true;
371
+ }
372
+
373
+ /** 年度计划改 objectiveIds 时,回写各 Objective.yearPlanId */
374
+ function assignYearPlanObjectives(store, planId, objectiveIds) {
375
+ const allowed = new Set(store.objectives.map((o) => o.id));
376
+ const next = (Array.isArray(objectiveIds) ? objectiveIds : [])
377
+ .map((id) => text(id, 64))
378
+ .filter((id) => allowed.has(id));
379
+ const nextSet = new Set(next);
380
+ for (const o of store.objectives) {
381
+ if (o.yearPlanId === planId && !nextSet.has(o.id)) o.yearPlanId = '';
382
+ else if (nextSet.has(o.id)) o.yearPlanId = planId;
383
+ }
384
+ const plan = store.yearPlans.find((p) => p.id === planId);
385
+ if (plan?.yearCycle) {
386
+ for (const o of store.objectives) {
387
+ if (nextSet.has(o.id) && !o.yearCycle) o.yearCycle = plan.yearCycle;
388
+ }
389
+ }
390
+ syncObjectiveYearPlanLinks(store.objectives, store.yearPlans);
391
+ }
392
+
393
+ function normalizeReview(raw, objectiveIds) {
394
+ if (!raw || typeof raw !== 'object') return null;
395
+ const title = text(raw.title, 200);
396
+ if (!title) return null;
397
+ const now = new Date().toISOString();
398
+ const objectiveId = text(raw.objectiveId, 64);
399
+ const scoreRaw = Number(raw.score);
400
+ const score = Number.isFinite(scoreRaw) ? Math.max(0, Math.min(100, scoreRaw)) : 0;
401
+ return {
402
+ id: text(raw.id, 64) || newId('rv'),
403
+ title,
404
+ objectiveId: objectiveIds.has(objectiveId) ? objectiveId : '',
405
+ score,
406
+ experience: text(raw.experience, 8000),
407
+ createdAt: text(raw.createdAt, 40) || now,
408
+ updatedAt: text(raw.updatedAt, 40) || now,
409
+ };
410
+ }
411
+
412
+ function normalizeYearPlan(raw, objectiveIds, planTypeIds, yearCycles) {
413
+ if (!raw || typeof raw !== 'object') return null;
414
+ const title = text(raw.title, 200);
415
+ if (!title) return null;
416
+ const now = new Date().toISOString();
417
+ return {
418
+ id: text(raw.id, 64) || newId('yp'),
419
+ title,
420
+ yearCycle: resolveYearCycleId(raw.yearCycle, yearCycles),
421
+ planType: resolvePlanTypeId(raw.planType, planTypeIds),
422
+ status: oneOf(raw.status, YEAR_PLAN_STATUSES, 'in_progress'),
423
+ objectiveIds: idList(raw.objectiveIds, objectiveIds),
424
+ createdAt: text(raw.createdAt, 40) || now,
425
+ updatedAt: text(raw.updatedAt, 40) || now,
426
+ };
427
+ }
428
+
429
+ function normalizeLifeStage(raw, planTypeIds, lifeCycles) {
430
+ if (!raw || typeof raw !== 'object') return null;
431
+ const title = text(raw.title, 200);
432
+ if (!title) return null;
433
+ const now = new Date().toISOString();
434
+ // 旧版 ageRange 自由文本并入人生周期目录
435
+ const cycleRaw = raw.lifeCycle || raw.ageRange;
436
+ return {
437
+ id: text(raw.id, 64) || newId('ls'),
438
+ title,
439
+ lifeCycle: resolveLifeCycleId(cycleRaw, lifeCycles),
440
+ planType: resolvePlanTypeId(raw.planType, planTypeIds),
441
+ progress: clampProgress(raw.progress),
442
+ createdAt: text(raw.createdAt, 40) || now,
443
+ updatedAt: text(raw.updatedAt, 40) || now,
444
+ };
445
+ }
446
+
447
+ function seedPlanTypes(rawList) {
448
+ const list = [];
449
+ const seen = new Set();
450
+ for (const item of Array.isArray(rawList) ? rawList : []) {
451
+ const n = normalizePlanType(item);
452
+ if (!n || seen.has(n.id)) continue;
453
+ seen.add(n.id);
454
+ list.push(n);
455
+ }
456
+ if (list.length > 0) return list;
457
+ const now = new Date().toISOString();
458
+ return DEFAULT_PLAN_TYPES.map((d) => ({
459
+ id: d.id,
460
+ name: d.name,
461
+ createdAt: now,
462
+ updatedAt: now,
463
+ }));
464
+ }
465
+
466
+ /**
467
+ * 年度周期目录:保留已有条目;把年度计划 / Objective 上的旧文案吸收进来;
468
+ * 全空时种子「当前年」。
469
+ */
470
+ function seedYearCycles(rawList, legacyNames) {
471
+ const list = [];
472
+ const seenIds = new Set();
473
+ const seenNames = new Set();
474
+ const now = new Date().toISOString();
475
+
476
+ for (const item of Array.isArray(rawList) ? rawList : []) {
477
+ const n = normalizeYearCycle(item);
478
+ if (!n || seenIds.has(n.id)) continue;
479
+ seenIds.add(n.id);
480
+ seenNames.add(n.name);
481
+ list.push(n);
482
+ }
483
+
484
+ for (const rawName of legacyNames) {
485
+ const name = text(rawName, 40);
486
+ // 已是目录 id / 已有同名 → 不重复建
487
+ if (!name || seenNames.has(name) || seenIds.has(name)) continue;
488
+ const id = newId('yc');
489
+ list.push({ id, name, createdAt: now, updatedAt: now });
490
+ seenIds.add(id);
491
+ seenNames.add(name);
492
+ }
493
+
494
+ if (list.length > 0) return list;
495
+ const y = new Date().getFullYear();
496
+ return [{ id: `yc_${y}`, name: `${y}年`, createdAt: now, updatedAt: now }];
497
+ }
498
+
499
+ function collectLegacyYearCycleNames(raw) {
500
+ const names = [];
501
+ for (const list of [raw?.yearPlans, raw?.objectives]) {
502
+ if (!Array.isArray(list)) continue;
503
+ for (const item of list) {
504
+ const s = text(item?.yearCycle, 40);
505
+ if (s) names.push(s);
506
+ }
507
+ }
508
+ return names;
509
+ }
510
+
511
+ /**
512
+ * 人生周期目录:保留已有;把人生阶段上的旧 ageRange / 文案吸收进来;可为空。
513
+ */
514
+ function seedLifeCycles(rawList, legacyNames) {
515
+ const list = [];
516
+ const seenIds = new Set();
517
+ const seenNames = new Set();
518
+ const now = new Date().toISOString();
519
+
520
+ for (const item of Array.isArray(rawList) ? rawList : []) {
521
+ const n = normalizeLifeCycle(item);
522
+ if (!n || seenIds.has(n.id)) continue;
523
+ seenIds.add(n.id);
524
+ seenNames.add(n.name);
525
+ list.push(n);
526
+ }
527
+
528
+ for (const rawName of legacyNames) {
529
+ const name = text(rawName, 60);
530
+ if (!name || seenNames.has(name) || seenIds.has(name)) continue;
531
+ const id = newId('lc');
532
+ list.push({ id, name, createdAt: now, updatedAt: now });
533
+ seenIds.add(id);
534
+ seenNames.add(name);
535
+ }
536
+
537
+ return list;
538
+ }
539
+
540
+ function collectLegacyLifeCycleNames(raw) {
541
+ const names = [];
542
+ const existingIds = new Set(
543
+ (Array.isArray(raw?.lifeCycles) ? raw.lifeCycles : [])
544
+ .map((x) => text(x?.id, 64))
545
+ .filter(Boolean),
546
+ );
547
+ if (!Array.isArray(raw?.lifeStages)) return names;
548
+ for (const item of raw.lifeStages) {
549
+ const fromAge = text(item?.ageRange, 60);
550
+ if (fromAge) names.push(fromAge);
551
+ const fromCycle = text(item?.lifeCycle, 60);
552
+ // 已是目录 id 的不要当名称种子;自由文本则吸收
553
+ if (fromCycle && !existingIds.has(fromCycle)) names.push(fromCycle);
554
+ }
555
+ return names;
556
+ }
557
+
558
+ function normalizeStore(raw) {
559
+ const store = emptyStore();
560
+ if (!raw || typeof raw !== 'object') return store;
561
+
562
+ const planTypes = seedPlanTypes(raw.planTypes);
563
+ const planTypeIds = new Set(planTypes.map((x) => x.id));
564
+
565
+ const yearCycles = seedYearCycles(raw.yearCycles, collectLegacyYearCycleNames(raw));
566
+ const lifeCycles = seedLifeCycles(raw.lifeCycles, collectLegacyLifeCycleNames(raw));
567
+
568
+ // 先收年度计划 id,再规范 Objective.yearPlanId
569
+ const yearPlanIdHints = new Set();
570
+ for (const item of Array.isArray(raw.yearPlans) ? raw.yearPlans : []) {
571
+ const id = text(item?.id, 64);
572
+ if (id) yearPlanIdHints.add(id);
573
+ }
574
+
575
+ const objectives = [];
576
+ for (const item of Array.isArray(raw.objectives) ? raw.objectives : []) {
577
+ const n = normalizeObjective(item, yearCycles, yearPlanIdHints);
578
+ if (n) objectives.push(n);
579
+ }
580
+ const objectiveIds = new Set(objectives.map((x) => x.id));
581
+
582
+ const krTasks = [];
583
+ for (const item of Array.isArray(raw.krTasks) ? raw.krTasks : []) {
584
+ const n = normalizeKrTask(item, objectiveIds, planTypeIds);
585
+ if (n) krTasks.push(n);
586
+ }
587
+ const krTaskIds = new Set(krTasks.map((x) => x.id));
588
+
589
+ const krTodos = [];
590
+ for (const item of Array.isArray(raw.krTodos) ? raw.krTodos : []) {
591
+ const n = normalizeKrTodo(item, krTaskIds);
592
+ if (n) krTodos.push(n);
593
+ }
594
+
595
+ const reviews = [];
596
+ for (const item of Array.isArray(raw.reviews) ? raw.reviews : []) {
597
+ const n = normalizeReview(item, objectiveIds);
598
+ if (n) reviews.push(n);
599
+ }
600
+
601
+ const yearPlans = [];
602
+ for (const item of Array.isArray(raw.yearPlans) ? raw.yearPlans : []) {
603
+ const n = normalizeYearPlan(item, objectiveIds, planTypeIds, yearCycles);
604
+ if (n) yearPlans.push(n);
605
+ }
606
+
607
+ // 旧 objectiveIds / 新 yearPlanId 对齐
608
+ syncObjectiveYearPlanLinks(objectives, yearPlans);
609
+
610
+ const lifeStages = [];
611
+ for (const item of Array.isArray(raw.lifeStages) ? raw.lifeStages : []) {
612
+ const n = normalizeLifeStage(item, planTypeIds, lifeCycles);
613
+ if (n) lifeStages.push(n);
614
+ }
615
+
616
+ store.planTypes = planTypes;
617
+ store.yearCycles = yearCycles;
618
+ store.lifeCycles = lifeCycles;
619
+ store.objectives = objectives;
620
+ store.krTasks = krTasks;
621
+ store.krTodos = krTodos;
622
+ store.reviews = reviews;
623
+ store.yearPlans = yearPlans;
624
+ store.lifeStages = lifeStages;
625
+ return store;
626
+ }
627
+
628
+ function readEntityFile(root, entity) {
629
+ const fp = lifeEntityPath(root, entity);
630
+ const legacyFp = lifeLegacyEntityPath(root, entity);
631
+
632
+ if (fs.existsSync(fp)) {
633
+ // 新路径已有时顺手清掉残留的旧内容目录
634
+ if (legacyFp) removeLegacyEntityFile(legacyFp);
635
+ try {
636
+ const raw = JSON.parse(fs.readFileSync(fp, 'utf8'));
637
+ return { exists: true, items: parseEntityPayload(raw) };
638
+ } catch {
639
+ return { exists: true, items: [] };
640
+ }
641
+ }
642
+
643
+ // 旧版内容目录 → `.lantern/config/life/`(只迁一次)
644
+ if (legacyFp && fs.existsSync(legacyFp)) {
645
+ let items = [];
646
+ try {
647
+ items = parseEntityPayload(JSON.parse(fs.readFileSync(legacyFp, 'utf8')));
648
+ } catch {
649
+ items = [];
650
+ }
651
+ writeEntityFile(root, entity, items);
652
+ removeLegacyEntityFile(legacyFp);
653
+ return { exists: true, items };
654
+ }
655
+
656
+ return { exists: false, items: [] };
657
+ }
658
+
659
+ function writeEntityFile(root, entity, items) {
660
+ const fp = lifeEntityPath(root, entity);
661
+ fs.mkdirSync(path.dirname(fp), { recursive: true });
662
+ const payload = { version: VERSION, items };
663
+ const tmp = `${fp}.${process.pid}.tmp`;
664
+ fs.writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
665
+ fs.renameSync(tmp, fp);
666
+ }
667
+
668
+ function readStore(root) {
669
+ const raw = {};
670
+ const existed = {};
671
+ for (const entity of LIFE_ENTITIES) {
672
+ const file = readEntityFile(root, entity);
673
+ raw[entity] = file.items;
674
+ existed[entity] = file.exists;
675
+ }
676
+ const store = normalizeStore(raw);
677
+ // 首次无「计划类型」文件时落盘种子,避免每次 GET 都像新建
678
+ if (!existed.planTypes && store.planTypes.length > 0) {
679
+ writeEntityFile(root, 'planTypes', store.planTypes);
680
+ }
681
+ // 首次无「年度周期」:落盘种子 / 从旧文案吸收的目录;顺手把已映射成 id 的记录写回
682
+ if (!existed.yearCycles && store.yearCycles.length > 0) {
683
+ writeEntityFile(root, 'yearCycles', store.yearCycles);
684
+ if (store.yearPlans.length) writeEntityFile(root, 'yearPlans', store.yearPlans);
685
+ if (store.objectives.length) writeEntityFile(root, 'objectives', store.objectives);
686
+ }
687
+ // 首次无「人生周期」:吸收旧 ageRange 文案;写回已映射的人生阶段
688
+ if (!existed.lifeCycles && store.lifeCycles.length > 0) {
689
+ writeEntityFile(root, 'lifeCycles', store.lifeCycles);
690
+ if (store.lifeStages.length) writeEntityFile(root, 'lifeStages', store.lifeStages);
691
+ }
692
+ return store;
693
+ }
694
+
695
+ function writeStoreEntities(root, store, entities) {
696
+ for (const entity of entities) {
697
+ if (!LIFE_ENTITY_META[entity]) continue;
698
+ const exists = fs.existsSync(lifeEntityPath(root, entity));
699
+ const items = store[entity] ?? [];
700
+ if (!exists && items.length === 0) continue;
701
+ writeEntityFile(root, entity, items);
702
+ }
703
+ }
704
+
705
+ function badRequest(message) {
706
+ const err = new Error(message);
707
+ err.statusCode = 400;
708
+ return err;
709
+ }
710
+
711
+ function validateTitle(entity, patch) {
712
+ if (entity === 'planTypes' || entity === 'yearCycles' || entity === 'lifeCycles') {
713
+ const max = entity === 'lifeCycles' ? 60 : 40;
714
+ if ('name' in patch && !text(patch.name, max)) {
715
+ throw badRequest(
716
+ entity === 'yearCycles'
717
+ ? '年度周期不能为空'
718
+ : entity === 'lifeCycles'
719
+ ? '人生周期不能为空'
720
+ : '类型名称不能为空',
721
+ );
722
+ }
723
+ return;
724
+ }
725
+ if ('title' in patch && !text(patch.title, 200)) {
726
+ throw badRequest('标题不能为空');
727
+ }
728
+ }
729
+
730
+ function buildItem(store, entity, raw) {
731
+ const objectiveIds = new Set(store.objectives.map((x) => x.id));
732
+ const krTaskIds = new Set(store.krTasks.map((x) => x.id));
733
+ const planTypeIds = new Set(store.planTypes.map((x) => x.id));
734
+ const today = todayIso();
735
+
736
+ if (entity === 'planTypes') {
737
+ const name = text(raw?.name, 40);
738
+ if (!name) throw badRequest('类型名称不能为空');
739
+ const dup = store.planTypes.some((x) => x.name === name);
740
+ if (dup) throw badRequest('已有同名计划类型');
741
+ const item = normalizePlanType({ ...raw, name });
742
+ if (!item) throw badRequest('类型名称不能为空');
743
+ return item;
744
+ }
745
+
746
+ if (entity === 'yearCycles') {
747
+ const name = text(raw?.name, 40);
748
+ if (!name) throw badRequest('年度周期不能为空');
749
+ const dup = store.yearCycles.some((x) => x.name === name);
750
+ if (dup) throw badRequest('已有同名年度周期');
751
+ const item = normalizeYearCycle({ ...raw, name });
752
+ if (!item) throw badRequest('年度周期不能为空');
753
+ return item;
754
+ }
755
+
756
+ if (entity === 'lifeCycles') {
757
+ const name = text(raw?.name, 60);
758
+ if (!name) throw badRequest('人生周期不能为空');
759
+ const dup = store.lifeCycles.some((x) => x.name === name);
760
+ if (dup) throw badRequest('已有同名人生周期');
761
+ const item = normalizeLifeCycle({ ...raw, name });
762
+ if (!item) throw badRequest('人生周期不能为空');
763
+ return item;
764
+ }
765
+
766
+ if (entity === 'krTodos') {
767
+ const item = normalizeKrTodo(
768
+ {
769
+ ...raw,
770
+ startDate: raw?.startDate ?? today,
771
+ dueDate: raw?.dueDate ?? today,
772
+ status: raw?.status ?? 'pending',
773
+ },
774
+ krTaskIds,
775
+ );
776
+ if (!item) throw badRequest('待办描述不能为空');
777
+ return item;
778
+ }
779
+ if (entity === 'krTasks') {
780
+ const item = normalizeKrTask(raw, objectiveIds, planTypeIds);
781
+ if (!item) throw badRequest('任务描述不能为空');
782
+ return item;
783
+ }
784
+ if (entity === 'objectives') {
785
+ const yearPlanIds = new Set(store.yearPlans.map((x) => x.id));
786
+ const item = normalizeObjective(raw, store.yearCycles, yearPlanIds);
787
+ if (!item) throw badRequest('目标描述不能为空');
788
+ if (item.yearPlanId) {
789
+ const plan = store.yearPlans.find((p) => p.id === item.yearPlanId);
790
+ if (plan?.yearCycle && !item.yearCycle) item.yearCycle = plan.yearCycle;
791
+ }
792
+ return item;
793
+ }
794
+ if (entity === 'reviews') {
795
+ const item = normalizeReview(
796
+ {
797
+ ...raw,
798
+ experience: (() => {
799
+ const exp = typeof raw?.experience === 'string' ? raw.experience.trim() : '';
800
+ return exp
801
+ ? raw.experience
802
+ : '1) 有什么是做得好的\n2) 有什么是做得不够好的\n3) 总结如何下次做得更好';
803
+ })(),
804
+ },
805
+ objectiveIds,
806
+ );
807
+ if (!item) throw badRequest('目标复盘摘要不能为空');
808
+ return item;
809
+ }
810
+ if (entity === 'yearPlans') {
811
+ const item = normalizeYearPlan(raw, objectiveIds, planTypeIds, store.yearCycles);
812
+ if (!item) throw badRequest('年度计划标题不能为空');
813
+ return item;
814
+ }
815
+ if (entity === 'lifeStages') {
816
+ const item = normalizeLifeStage(raw, planTypeIds, store.lifeCycles);
817
+ if (!item) throw badRequest('人生阶段标题不能为空');
818
+ return item;
819
+ }
820
+ throw badRequest(`未知实体:${entity}`);
821
+ }
822
+
823
+ function normalizePatch(store, entity, body, base) {
824
+ const objectiveIds = new Set(store.objectives.map((x) => x.id));
825
+ const krTaskIds = new Set(store.krTasks.map((x) => x.id));
826
+ const patch = {};
827
+
828
+ if ('title' in body) patch.title = text(body.title, 200);
829
+ if ('lifeCycle' in body) {
830
+ patch.lifeCycle = resolveLifeCycleId(body.lifeCycle, store.lifeCycles);
831
+ }
832
+ if ('note' in body) patch.note = text(body.note);
833
+ if ('aiComment' in body) patch.aiComment = text(body.aiComment);
834
+ if ('experience' in body) patch.experience = text(body.experience, 8000);
835
+ if ('yearCycle' in body) {
836
+ patch.yearCycle = resolveYearCycleId(body.yearCycle, store.yearCycles);
837
+ }
838
+ if ('startDate' in body) patch.startDate = dateOrEmpty(body.startDate);
839
+ if ('dueDate' in body) patch.dueDate = dateOrEmpty(body.dueDate);
840
+
841
+ if ('status' in body) {
842
+ if (entity === 'krTodos') patch.status = oneOf(body.status, KR_TODO_STATUSES, base.status);
843
+ else if (entity === 'krTasks') patch.status = oneOf(body.status, KR_TASK_STATUSES, base.status);
844
+ else if (entity === 'yearPlans')
845
+ patch.status = oneOf(body.status, YEAR_PLAN_STATUSES, base.status);
846
+ }
847
+ if ('priority' in body)
848
+ patch.priority = oneOf(body.priority, LIFE_PRIORITIES, base.priority ?? '');
849
+ if ('planType' in body) {
850
+ const planTypeIds = new Set(store.planTypes.map((x) => x.id));
851
+ patch.planType = resolvePlanTypeId(body.planType, planTypeIds);
852
+ }
853
+ if ('name' in body && entity === 'planTypes') {
854
+ const name = text(body.name, 40);
855
+ if (!name) throw badRequest('类型名称不能为空');
856
+ const dup = store.planTypes.some((x) => x.name === name && x.id !== base.id);
857
+ if (dup) throw badRequest('已有同名计划类型');
858
+ patch.name = name;
859
+ }
860
+ if ('name' in body && entity === 'yearCycles') {
861
+ const name = text(body.name, 40);
862
+ if (!name) throw badRequest('年度周期不能为空');
863
+ const dup = store.yearCycles.some((x) => x.name === name && x.id !== base.id);
864
+ if (dup) throw badRequest('已有同名年度周期');
865
+ patch.name = name;
866
+ }
867
+ if ('name' in body && entity === 'lifeCycles') {
868
+ const name = text(body.name, 60);
869
+ if (!name) throw badRequest('人生周期不能为空');
870
+ const dup = store.lifeCycles.some((x) => x.name === name && x.id !== base.id);
871
+ if (dup) throw badRequest('已有同名人生周期');
872
+ patch.name = name;
873
+ }
874
+ if ('quarter' in body) patch.quarter = oneOf(body.quarter, QUARTERS, base.quarter ?? '');
875
+ if ('progress' in body) patch.progress = clampProgress(body.progress);
876
+ if ('score' in body) {
877
+ const n = Number(body.score);
878
+ patch.score = Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : (base.score ?? 0);
879
+ }
880
+ if ('krTaskId' in body) {
881
+ const id = text(body.krTaskId, 64);
882
+ patch.krTaskId = !id || krTaskIds.has(id) ? id : base.krTaskId;
883
+ }
884
+ if ('objectiveId' in body) {
885
+ const id = text(body.objectiveId, 64);
886
+ patch.objectiveId = !id || objectiveIds.has(id) ? id : base.objectiveId;
887
+ }
888
+ if ('objectiveIds' in body) {
889
+ patch.objectiveIds = idList(body.objectiveIds, objectiveIds);
890
+ }
891
+ if ('yearPlanId' in body) {
892
+ const planIds = new Set(store.yearPlans.map((x) => x.id));
893
+ const id = text(body.yearPlanId, 64);
894
+ patch.yearPlanId = !id || planIds.has(id) ? id : base.yearPlanId || '';
895
+ }
896
+ return patch;
897
+ }
898
+
899
+ /**
900
+ * 删除时清引用 / 级联:
901
+ * - 删 Objective → 清 KR 任务 / 复盘 / 年度计划上的 objective 引用
902
+ * - 删 KR 任务 → 清下属待办的 krTaskId(待办保留)
903
+ */
904
+ function applyDelete(store, entity, ids, dirty) {
905
+ const idSet = new Set(ids);
906
+ const before = store[entity].length;
907
+ store[entity] = store[entity].filter((x) => !idSet.has(x.id));
908
+ const removed = before - store[entity].length;
909
+
910
+ if (entity === 'objectives') {
911
+ let touchedTasks = false;
912
+ for (const item of store.krTasks) {
913
+ if (idSet.has(item.objectiveId)) {
914
+ item.objectiveId = '';
915
+ touchedTasks = true;
916
+ }
917
+ }
918
+ if (touchedTasks) dirty.add('krTasks');
919
+
920
+ let touchedReviews = false;
921
+ for (const item of store.reviews) {
922
+ if (idSet.has(item.objectiveId)) {
923
+ item.objectiveId = '';
924
+ touchedReviews = true;
925
+ }
926
+ }
927
+ if (touchedReviews) dirty.add('reviews');
928
+
929
+ let touchedPlans = false;
930
+ for (const item of store.yearPlans) {
931
+ const next = item.objectiveIds.filter((id) => !idSet.has(id));
932
+ if (next.length !== item.objectiveIds.length) {
933
+ item.objectiveIds = next;
934
+ touchedPlans = true;
935
+ }
936
+ }
937
+ if (touchedPlans) dirty.add('yearPlans');
938
+ }
939
+
940
+ if (entity === 'krTasks') {
941
+ let touched = false;
942
+ for (const item of store.krTodos) {
943
+ if (idSet.has(item.krTaskId)) {
944
+ item.krTaskId = '';
945
+ touched = true;
946
+ }
947
+ }
948
+ if (touched) dirty.add('krTodos');
949
+ }
950
+
951
+ if (entity === 'planTypes') {
952
+ const clear = (list) => {
953
+ let touched = false;
954
+ for (const item of list) {
955
+ if (idSet.has(item.planType)) {
956
+ item.planType = '';
957
+ touched = true;
958
+ }
959
+ }
960
+ return touched;
961
+ };
962
+ if (clear(store.lifeStages)) dirty.add('lifeStages');
963
+ if (clear(store.yearPlans)) dirty.add('yearPlans');
964
+ if (clear(store.krTasks)) dirty.add('krTasks');
965
+ }
966
+
967
+ if (entity === 'yearCycles') {
968
+ const clear = (list) => {
969
+ let touched = false;
970
+ for (const item of list) {
971
+ if (idSet.has(item.yearCycle)) {
972
+ item.yearCycle = '';
973
+ touched = true;
974
+ }
975
+ }
976
+ return touched;
977
+ };
978
+ if (clear(store.yearPlans)) dirty.add('yearPlans');
979
+ if (clear(store.objectives)) dirty.add('objectives');
980
+ }
981
+
982
+ if (entity === 'lifeCycles') {
983
+ let touched = false;
984
+ for (const item of store.lifeStages) {
985
+ if (idSet.has(item.lifeCycle)) {
986
+ item.lifeCycle = '';
987
+ touched = true;
988
+ }
989
+ }
990
+ if (touched) dirty.add('lifeStages');
991
+ }
992
+
993
+ if (entity === 'yearPlans') {
994
+ let touched = false;
995
+ for (const item of store.objectives) {
996
+ if (idSet.has(item.yearPlanId)) {
997
+ item.yearPlanId = '';
998
+ touched = true;
999
+ }
1000
+ }
1001
+ if (touched) dirty.add('objectives');
1002
+ }
1003
+
1004
+ return { removed, total: store[entity].length };
1005
+ }
1006
+
1007
+ /**
1008
+ * @returns {import('vite').Plugin}
1009
+ */
1010
+ export function lhLifePlugin() {
1011
+ return {
1012
+ name: 'lh-life',
1013
+ configureServer(server) {
1014
+ server.middlewares.use(async (req, res, next) => {
1015
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1');
1016
+ if (!parsed.pathname.startsWith(PREFIX)) return next();
1017
+ const root = getDataRoot();
1018
+
1019
+ try {
1020
+ const method = req.method || 'GET';
1021
+
1022
+ if (method === 'GET' && parsed.searchParams.get('health') === '1') {
1023
+ return sendJson(res, 200, { ok: true, files: lifeStorePaths(root) });
1024
+ }
1025
+
1026
+ if (method === 'GET') {
1027
+ return sendJson(res, 200, { ok: true, ...readStore(root) });
1028
+ }
1029
+
1030
+ if (method === 'POST') {
1031
+ const body = JSON.parse((await readBody(req)) || '{}');
1032
+ const entity = text(body.entity, 40);
1033
+ if (!LIFE_ENTITIES.includes(entity)) {
1034
+ return sendJson(res, 400, { ok: false, error: `未知实体:${entity || '(空)'}` });
1035
+ }
1036
+ const rawItems = Array.isArray(body.items) ? body.items : [body.item ?? body];
1037
+ const store = readStore(root);
1038
+ const created = [];
1039
+ const dirty = new Set([entity]);
1040
+ for (const raw of rawItems) {
1041
+ created.push(buildItem(store, entity, raw));
1042
+ }
1043
+ store[entity].push(...created);
1044
+ if (entity === 'objectives') {
1045
+ for (const item of created) {
1046
+ if (item.yearPlanId) assignObjectiveYearPlan(store, item.id, item.yearPlanId);
1047
+ }
1048
+ dirty.add('yearPlans');
1049
+ }
1050
+ if (entity === 'yearPlans') {
1051
+ for (const item of created) {
1052
+ if (item.objectiveIds?.length) {
1053
+ assignYearPlanObjectives(store, item.id, item.objectiveIds);
1054
+ }
1055
+ }
1056
+ dirty.add('objectives');
1057
+ }
1058
+ writeStoreEntities(root, store, dirty);
1059
+ return sendJson(res, 200, {
1060
+ ok: true,
1061
+ items: created,
1062
+ total: store[entity].length,
1063
+ });
1064
+ }
1065
+
1066
+ if (method === 'PUT') {
1067
+ const body = JSON.parse((await readBody(req)) || '{}');
1068
+ const entity = text(body.entity, 40);
1069
+ if (!LIFE_ENTITIES.includes(entity)) {
1070
+ return sendJson(res, 400, { ok: false, error: `未知实体:${entity || '(空)'}` });
1071
+ }
1072
+ const id = text(body.id, 64);
1073
+ if (!id) return sendJson(res, 400, { ok: false, error: '缺少记录 id' });
1074
+ const store = readStore(root);
1075
+ const idx = store[entity].findIndex((x) => x.id === id);
1076
+ if (idx < 0) return sendJson(res, 404, { ok: false, error: '记录不存在' });
1077
+
1078
+ const base = store[entity][idx];
1079
+ const patch = normalizePatch(store, entity, body, base);
1080
+ validateTitle(entity, patch);
1081
+ const next = { ...base, ...patch, updatedAt: new Date().toISOString() };
1082
+ store[entity][idx] = next;
1083
+ const dirty = new Set([entity]);
1084
+ if (entity === 'objectives' && 'yearPlanId' in patch) {
1085
+ assignObjectiveYearPlan(store, id, next.yearPlanId || '');
1086
+ dirty.add('yearPlans');
1087
+ } else if (entity === 'objectives' && 'yearCycle' in patch && next.yearPlanId) {
1088
+ // 只改年度周期时:若已绑年度计划的年度不一致,清空关联
1089
+ const plan = store.yearPlans.find((p) => p.id === next.yearPlanId);
1090
+ if (plan?.yearCycle && plan.yearCycle !== next.yearCycle) {
1091
+ next.yearPlanId = '';
1092
+ store[entity][idx] = next;
1093
+ assignObjectiveYearPlan(store, id, '');
1094
+ dirty.add('yearPlans');
1095
+ }
1096
+ }
1097
+ if (entity === 'yearPlans' && 'objectiveIds' in patch) {
1098
+ assignYearPlanObjectives(store, id, next.objectiveIds || []);
1099
+ dirty.add('objectives');
1100
+ }
1101
+ writeStoreEntities(root, store, dirty);
1102
+ return sendJson(res, 200, { ok: true, item: store[entity][idx] });
1103
+ }
1104
+
1105
+ if (method === 'DELETE') {
1106
+ const body = JSON.parse((await readBody(req)) || '{}');
1107
+ const entity = text(body.entity, 40);
1108
+ if (!LIFE_ENTITIES.includes(entity)) {
1109
+ return sendJson(res, 400, { ok: false, error: `未知实体:${entity || '(空)'}` });
1110
+ }
1111
+ const ids = (Array.isArray(body.ids) ? body.ids : [body.id])
1112
+ .map((x) => text(x, 64))
1113
+ .filter(Boolean);
1114
+ if (!ids.length) return sendJson(res, 400, { ok: false, error: '缺少记录 id' });
1115
+ const store = readStore(root);
1116
+ const dirty = new Set([entity]);
1117
+ const result = applyDelete(store, entity, ids, dirty);
1118
+ writeStoreEntities(root, store, dirty);
1119
+ return sendJson(res, 200, { ok: true, ...result });
1120
+ }
1121
+
1122
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
1123
+ } catch (err) {
1124
+ const status = Number(err?.statusCode) || 500;
1125
+ return sendJson(res, status, { ok: false, error: String(err?.message ?? err) });
1126
+ }
1127
+ });
1128
+ },
1129
+ };
1130
+ }