dsh-workbench-tasks 0.0.0-stage → 5.2.20

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/cordis.patch.yml +7 -0
  4. package/lib/client.js +11963 -0
  5. package/lib/db/db-core.js +432 -0
  6. package/lib/db/db-legacy.js +473 -0
  7. package/lib/db/db.js +97 -0
  8. package/lib/db/ownership-path.js +33 -0
  9. package/lib/db/timeline-schema.js +7 -0
  10. package/lib/db/workspace-schema.js +15 -0
  11. package/lib/index.js +232 -0
  12. package/lib/infra/backup.js +289 -0
  13. package/lib/infra/config.js +462 -0
  14. package/lib/infra/data.js +368 -0
  15. package/lib/infra/sync.js +189 -0
  16. package/lib/publisher/brief.js +76 -0
  17. package/lib/publisher/catalog.js +99 -0
  18. package/lib/publisher/command.js +81 -0
  19. package/lib/stats/activity-calendar.js +74 -0
  20. package/lib/stats/difficulty-bins.js +49 -0
  21. package/lib/stats/events.js +40 -0
  22. package/lib/stats/overview.js +99 -0
  23. package/lib/stats/stats-today.js +26 -0
  24. package/lib/stats/stats.js +589 -0
  25. package/lib/stats/timeline-stats.js +174 -0
  26. package/lib/tagging/source.js +89 -0
  27. package/lib/tagging/tag-options.js +99 -0
  28. package/lib/tagging/tagging.js +371 -0
  29. package/lib/task/model/task-difficulty.js +15 -0
  30. package/lib/task/model/task-model.js +256 -0
  31. package/lib/task/model/task-ownership-path.js +22 -0
  32. package/lib/task/model/task-priority.js +33 -0
  33. package/lib/task/read/task-discovery.js +123 -0
  34. package/lib/task/read/task-publish-filter.js +31 -0
  35. package/lib/task/read/task-query.js +351 -0
  36. package/lib/task/read/task-search-schema.js +34 -0
  37. package/lib/task/read/task-view.js +146 -0
  38. package/lib/task/write/task-bulk.js +247 -0
  39. package/lib/task/write/task-claim.js +229 -0
  40. package/lib/task/write/task-create-schema.js +34 -0
  41. package/lib/task/write/task-create.js +178 -0
  42. package/lib/task/write/task-operations.js +207 -0
  43. package/lib/task/write/task-target.js +56 -0
  44. package/lib/task/write/task-transaction.js +18 -0
  45. package/lib/task/write/task-update.js +104 -0
  46. package/lib/tasks.js +456 -0
  47. package/lib/timeline/task-timelines.js +110 -0
  48. package/lib/timeline/timeline-actions.js +69 -0
  49. package/lib/timeline/timeline-migration.js +70 -0
  50. package/lib/timeline/timeline-store.js +57 -0
  51. package/lib/timeline/timeline-sync.js +46 -0
  52. package/lib/tree/task-node-write.js +26 -0
  53. package/lib/tree/tree.js +517 -0
  54. package/lib/workspace/workspace-actions.js +217 -0
  55. package/lib/workspace/workspace-store.js +196 -0
  56. package/package.json +144 -4
  57. package/shared/tree/limits.cjs +3 -0
@@ -0,0 +1,473 @@
1
+ /**
2
+ * 任务子插件:旧库迁移(MPTT 旧表、type 列、优先级回填)。
3
+ *
4
+ * 从 db.js 拆出,纯结构调整,行为不变(2026-11-09)。
5
+ */
6
+ import { quoteIdent, dropIndexesFor, now, newId, idOf, todayStr, dateText, timeMs, tableExists, columnsOf, hasColumn, metaGet, metaSet, tx, logChange, insertNode, createSchema, seedDefaultTree } from "./db-core.js";
7
+
8
+ function legacyName(base, ts) {
9
+ const d = new Date(ts);
10
+ const pad = function (n) {
11
+ return String(n).padStart(2, "0");
12
+ };
13
+ let name = base + "_legacy_" + d.getFullYear() + pad(d.getMonth() + 1) + pad(d.getDate()) + "_" + pad(d.getHours()) + pad(d.getMinutes()) + pad(d.getSeconds());
14
+ let i = 1;
15
+ while (tableExists(name)) {
16
+ name = base + "_legacy_" + (i++);
17
+ }
18
+ return name;
19
+ }
20
+
21
+ function pick(obj, keys) {
22
+ if (!obj) return undefined;
23
+ for (const k of keys) {
24
+ if (obj[k] !== undefined && obj[k] !== null && obj[k] !== "") return obj[k];
25
+ }
26
+ return undefined;
27
+ }
28
+
29
+ function validStatus(v) {
30
+ const s = String(v);
31
+ return ["0", "1", "2", "3"].indexOf(s) >= 0 ? s : "0";
32
+ }
33
+
34
+ function validType(v) {
35
+ const s = String(v);
36
+ return ["0", "1", "2", "3"].indexOf(s) >= 0 ? s : "0";
37
+ }
38
+
39
+ function clampPriority(v) {
40
+ const n = Number(v);
41
+ if (!Number.isFinite(n)) return 0;
42
+ return Math.max(0, Math.min(10, Math.round(n)));
43
+ }
44
+
45
+ function clampDifficulty(v) {
46
+ if (v === undefined || v === null || v === "") return null;
47
+ const n = Number(v);
48
+ if (!Number.isFinite(n)) return null;
49
+ return Math.max(0, Math.min(5, n));
50
+ }
51
+
52
+ function buildLegacyPlan(oldNodes, oldTasks, ts, report) {
53
+ const byId = new Map();
54
+ for (const n of oldNodes || []) {
55
+ if (n && n.id !== undefined && n.id !== null) byId.set(String(n.id), n);
56
+ }
57
+
58
+ const rootOld = byId.get("1");
59
+ if (rootOld) {
60
+ const p = String(rootOld.parent === undefined || rootOld.parent === null ? "0" : rootOld.parent);
61
+ if (p !== "0" && byId.has(p)) {
62
+ throw new Error("旧 task_node 的 id=1 不是根节点,无法安全迁移");
63
+ }
64
+ }
65
+
66
+ const rows = [];
67
+ const children = new Map();
68
+ function addChild(parent, node) {
69
+ if (!children.has(parent)) children.set(parent, []);
70
+ children.get(parent).push(node);
71
+ }
72
+
73
+ for (const n of oldNodes || []) {
74
+ const id = String(n.id);
75
+ if (id === "1") {
76
+ addChild("0", n);
77
+ continue;
78
+ }
79
+ let parent = n.parent === undefined || n.parent === null ? "0" : String(n.parent);
80
+ if (parent === "0" || !byId.has(parent)) {
81
+ report.orphanNodes += 1;
82
+ parent = "1";
83
+ }
84
+ n.__parent = parent;
85
+ addChild(parent, n);
86
+ }
87
+
88
+ let syntheticRoot = null;
89
+ if (!rootOld) {
90
+ syntheticRoot = {
91
+ id: "1",
92
+ name: "全部任务组",
93
+ type: "2",
94
+ parent: "0",
95
+ __parent: "0",
96
+ create_time: ts,
97
+ update_time: ts,
98
+ };
99
+ addChild("0", syntheticRoot);
100
+ }
101
+
102
+ const seen = new Set();
103
+ function walk(id, parentPath, depth, sort) {
104
+ if (seen.has(id)) throw new Error("旧 task_node 存在环:" + id);
105
+ seen.add(id);
106
+ const old = id === "1" && syntheticRoot ? syntheticRoot : byId.get(id);
107
+ if (!old) return;
108
+ const type = id === "1" ? "2" : String(old.type) === "1" ? "1" : "0";
109
+ const name = String(old.name || (id === "1" ? "全部任务组" : "未命名"));
110
+ const path = parentPath + id + "/";
111
+ const created = timeMs(pick(old, ["create_time", "created_at"]), ts);
112
+ const updated = timeMs(pick(old, ["update_time", "updated_at"]), created);
113
+ rows.push({
114
+ id,
115
+ name,
116
+ type,
117
+ parent_id: id === "1" ? "0" : String(old.__parent || "1"),
118
+ path,
119
+ sort,
120
+ depth,
121
+ created_at: created,
122
+ updated_at: updated,
123
+ deleted_at: null,
124
+ rev: 1,
125
+ });
126
+ const kids = (children.get(id) || []).slice().sort(function (a, b) {
127
+ const al = Number(a.lft);
128
+ const bl = Number(b.lft);
129
+ if (Number.isFinite(al) && Number.isFinite(bl) && al !== bl) return al - bl;
130
+ return String(a.id).localeCompare(String(b.id), "en");
131
+ });
132
+ let i = 0;
133
+ for (const kid of kids) {
134
+ walk(String(kid.id), path, depth + 1, i++);
135
+ }
136
+ }
137
+
138
+ const rootChildren = (children.get("0") || []).filter(function (n) {
139
+ return String(n.id) === "1";
140
+ });
141
+ if (!rootChildren.length) throw new Error("旧 task_node 没有可用的根节点");
142
+ walk("1", "/", 0, 0);
143
+
144
+ const leftover = Array.from(byId.keys()).filter(function (id) {
145
+ return !seen.has(id);
146
+ });
147
+ if (leftover.length) {
148
+ throw new Error("旧 task_node 存在不可达节点:" + leftover.slice(0, 10).join(","));
149
+ }
150
+
151
+ const tableRows = rows.filter(function (r) {
152
+ return r.type === "1";
153
+ });
154
+ let defaultTable = tableRows[0];
155
+ if (!defaultTable) {
156
+ const used = new Set(rows.map(function (r) {
157
+ return r.id;
158
+ }));
159
+ let groupId = "2";
160
+ while (used.has(groupId)) groupId = String(Number(groupId) + 1);
161
+ const group = {
162
+ id: groupId,
163
+ name: "默认任务组",
164
+ type: "0",
165
+ parent_id: "1",
166
+ path: "/1/" + groupId + "/",
167
+ sort: rows.filter(function (r) {
168
+ return r.parent_id === "1";
169
+ }).length,
170
+ depth: 1,
171
+ created_at: ts,
172
+ updated_at: ts,
173
+ deleted_at: null,
174
+ rev: 1,
175
+ };
176
+ rows.push(group);
177
+ used.add(groupId);
178
+ let tableId = String(Number(groupId) + 1);
179
+ while (used.has(tableId)) tableId = String(Number(tableId) + 1);
180
+ defaultTable = {
181
+ id: tableId,
182
+ name: "默认任务表",
183
+ type: "1",
184
+ parent_id: groupId,
185
+ path: group.path + tableId + "/",
186
+ sort: 0,
187
+ depth: 2,
188
+ created_at: ts,
189
+ updated_at: ts,
190
+ deleted_at: null,
191
+ rev: 1,
192
+ };
193
+ rows.push(defaultTable);
194
+ }
195
+
196
+ const tableIds = new Set(rows.filter(function (r) {
197
+ return r.type === "1";
198
+ }).map(function (r) {
199
+ return r.id;
200
+ }));
201
+
202
+ const taskRows = [];
203
+ for (const t of oldTasks || []) {
204
+ const id = String(t.id);
205
+ let tableId = idOf(t.table_id);
206
+ if (!tableIds.has(tableId)) {
207
+ report.orphanTasks += 1;
208
+ tableId = defaultTable.id;
209
+ }
210
+ const publish = dateText(pick(t, ["publish_date", "publishDate"])) || dateText(pick(t, ["create_time", "created_at"])) || todayStr();
211
+ const target = dateText(pick(t, ["target_date", "targetDate"])) || publish;
212
+ const status = validStatus(t.status);
213
+ const timelineRaw = pick(t, ["timeline_key", "timelineKey"]);
214
+ const restartRaw = pick(t, ["restart_key", "restartKey"]);
215
+ const created = timeMs(pick(t, ["create_time", "created_at"]), ts);
216
+ const updated = timeMs(pick(t, ["update_time", "updated_at"]), created);
217
+ taskRows.push({
218
+ id,
219
+ title: String(t.title || ""),
220
+ description: String(t.description === undefined || t.description === null ? "" : t.description),
221
+ status,
222
+ legacyType: validType(t.type),
223
+ priority: clampPriority(t.priority),
224
+ difficulty: clampDifficulty(t.difficulty),
225
+ table_id: tableId,
226
+ timeline_key: timelineRaw === undefined || timelineRaw === null || Number(timelineRaw) === 0 ? id : String(timelineRaw),
227
+ restart_key: restartRaw === undefined || restartRaw === null || Number(restartRaw) === 0 ? id : String(restartRaw),
228
+ publish_date: publish,
229
+ target_date: target,
230
+ done_date: dateText(t.done_date),
231
+ shutdown_date: dateText(t.shutdown_date),
232
+ created_at: created,
233
+ updated_at: updated,
234
+ deleted_at: null,
235
+ rev: 1,
236
+ });
237
+ }
238
+
239
+ return { rows, taskRows, defaultTableId: defaultTable.id };
240
+ }
241
+
242
+ export function migrateLegacy(db, report) {
243
+ const oldTasks = tableExists(db, "task") ? db.prepare("SELECT * FROM task").all() : [];
244
+ const oldNodes = tableExists(db, "task_node") ? db.prepare("SELECT * FROM task_node").all() : [];
245
+ const ts = now();
246
+ const plan = buildLegacyPlan(oldNodes, oldTasks, ts, report);
247
+ tx(db, function () {
248
+ if (tableExists(db, "task")) {
249
+ const name = legacyName("task", ts);
250
+ db.exec("ALTER TABLE task RENAME TO " + quoteIdent(name));
251
+ dropIndexesFor(db, name);
252
+ report.legacyTask = name;
253
+ }
254
+ if (tableExists(db, "task_node")) {
255
+ const name = legacyName("task_node", ts);
256
+ db.exec("ALTER TABLE task_node RENAME TO " + quoteIdent(name));
257
+ dropIndexesFor(db, name);
258
+ report.legacyNode = name;
259
+ }
260
+ createSchema(db);
261
+ for (const row of plan.rows) insertNode(db, row);
262
+ const ins = db.prepare(
263
+ "INSERT INTO task(id,title,description,status,priority,difficulty,table_id,timeline_key,restart_key,publish_date,target_date,done_date,shutdown_date,created_at,updated_at,deleted_at,rev) " +
264
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
265
+ );
266
+ const legacyTypes = {};
267
+ for (const t of plan.taskRows) {
268
+ if (t.legacyType !== undefined && t.legacyType !== null) legacyTypes[String(t.id)] = String(t.legacyType);
269
+ ins.run(t.id, t.title, t.description, t.status, t.priority, t.difficulty, t.table_id, t.timeline_key, t.restart_key, t.publish_date, t.target_date, t.done_date, t.shutdown_date, t.created_at, t.updated_at, null, t.rev);
270
+ }
271
+ // type 列已废弃;旧类型的映射留给标签迁移(tagging.migrateLegacyTypes)消费。
272
+ if (Object.keys(legacyTypes).length) metaSet(db, "legacy_task_types", JSON.stringify(legacyTypes));
273
+ });
274
+ report.source = "legacy_mptt";
275
+ report.nodes = plan.rows.length;
276
+ report.tasks = plan.taskRows.length;
277
+ report.defaultTableId = plan.defaultTableId;
278
+ }
279
+
280
+ function mapOldPriority(v) {
281
+ const n = Number(v);
282
+ if (n === 1) return 8;
283
+ if (n === 2) return 6;
284
+ if (n === 3) return 4;
285
+ return clampPriority(n);
286
+ }
287
+
288
+ export function migrateCurrentTasks(db, report) {
289
+ const old = db.prepare("SELECT * FROM tasks").all();
290
+ const ts = now();
291
+ tx(db, function () {
292
+ createSchema(db);
293
+ seedDefaultTree(db);
294
+ const table = db.prepare("SELECT * FROM task_node WHERE type='1' AND deleted_at IS NULL ORDER BY depth ASC, sort ASC LIMIT 1").get();
295
+ const tableId = table ? String(table.id) : "3";
296
+ const ins = db.prepare(
297
+ "INSERT INTO task(id,title,description,status,priority,difficulty,table_id,timeline_key,restart_key,publish_date,target_date,done_date,shutdown_date,created_at,updated_at,deleted_at,rev) " +
298
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
299
+ );
300
+ const used = new Set();
301
+ for (const t of old) {
302
+ let id = String(t.id);
303
+ if (used.has(id)) id = newId();
304
+ used.add(id);
305
+ const updated = timeMs(t.updated_at, ts);
306
+ const publish = dateText(updated) || todayStr();
307
+ const target = dateText(t.due_at) || publish;
308
+ const done = String(t.status) === "done";
309
+ const tags = String(t.tags || "[]");
310
+ if (tags && tags !== "[]") report.droppedTags += 1;
311
+ ins.run(
312
+ id,
313
+ String(t.title || ""),
314
+ String(t.note === undefined || t.note === null ? "" : t.note),
315
+ done ? "2" : "0",
316
+ mapOldPriority(t.priority),
317
+ null,
318
+ tableId,
319
+ id,
320
+ id,
321
+ publish,
322
+ target,
323
+ done ? dateText(updated) : null,
324
+ null,
325
+ updated,
326
+ updated,
327
+ t.deleted_at === undefined || t.deleted_at === null ? null : Number(t.deleted_at),
328
+ Number(t.rev) || 1,
329
+ );
330
+ }
331
+ const name = legacyName("tasks", ts);
332
+ db.exec("ALTER TABLE tasks RENAME TO " + quoteIdent(name));
333
+ dropIndexesFor(db, name);
334
+ report.legacyTasks = name;
335
+ });
336
+ report.source = "workbench_tasks";
337
+ report.tasks = old.length;
338
+ report.defaultTableId = db.prepare("SELECT id FROM task_node WHERE type='1' AND deleted_at IS NULL LIMIT 1").get().id;
339
+ }
340
+
341
+ /**
342
+ * 任务「类型」已迁到标签域,task.type 列彻底删除。
343
+ * 删列前先把仍有效的旧取值记到 meta.legacy_task_types,供标签迁移消费。
344
+ */
345
+ function dropTaskTypeColumn(db, report) {
346
+ if (!tableExists(db, "task") || !hasColumn(db, "task", "type")) return;
347
+ const rows = db.prepare("SELECT id, type FROM task WHERE type IS NOT NULL AND type<>''").all();
348
+ const legacy = {};
349
+ for (const row of rows) {
350
+ const code = String(row.type);
351
+ if (code === "0" || code === "1" || code === "2" || code === "3") legacy[String(row.id)] = code;
352
+ }
353
+ if (Object.keys(legacy).length) {
354
+ let merged = legacy;
355
+ const prev = metaGet(db, "legacy_task_types");
356
+ if (prev) {
357
+ try {
358
+ merged = Object.assign({}, JSON.parse(String(prev)), legacy);
359
+ } catch (e) {
360
+ merged = legacy;
361
+ }
362
+ }
363
+ metaSet(db, "legacy_task_types", JSON.stringify(merged));
364
+ }
365
+ try {
366
+ db.exec("ALTER TABLE task DROP COLUMN type");
367
+ } catch (e) {
368
+ // 老 SQLite 不支持 DROP COLUMN:重建表。
369
+ const cols = columnsOf(db, "task").filter(function (c) { return c !== "type"; });
370
+ const tmp = "task_drop_type_tmp";
371
+ db.exec("DROP TABLE IF EXISTS " + quoteIdent(tmp));
372
+ db.exec("ALTER TABLE task RENAME TO " + quoteIdent(tmp));
373
+ dropIndexesFor(db, tmp);
374
+ createSchema(db);
375
+ db.exec(
376
+ "INSERT INTO task(" + cols.join(",") + ") SELECT " + cols.join(",") + " FROM " + quoteIdent(tmp),
377
+ );
378
+ db.exec("DROP TABLE " + quoteIdent(tmp));
379
+ }
380
+ report.droppedTypeColumn = true;
381
+ }
382
+
383
+ /** 旧库补 task_node.description(表描述);新库由 NODE_DDL 直接建好。 */
384
+ export function ensureNodeColumns(db, report) {
385
+ if (!tableExists(db, "task_node")) return;
386
+ if (hasColumn(db, "task_node", "description")) return;
387
+ db.exec("ALTER TABLE task_node ADD COLUMN description TEXT NOT NULL DEFAULT ''");
388
+ if (report) report.nodeDescriptionAdded = true;
389
+ }
390
+
391
+ /** 原子删除任务手动排序;失败时恢复索引与列,保留所有任务数据。 */
392
+ function dropTaskSortColumn(db, report) {
393
+ if (!hasColumn(db, "task", "sort")) return;
394
+ db.exec("SAVEPOINT task_drop_sort");
395
+ try {
396
+ db.exec("DROP INDEX IF EXISTS idx_task_sort");
397
+ db.exec("ALTER TABLE task DROP COLUMN sort");
398
+ db.exec("RELEASE task_drop_sort");
399
+ } catch (error) {
400
+ db.exec("ROLLBACK TO task_drop_sort");
401
+ db.exec("RELEASE task_drop_sort");
402
+ throw new Error("任务排序列迁移失败,原数据与索引已保留:" + error.message, { cause: error });
403
+ }
404
+ report.droppedSortColumn = true;
405
+ }
406
+
407
+ export function ensureTaskColumns(db, report) {
408
+ if (!tableExists(db, "task") || !hasColumn(db, "task", "created_at")) return;
409
+ dropTaskSortColumn(db, report || {});
410
+ if (!hasColumn(db, "task", "dedupe_key")) db.exec("ALTER TABLE task ADD COLUMN dedupe_key TEXT");
411
+ if (!hasColumn(db, "task", "review")) db.exec("ALTER TABLE task ADD COLUMN review TEXT NOT NULL DEFAULT ''");
412
+ if (!hasColumn(db, "task", "owner")) db.exec("ALTER TABLE task ADD COLUMN owner TEXT");
413
+ if (!hasColumn(db, "task", "claimed_at")) db.exec("ALTER TABLE task ADD COLUMN claimed_at INTEGER");
414
+ if (!hasColumn(db, "task", "claim_token")) db.exec("ALTER TABLE task ADD COLUMN claim_token TEXT");
415
+ dropTaskTypeColumn(db, report || {});
416
+ }
417
+
418
+ /**
419
+ * 已完成任务不再需要优先级:一次性把历史库里 status=2 的 priority 清零。
420
+ *
421
+ * 新写入由 tasks.js 保证(create/update/bulkUpdate 都会把 DONE 的 priority 归一为 0),
422
+ * 这里只修历史数据。改动走 sync_change_log(origin=migrate),云端能收到这次修正;
423
+ * meta 标记保证只跑一次,之后用户手动改库也不会被反复覆盖。
424
+ */
425
+ /**
426
+ * 优先级不变量回填(幂等,每次启动都跑):
427
+ * - 非 ACTIVE(已关闭/已完成/已重启)一律 P0;
428
+ * - ACTIVE 不允许 P0,历史遗留的 0 值回落到 P1。
429
+ * 只处理未删除行,避免给墓碑行涨 rev;独立库没有 sync_change_log 时跳过变更日志。
430
+ */
431
+ export function normalizePriorities(db, report) {
432
+ const ts = now();
433
+ let cleared = 0;
434
+ let raised = 0;
435
+ try {
436
+ tx(db, function () {
437
+ const updateOne = db.prepare("UPDATE task SET priority=?, updated_at=?, rev=? WHERE id=?");
438
+ const load = db.prepare("SELECT * FROM task WHERE id=?");
439
+ function apply(rows, value) {
440
+ for (const row of rows) {
441
+ const id = String(row.id);
442
+ const rev = Number(row.rev || 0) + 1;
443
+ updateOne.run(value, ts, rev, id);
444
+ const full = load.get(id);
445
+ if (full) {
446
+ try {
447
+ logChange(db, "task", id, "update", full, "migrate", ts);
448
+ } catch (e) {
449
+ /* 独立库(单测/导出)没有 sync_change_log:照常回填,跳过变更日志 */
450
+ }
451
+ }
452
+ }
453
+ return rows.length;
454
+ }
455
+ cleared = apply(
456
+ db.prepare("SELECT id, rev FROM task WHERE status<>'0' AND priority<>0 AND deleted_at IS NULL").all(),
457
+ 0,
458
+ );
459
+ raised = apply(
460
+ db.prepare("SELECT id, rev FROM task WHERE status='0' AND priority=0 AND deleted_at IS NULL").all(),
461
+ 1,
462
+ );
463
+ });
464
+ } catch (e) {
465
+ if (report) report.prioritiesError = String((e && e.message) || e);
466
+ return { cleared: 0, raised: 0 };
467
+ }
468
+ if (report) {
469
+ report.prioritiesCleared = cleared;
470
+ report.prioritiesRaised = raised;
471
+ }
472
+ return { cleared, raised };
473
+ }
package/lib/db/db.js ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 任务子插件:schema 入口(ensureSchema)。
3
+ *
4
+ * 具体实现按职责拆到 db-core.js(通用/建表)与 db-legacy.js(旧库迁移),
5
+ * 本文件只保留迁移编排,并对调用方保持原有导出面。
6
+ */
7
+ import { tableExists, columnsOf, hasColumn, metaSet, now, createSchema, seedDefaultTree } from "./db-core.js";
8
+ import {
9
+ migrateLegacy,
10
+ migrateCurrentTasks,
11
+ ensureTaskColumns,
12
+ ensureNodeColumns,
13
+ normalizePriorities,
14
+ } from "./db-legacy.js";
15
+
16
+ export * from "./db-core.js";
17
+ export { migrateLegacy, migrateCurrentTasks, ensureTaskColumns, ensureNodeColumns, normalizePriorities } from "./db-legacy.js";
18
+
19
+ export function ensureSchema(db, log) {
20
+ if (!tableExists(db, "meta")) {
21
+ db.exec("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL);");
22
+ }
23
+ const report = {
24
+ at: new Date(now()).toISOString(),
25
+ source: "existing",
26
+ tasks: 0,
27
+ nodes: 0,
28
+ orphanNodes: 0,
29
+ orphanTasks: 0,
30
+ droppedTags: 0,
31
+ droppedTypeColumn: false,
32
+ droppedSortColumn: false,
33
+ droppedDependencyTable: false,
34
+ };
35
+
36
+ const hasTask = tableExists(db, "task");
37
+ const hasNode = tableExists(db, "task_node");
38
+ const hasTasks = tableExists(db, "tasks");
39
+
40
+ if (hasTask) {
41
+ const cols = columnsOf(db, "task");
42
+ const isNew = cols.indexOf("created_at") >= 0 && cols.indexOf("updated_at") >= 0 && cols.indexOf("rev") >= 0;
43
+ const isLegacy = cols.indexOf("create_time") >= 0 || (cols.indexOf("table_id") >= 0 && cols.indexOf("description") >= 0 && cols.indexOf("created_at") < 0);
44
+ if (!isNew && !isLegacy) throw new Error("检测到未知的 task 表结构,拒绝自动迁移");
45
+ if (isLegacy) {
46
+ migrateLegacy(db, report);
47
+ } else {
48
+ if (hasNode && columnsOf(db, "task_node").indexOf("parent_id") < 0) {
49
+ throw new Error("task 是新表,但 task_node 仍是旧 MPTT 表,拒绝混合迁移");
50
+ }
51
+ ensureTaskColumns(db, report);
52
+ ensureNodeColumns(db, report);
53
+ createSchema(db);
54
+ seedDefaultTree(db);
55
+ report.tasks = db.prepare("SELECT COUNT(*) AS n FROM task").get().n;
56
+ report.nodes = db.prepare("SELECT COUNT(*) AS n FROM task_node").get().n;
57
+ }
58
+ } else if (hasNode) {
59
+ migrateLegacy(db, report);
60
+ } else if (hasTasks) {
61
+ migrateCurrentTasks(db, report);
62
+ } else {
63
+ createSchema(db);
64
+ seedDefaultTree(db);
65
+ report.source = "fresh";
66
+ }
67
+
68
+ // 5.0.0 起任务依赖整体移除:旧库把 task_dep 表 DROP 掉,不再保留墓碑行。
69
+ if (tableExists(db, "task_dep")) {
70
+ db.exec("DROP TABLE IF EXISTS task_dep");
71
+ report.droppedDependencyTable = true;
72
+ }
73
+
74
+ // 旧库补列/删列必须先完成,再补建当前 schema 的索引。
75
+ ensureTaskColumns(db, report);
76
+ ensureNodeColumns(db, report);
77
+ createSchema(db);
78
+ if (hasColumn(db, "task", "created_at")) {
79
+ try {
80
+ db.exec("CREATE INDEX IF NOT EXISTS idx_task_dedupe ON task(dedupe_key) WHERE dedupe_key IS NOT NULL");
81
+ } catch (e) {
82
+ if (log) log("[tasks] 索引补建失败:" + String((e && e.message) || e));
83
+ }
84
+ }
85
+ seedDefaultTree(db);
86
+ if (hasColumn(db, "task", "priority") && hasColumn(db, "task", "status")) {
87
+ try {
88
+ normalizePriorities(db, report);
89
+ } catch (e) {
90
+ if (log) log("[tasks] 优先级回填失败:" + String((e && e.message) || e));
91
+ }
92
+ }
93
+ metaSet(db, "task_schema_version", "6");
94
+ metaSet(db, "task_migration_report", JSON.stringify(report));
95
+ if (log) log("[tasks] migration", report);
96
+ return report;
97
+ }
@@ -0,0 +1,33 @@
1
+ /** 归属路径校验和邻接链派生;纯函数,不依赖任务业务模块。 */
2
+ export function ownershipError(code, message, details = {}) {
3
+ const candidateTables = (details.candidateTables || []).slice(0,5);
4
+ const nextActions = details.nextActions || ['tasks.capabilities({limit:50})', 'tasks.resolveTable({query:"任务主题"})', '确认后使用 tablePath + createMissing:true + pathDescriptions;拿不准就问用户'];
5
+ const error = new Error(code + ':' + message + ';未执行本次写入。' + (candidateTables.length ? ' 候选:' + JSON.stringify(candidateTables) : '') + ' 下一步:' + nextActions.join(';') + (details.candidates ? ' 冲突:' + JSON.stringify(details.candidates) : ''));
6
+ error.code = code;
7
+ error.details = { code, message, candidateTables, nextActions, retryable: false, ...details };
8
+ return error;
9
+ }
10
+ export function pathFromMap(id, map) {
11
+ const chain = [], seen = new Set();
12
+ let cur = map.get(String(id));
13
+ if (!cur) throw ownershipError('TABLE_NOT_FOUND', '任务表不存在:' + id);
14
+ while (cur) {
15
+ const key = String(cur.id);
16
+ if (seen.has(key)) throw ownershipError('TREE_CORRUPT', '任务树存在环:' + key);
17
+ if (cur.deleted_at != null) throw ownershipError('TREE_CORRUPT', '任务树含已删除节点:' + key);
18
+ if (String(cur.type) === '2' && String(cur.parent_id) !== '0') throw ownershipError('TREE_CORRUPT', '逻辑根不能挂在其它节点下');
19
+ seen.add(key); chain.unshift(cur);
20
+ if (String(cur.parent_id) === '0') {
21
+ if (String(cur.type) !== '2') throw ownershipError('TREE_CORRUPT', '祖先链未终止于逻辑根');
22
+ break;
23
+ }
24
+ cur = map.get(String(cur.parent_id));
25
+ if (!cur) throw ownershipError('TREE_CORRUPT', '任务树祖先缺失');
26
+ if (!['0', '2'].includes(String(cur.type))) throw ownershipError('TREE_CORRUPT', '任务表不能充当祖先');
27
+ }
28
+ const roots = [...map.values()].filter(n => n.deleted_at == null && String(n.parent_id) === '0');
29
+ if (roots.length !== 1 || String(roots[0].id) !== String(chain[0].id)) throw ownershipError('TREE_CORRUPT', '需要唯一逻辑根');
30
+ const pathSegments = chain.map(n => ({ id: String(n.id), name: String(n.name), type: String(n.type), description: String(n.description || '') }));
31
+ const names = pathSegments.slice(1).map(n => n.name);
32
+ return { path: pathSegments.map(n => n.name).join(' / '), tablePath: names.some(n => n.includes('/')) ? names : names.join('/'), pathSegments };
33
+ }
@@ -0,0 +1,7 @@
1
+ export const TIMELINE_DDL = [
2
+ "CREATE TABLE IF NOT EXISTS task_timeline (id TEXT NOT NULL PRIMARY KEY,title TEXT NOT NULL DEFAULT '',description TEXT NOT NULL DEFAULT '',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,deleted_at INTEGER,rev INTEGER NOT NULL DEFAULT 1 CHECK(rev>=1))",
3
+ "CREATE INDEX IF NOT EXISTS idx_task_timeline_updated_at ON task_timeline(updated_at)",
4
+ "CREATE TABLE IF NOT EXISTS task_timeline_link (id TEXT NOT NULL PRIMARY KEY,task_id TEXT NOT NULL UNIQUE,timeline_id TEXT NOT NULL,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,deleted_at INTEGER,rev INTEGER NOT NULL DEFAULT 1 CHECK(rev>=1))",
5
+ "CREATE INDEX IF NOT EXISTS idx_task_timeline_link_timeline_id ON task_timeline_link(timeline_id)",
6
+ "CREATE INDEX IF NOT EXISTS idx_task_timeline_link_updated_at ON task_timeline_link(updated_at)",
7
+ ];
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 工作区实体与任务关联的 DDL。
3
+ *
4
+ * 任务与工作区是多对多:一个任务可挂 0..n 个工作区,一个工作区可挂 0..n 个任务。
5
+ * link 的 id 是确定性的 workspace_id + ":" + task_id(多设备同步幂等),
6
+ * 唯一索引只覆盖存活行,软删后允许重新建立同一条关联。
7
+ */
8
+ export const WORKSPACE_DDL = [
9
+ "CREATE TABLE IF NOT EXISTS task_workspace (id TEXT NOT NULL PRIMARY KEY,title TEXT NOT NULL DEFAULT '',name TEXT NOT NULL DEFAULT '',description TEXT NOT NULL DEFAULT '',dir TEXT,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,deleted_at INTEGER,rev INTEGER NOT NULL DEFAULT 1 CHECK(rev>=1))",
10
+ "CREATE INDEX IF NOT EXISTS idx_task_workspace_updated_at ON task_workspace(updated_at)",
11
+ "CREATE TABLE IF NOT EXISTS task_workspace_link (id TEXT NOT NULL PRIMARY KEY,workspace_id TEXT NOT NULL,task_id TEXT NOT NULL,created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,deleted_at INTEGER,rev INTEGER NOT NULL DEFAULT 1 CHECK(rev>=1))",
12
+ "CREATE UNIQUE INDEX IF NOT EXISTS uk_task_workspace_link ON task_workspace_link(workspace_id,task_id) WHERE deleted_at IS NULL",
13
+ "CREATE INDEX IF NOT EXISTS idx_task_workspace_link_task_id ON task_workspace_link(task_id)",
14
+ "CREATE INDEX IF NOT EXISTS idx_task_workspace_link_workspace_id ON task_workspace_link(workspace_id)",
15
+ ];