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,371 @@
1
+ /**
2
+ * 任务 ↔ 标签域(wb-addon-tags)的适配层。
3
+ *
4
+ * 与 sites 的做法保持一致:tag 表归标签域所有,任务侧只读写
5
+ * tag_mapping 中 item_type='task' 的行;标签域未安装时整块标签能力降级,
6
+ * 任务照常读写,只是没有标签。
7
+ *
8
+ * 唯一一次「代写标签」是迁移:把旧的「工作/生活/学习/开发」类型补成同名
9
+ * 标签,否则老任务会集体变成未打标签。迁移用 meta 标记,只跑一次。
10
+ */
11
+
12
+ import { idOf, newId, logChange, tableExists, metaGet, metaSet, tx } from "../db/db.js";
13
+ import { TAG_SOURCE, TAG_SOURCE_OWNER, TAG_SOURCE_TITLE, ensureTagSource, withTagSource } from "./source.js";
14
+
15
+ export const TAG_ITEM_TYPE = "task";
16
+
17
+ /** 旧 type 0..3 对应的标签名;也是 tab 1..4 的兼容标签。 */
18
+ export const LEGACY_TYPE_TAGS = { "0": "工作", "1": "生活", "2": "学习", "3": "开发" };
19
+
20
+ const MIGRATION_KEY = "tags_from_types_v1";
21
+
22
+ export function tagsAvailable(db, api) {
23
+ return !!api && typeof api.hasDomain === "function" && api.hasDomain("wb-addon-tags") &&
24
+ tableExists(db, "tag_mapping") && tableExists(db, "tag");
25
+ }
26
+
27
+ export function normalizeTagIds(raw) {
28
+ let ids = raw;
29
+ if (typeof ids === "string") ids = ids.split(",");
30
+ if (!Array.isArray(ids)) return [];
31
+ const out = [];
32
+ for (const v of ids) {
33
+ const id = idOf(v);
34
+ if (id && out.indexOf(id) < 0) out.push(id);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /** 标签名列表 → 小写后的去重名字数组(用于按名字过滤/建标签)。 */
40
+ export function normalizeTagNames(raw) {
41
+ let names = raw;
42
+ if (typeof names === "string") names = names.split(/[,,]/);
43
+ if (!Array.isArray(names)) return [];
44
+ const out = [];
45
+ for (const v of names) {
46
+ const name = String(v === undefined || v === null ? "" : v).trim();
47
+ if (name && out.indexOf(name) < 0) out.push(name);
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /**
53
+ * 「可用标签」提示:报错时把候选标签列出来,让调用方一次就能改对,
54
+ * 而不是只知道「标签不存在」还要再调一次 tasks.tags 才能看到有哪些。
55
+ */
56
+ export function availableTagsText(db, limit) {
57
+ const max = Number.isFinite(Number(limit)) ? Math.max(1, Math.min(50, Math.floor(Number(limit)))) : 20;
58
+ const totalRow = db.prepare("SELECT COUNT(*) AS n FROM tag WHERE deleted_at IS NULL").get();
59
+ const total = Number((totalRow && totalRow.n) || 0);
60
+ if (!total) return "当前还没有任何标签(先 tags.create,或打开 form.autoCreateTags 让写入时自动创建)";
61
+ const rows = db.prepare("SELECT id, name FROM tag WHERE deleted_at IS NULL ORDER BY name ASC LIMIT ?").all(max);
62
+ const listed = rows.map(function (r) { return String(r.name) + "(" + String(r.id) + ")"; }).join("、");
63
+ return "可用标签(共 " + total + " 个" + (total > rows.length ? ",只列前 " + rows.length + " 个" : "") + "):" + listed;
64
+ }
65
+
66
+ export function requireTagRows(db, tagIds) {
67
+ const rows = [];
68
+ const missing = [];
69
+ for (const id of tagIds) {
70
+ const row = db.prepare("SELECT * FROM tag WHERE id=? AND deleted_at IS NULL").get(id);
71
+ if (!row) missing.push(String(id));
72
+ else rows.push(row);
73
+ }
74
+ if (missing.length) {
75
+ throw new Error(
76
+ "标签 id 不存在:" + missing.join("、") + "。" + availableTagsText(db, 20) +
77
+ "。tagIds / addTagIds 必须是已存在的标签 id,不会按 id 自动创建;按名字挂标签请改用 tags / addTags",
78
+ );
79
+ }
80
+ return rows;
81
+ }
82
+
83
+ export function tagIdsByNames(db, names) {
84
+ const ids = [];
85
+ const missing = [];
86
+ for (const name of names) {
87
+ const row = db.prepare("SELECT id FROM tag WHERE name=? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 1").get(name);
88
+ if (row) ids.push(String(row.id));
89
+ else missing.push(name);
90
+ }
91
+ return { ids: ids, missing: missing };
92
+ }
93
+
94
+ /**
95
+ * 按名字取标签 id;没有就建。标签名唯一(uk_tag_name),并发撞索引时回查已有 id,
96
+ * 避免把「另一端刚建好的同名标签」当成失败。
97
+ */
98
+ export function ensureTagIdByName(db, name, ts, origin) {
99
+ const sql = "SELECT * FROM tag WHERE name=? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 1";
100
+ const hit = db.prepare(sql).get(name);
101
+ if (hit) return String(hit.id);
102
+ const id = newId();
103
+ try {
104
+ db.prepare(
105
+ "INSERT INTO tag(id,name,created_at,updated_at,deleted_at,rev) VALUES(?,?,?,?,?,?)",
106
+ ).run(id, name, ts, ts, null, 1);
107
+ } catch (e) {
108
+ const again = db.prepare(sql).get(name);
109
+ if (again) return String(again.id);
110
+ throw e;
111
+ }
112
+ logChange(db, "tag", id, "create", {
113
+ id: id, name: name, created_at: ts, updated_at: ts, deleted_at: null, rev: 1,
114
+ }, origin, ts);
115
+ return id;
116
+ }
117
+
118
+ /** 按名字取标签;没有就建。仅用于新建/更新任务时直接传标签名。 */
119
+ export function ensureTagsByNames(db, names, ts, origin) {
120
+ const ids = [];
121
+ for (const name of names) ids.push(ensureTagIdByName(db, name, ts, origin));
122
+ return ids;
123
+ }
124
+
125
+ /** 用 tagIds 全量替换某任务的标签;软删复用旧 mapping,避免每次写都新增历史行。 */
126
+ function writeTaskTags(db, taskId, tagIds, ts, origin) {
127
+ const current = db.prepare(
128
+ "SELECT * FROM tag_mapping WHERE item_type=? AND item_id=? AND deleted_at IS NULL",
129
+ ).all(TAG_ITEM_TYPE, String(taskId));
130
+ const byTag = new Map();
131
+ for (const m of current) byTag.set(String(m.tag_id), m);
132
+ const wanted = new Set(tagIds.map(String));
133
+ for (const m of current) {
134
+ if (wanted.has(String(m.tag_id))) continue;
135
+ db.prepare("UPDATE tag_mapping SET deleted_at=?, updated_at=?, rev=rev+1 WHERE id=?").run(ts, ts, String(m.id));
136
+ logChange(db, "tag_mapping", String(m.id), "delete", null, origin, ts);
137
+ }
138
+ for (const tagId of tagIds) {
139
+ if (byTag.has(String(tagId))) continue;
140
+ const deleted = db.prepare(
141
+ "SELECT * FROM tag_mapping WHERE item_type=? AND item_id=? AND tag_id=? AND deleted_at IS NOT NULL ORDER BY updated_at DESC LIMIT 1",
142
+ ).get(TAG_ITEM_TYPE, String(taskId), String(tagId));
143
+ if (deleted) {
144
+ db.prepare("UPDATE tag_mapping SET deleted_at=NULL, updated_at=?, rev=rev+1 WHERE id=?").run(ts, String(deleted.id));
145
+ logChange(db, "tag_mapping", String(deleted.id), "upsert", {
146
+ id: String(deleted.id), tag_id: String(tagId), item_id: String(taskId), item_type: TAG_ITEM_TYPE,
147
+ updated_at: ts, deleted_at: null, rev: Number(deleted.rev) + 1,
148
+ }, origin, ts);
149
+ continue;
150
+ }
151
+ const id = newId();
152
+ db.prepare(
153
+ "INSERT INTO tag_mapping(id,tag_id,item_id,item_type,created_at,updated_at,deleted_at,rev) VALUES(?,?,?,?,?,?,?,?)",
154
+ ).run(id, String(tagId), String(taskId), TAG_ITEM_TYPE, ts, ts, null, 1);
155
+ logChange(db, "tag_mapping", id, "create", {
156
+ id: id, tag_id: String(tagId), item_id: String(taskId), item_type: TAG_ITEM_TYPE,
157
+ created_at: ts, updated_at: ts, deleted_at: null, rev: 1,
158
+ }, origin, ts);
159
+ }
160
+ }
161
+
162
+ export function tagsForTasks(db, ids) {
163
+ const map = new Map();
164
+ if (!ids.length) return map;
165
+ const marks = ids.map(function () { return "?"; }).join(",");
166
+ const rows = db.prepare(
167
+ "SELECT m.item_id AS item_id, t.id AS id, t.name AS name FROM tag_mapping m JOIN tag t ON t.id=m.tag_id " +
168
+ "WHERE m.item_type=? AND m.deleted_at IS NULL AND t.deleted_at IS NULL AND m.item_id IN (" + marks + ") " +
169
+ "ORDER BY t.name ASC",
170
+ ).all(...[TAG_ITEM_TYPE].concat(ids.map(String)));
171
+ for (const row of rows) {
172
+ const key = String(row.item_id);
173
+ if (!map.has(key)) map.set(key, []);
174
+ map.get(key).push({ id: String(row.id), name: String(row.name || "") });
175
+ }
176
+ return map;
177
+ }
178
+
179
+ /** 给 taskOut 结果补 tags / tagIds;标签域未安装时补空数组,方便前端直接用。 */
180
+ export function attachTags(db, api, records) {
181
+ const list = Array.isArray(records) ? records : [records];
182
+ const available = tagsAvailable(db, api);
183
+ const map = available ? tagsForTasks(db, list.map(function (t) { return t.id; })) : new Map();
184
+ for (const t of list) {
185
+ if (!available) {
186
+ // 标签域未安装:省略 tags/tagIds,别让调用方以为「这个任务真的没有标签」。
187
+ delete t.tags;
188
+ delete t.tagIds;
189
+ continue;
190
+ }
191
+ const tags = map.get(String(t.id)) || [];
192
+ t.tags = tags;
193
+ t.tagIds = tags.map(function (x) { return x.id; });
194
+ }
195
+ return records;
196
+ }
197
+
198
+ /** 给一个任务补一个标签(按名,缺标签就建);已有映射则跳过。导入旧备份时用。 */
199
+ function writeTaskTagByName(db, taskId, name, ts, origin) {
200
+ const ids = ensureTagsByNames(db, [name], ts, origin);
201
+ const tagId = ids[0];
202
+ const exists = db.prepare(
203
+ "SELECT 1 AS ok FROM tag_mapping WHERE item_type=? AND item_id=? AND tag_id=? AND deleted_at IS NULL",
204
+ ).get(TAG_ITEM_TYPE, String(taskId), String(tagId));
205
+ if (exists) return false;
206
+ const id = newId();
207
+ db.prepare(
208
+ "INSERT INTO tag_mapping(id,tag_id,item_id,item_type,created_at,updated_at,deleted_at,rev) VALUES(?,?,?,?,?,?,?,?)",
209
+ ).run(id, String(tagId), String(taskId), TAG_ITEM_TYPE, ts, ts, null, 1);
210
+ logChange(db, "tag_mapping", id, "create", {
211
+ id: id, tag_id: String(tagId), item_id: String(taskId), item_type: TAG_ITEM_TYPE,
212
+ created_at: ts, updated_at: ts, deleted_at: null, rev: 1,
213
+ }, origin, ts);
214
+ return true;
215
+ }
216
+
217
+
218
+ /**
219
+ * 启动时幂等登记本域来源(`tag_mapping.item_type='task'`)。
220
+ * 标签域未装或版本过低时静默跳过;重复注册不阻断启动,写入门禁会在写入时给出可读错误。
221
+ */
222
+ export function ensureTaskTagSource(db, log) {
223
+ if (!tableExists(db, "tag_source")) return { ok: false, skipped: "no_table" };
224
+ try {
225
+ const r = ensureTagSource(db, TAG_SOURCE, TAG_SOURCE_OWNER, TAG_SOURCE_TITLE);
226
+ const ready = tableExists(db, "tag_source")
227
+ ? db.prepare("SELECT COUNT(*) AS n FROM tag_source WHERE source=? AND deleted_at IS NULL").get(TAG_SOURCE)
228
+ : null;
229
+ const count = Number((ready && ready.n) || 0);
230
+ if (count !== 1 && typeof log === "function") {
231
+ log("标签来源登记异常(" + TAG_SOURCE + "):当前 " + count + " 条活跃注册,标签写入会被拒绝");
232
+ }
233
+ return { ok: count === 1, count: count, created: !!(r && r.created) };
234
+ } catch (e) {
235
+ if (typeof log === "function") log("标签来源登记失败:" + String((e && e.message) || e));
236
+ return { ok: false, error: String((e && e.message) || e) };
237
+ }
238
+ }
239
+
240
+ /** 用 tagIds 全量替换某任务的标签(写入门禁:来源必须恰好注册一次)。 */
241
+ export function replaceTaskTags(db, taskId, tagIds, ts, origin) {
242
+ return withTagSource(db, TAG_SOURCE, function () {
243
+ return writeTaskTags(db, taskId, tagIds, ts, origin);
244
+ });
245
+ }
246
+
247
+ /** 给一个任务补一个标签(按名,缺标签就建);已有映射则跳过。导入旧备份时用。 */
248
+ export function addTaskTagByName(db, taskId, name, ts, origin) {
249
+ return withTagSource(db, TAG_SOURCE, function () {
250
+ return writeTaskTagByName(db, taskId, name, ts, origin);
251
+ });
252
+ }
253
+
254
+ export const STATUS_FIELDS = [
255
+ ["total", null],
256
+ ["open", "0"],
257
+ ["shutdown", "1"],
258
+ ["done", "2"],
259
+ ["restarted", "3"],
260
+ ];
261
+
262
+ export function countsOf(row) {
263
+ const out = { total: 0, open: 0, shutdown: 0, done: 0, restarted: 0 };
264
+ for (const pair of STATUS_FIELDS) out[pair[0]] = Number((row && row[pair[0]]) || 0);
265
+ return out;
266
+ }
267
+
268
+ /** 左栏标签导航:所有标签 + 各自任务数,末尾附「未打标签」计数。 */
269
+ export function tagNavStats(db, api) {
270
+ if (!tagsAvailable(db, api)) {
271
+ return { available: false, tags: [], untagged: { total: 0, open: 0, shutdown: 0, done: 0, restarted: 0 } };
272
+ }
273
+ const rows = db.prepare(
274
+ "SELECT g.id AS id, g.name AS name, " +
275
+ STATUS_FIELDS.map(function (p) {
276
+ return p[1] === null
277
+ ? "COUNT(t.id) AS total"
278
+ : "SUM(CASE WHEN t.status='" + p[1] + "' THEN 1 ELSE 0 END) AS " + p[0];
279
+ }).join(", ") + " " +
280
+ "FROM tag g " +
281
+ "LEFT JOIN tag_mapping m ON m.tag_id=g.id AND m.item_type='task' AND m.deleted_at IS NULL " +
282
+ "LEFT JOIN task t ON t.id=m.item_id AND t.deleted_at IS NULL " +
283
+ "WHERE g.deleted_at IS NULL GROUP BY g.id, g.name " +
284
+ "ORDER BY total DESC, g.name ASC",
285
+ ).all();
286
+ const tags = rows.map(function (row) {
287
+ return Object.assign({ id: String(row.id), name: String(row.name || "") }, countsOf(row));
288
+ });
289
+ const untaggedRow = db.prepare(
290
+ "SELECT " + STATUS_FIELDS.map(function (p) {
291
+ return p[1] === null
292
+ ? "COUNT(*) AS total"
293
+ : "SUM(CASE WHEN status='" + p[1] + "' THEN 1 ELSE 0 END) AS " + p[0];
294
+ }).join(", ") + " FROM task " +
295
+ "WHERE deleted_at IS NULL AND NOT EXISTS (" +
296
+ "SELECT 1 FROM tag_mapping m WHERE m.item_type='task' AND m.item_id=task.id AND m.deleted_at IS NULL)",
297
+ ).get();
298
+ return { available: true, tags: tags, untagged: countsOf(untaggedRow) };
299
+ }
300
+
301
+ /** 统计页的「标签 × 状态」分组;多标签任务会出现在多个分组里。 */
302
+ export function tagBreakdown(db, api) {
303
+ const nav = tagNavStats(db, api);
304
+ if (!nav.available) return { rows: [], untagged: nav.untagged };
305
+ const rows = nav.tags.map(function (x) {
306
+ return { key: x.id, label: x.name, total: x.total, open: x.open, done: x.done, shutdown: x.shutdown, restarted: x.restarted };
307
+ });
308
+ if (nav.untagged.total > 0) {
309
+ rows.push({
310
+ key: "untagged", label: "未打标签", total: nav.untagged.total, open: nav.untagged.open,
311
+ done: nav.untagged.done, shutdown: nav.untagged.shutdown, restarted: nav.untagged.restarted,
312
+ });
313
+ }
314
+ return { rows: rows, untagged: nav.untagged };
315
+ }
316
+
317
+ /**
318
+ * 把旧类型迁移成标签(幂等):
319
+ * 1) 工作/生活/学习/开发 四个标签缺失就补建;
320
+ * 2) meta.legacy_task_types(删 type 列前记下的 {taskId: "0".."3"})里的任务补标签;
321
+ * 3) 写入 meta 标记,之后不再执行。
322
+ * 标签域未安装时直接跳过,等装好标签域后的第一次调用再补。
323
+ */
324
+ export function migrateLegacyTypes(db, api, origin) {
325
+ if (!tagsAvailable(db, api)) return { migrated: false, reason: "标签域未安装" };
326
+ if (metaGet(db, MIGRATION_KEY)) return { migrated: false, reason: "已迁移" };
327
+ let legacy = {};
328
+ const raw = metaGet(db, "legacy_task_types");
329
+ if (raw) {
330
+ try {
331
+ legacy = JSON.parse(String(raw)) || {};
332
+ } catch (e) {
333
+ legacy = {};
334
+ }
335
+ }
336
+ let tagsCreated = 0;
337
+ let mappings = 0;
338
+ const ts = Date.now();
339
+ tx(db, function () {
340
+ for (const code of Object.keys(LEGACY_TYPE_TAGS)) {
341
+ const name = LEGACY_TYPE_TAGS[code];
342
+ const taskIds = Object.keys(legacy).filter(function (id) {
343
+ return String(legacy[id]) === code;
344
+ });
345
+ if (!taskIds.length) continue;
346
+ const existed = db.prepare("SELECT 1 AS ok FROM tag WHERE name=? AND deleted_at IS NULL").get(name);
347
+ const tagId = ensureTagIdByName(db, name, ts, origin || "migrate");
348
+ const tag = { id: tagId, name: name };
349
+ if (!existed) tagsCreated += 1;
350
+ for (const taskId of taskIds) {
351
+ const alive = db.prepare("SELECT 1 AS ok FROM task WHERE id=? AND deleted_at IS NULL").get(String(taskId));
352
+ if (!alive) continue;
353
+ const exists = db.prepare(
354
+ "SELECT 1 AS ok FROM tag_mapping WHERE item_type=? AND item_id=? AND tag_id=? AND deleted_at IS NULL",
355
+ ).get(TAG_ITEM_TYPE, String(taskId), String(tag.id));
356
+ if (exists) continue;
357
+ const id = newId();
358
+ db.prepare(
359
+ "INSERT INTO tag_mapping(id,tag_id,item_id,item_type,created_at,updated_at,deleted_at,rev) VALUES(?,?,?,?,?,?,?,?)",
360
+ ).run(id, String(tag.id), String(taskId), TAG_ITEM_TYPE, ts, ts, null, 1);
361
+ logChange(db, "tag_mapping", id, "create", {
362
+ id: id, tag_id: String(tag.id), item_id: String(taskId), item_type: TAG_ITEM_TYPE,
363
+ created_at: ts, updated_at: ts, deleted_at: null, rev: 1,
364
+ }, origin || "migrate", ts);
365
+ mappings += 1;
366
+ }
367
+ }
368
+ metaSet(db, MIGRATION_KEY, String(ts));
369
+ });
370
+ return { migrated: true, tagsCreated: tagsCreated, mappings: mappings };
371
+ }
@@ -0,0 +1,15 @@
1
+ /** 难度语义唯一真源:action schema、能力引导和字段说明共用。 */
2
+ export const DIFFICULTY_GUIDANCE = "0/null = 未设置(不是最简单);1–5 数值越大越难:1 = 改文案/样式等单点小改,2 = 单模块内的局部功能,3 = 跨 2–3 个模块或带数据读取变更,4 = 涉及存储/迁移/同步/构建链路,5 = 跨进程架构重构或需多阶段验证。依据改动文件数、是否涉及数据迁移与测试面判定;兼容 0.5 档。create/update 建议填写 1–5,未完成任务也可保存;已完成任务应填写,但不做硬必填。";
3
+ export const DIFFICULTY_SCHEMA = { type: ["number", "null"], minimum: 0, maximum: 5, description: DIFFICULTY_GUIDANCE };
4
+
5
+ export function difficultyMissingNotices(args, difficulty) {
6
+ const hasContext = String(args.description ?? "").trim() || [args.tags, args.tagIds].some(values => Array.isArray(values) && values.length);
7
+ return hasContext && !(Number(difficulty) > 0)
8
+ ? [{ code: "difficulty_missing", field: "difficulty", message: "建议填写 1–5 难度;0 会被统计为未设置" }]
9
+ : [];
10
+ }
11
+
12
+ export function cleanDifficultyReceipt(task) {
13
+ if (task.difficulty === null || task.difficulty === undefined) delete task.difficulty;
14
+ return task;
15
+ }
@@ -0,0 +1,256 @@
1
+ // 模型助手;与 task-bulk 的循环引用只在调用期取值,顶层不求值。
2
+ import {
3
+ idOf,
4
+ dateText,
5
+ logChange,
6
+ taskOut,
7
+ nodeMap,
8
+ } from "../../db/db.js";
9
+ // task-query 循环依赖仅在调用期读取 tasks 的函数/常量。
10
+ import { configValues } from "../../infra/config.js";
11
+ import {
12
+ normalizeTagIds,
13
+ normalizeTagNames,
14
+ requireTagRows,
15
+ availableTagsText,
16
+ tagIdsByNames,
17
+ ensureTagsByNames,
18
+ } from "../../tagging/tagging.js";
19
+ /**
20
+ * 标签名校验:默认(form.autoCreateTags=true)未知名字会被补建;
21
+ * 关掉开关后未知名字直接报错,并把可用标签列出来,调用方一次就能改成已存在的名字。
22
+ */
23
+ export function requireKnownTagNames(db, tagNames) {
24
+ if (!tagNames || !tagNames.length) return;
25
+ const values = configValues(db);
26
+ if (values["form.autoCreateTags"] !== false) return;
27
+ const missing = tagIdsByNames(db, tagNames).missing;
28
+ if (missing.length) {
29
+ throw new Error(
30
+ "标签不存在:" + missing.join("、") + "。" + availableTagsText(db, 20) +
31
+ "。当前 form.autoCreateTags=false(写入时不自动创建标签):可改用上面已有的标签名," +
32
+ "或在配置页打开「自动创建未知标签」(tasks.configSet key=form.autoCreateTags value=true)",
33
+ );
34
+ }
35
+ }
36
+
37
+ /**
38
+ * 标签域(dsh-workbench-tags)是可选能力:没装时任务照常读写,只是忽略标签参数,
39
+ * 并在回执里带一条 notices,让调用方知道「标签没处理」而不是「任务没写成」。
40
+ */
41
+ export const TAG_DOMAIN_NOTICE = {
42
+ code: "tag_domain_missing",
43
+ field: "tags",
44
+ message: "标签模块没有安装,无法处理标签数据;本次已忽略 tags/tagIds/addTags/removeTags",
45
+ };
46
+
47
+ function hasTagArgs(source) {
48
+ return source.tagIds !== undefined || source.tags !== undefined
49
+ || source.addTagIds !== undefined || source.addTags !== undefined
50
+ || source.removeTagIds !== undefined || source.removeTags !== undefined;
51
+ }
52
+
53
+ export function tagMissingNotices(source, available) {
54
+ return available || !hasTagArgs(source) ? [] : [Object.assign({}, TAG_DOMAIN_NOTICE)];
55
+ }
56
+
57
+ export function withNotices(result, notices) {
58
+ if (notices && notices.length) result.notices = notices;
59
+ return result;
60
+ }
61
+
62
+ export const STATUSES = ["0", "1", "2", "3", "4"];
63
+ const SOURCES = { TASK_TABLE: "0", TASK_TIMELINE: "1", TASK_RESTART: "2" };
64
+ const PUT_TYPES = { STATUS: "0", PRIORITY: "1", TITLE: "2", DESCRIPTION: "3", REVIEW: "4", CLAIM: "5" };
65
+ export const STATUS_NAMES = { ACTIVE: "0", SHUTDOWN: "1", DONE: "2", RESTARTED: "3", CLAIMED: "4", open: "0", done: "2" };
66
+
67
+ export function asCode(value, names, allowed, label) {
68
+ if (value === undefined || value === null || value === "") return null;
69
+ let s = String(value);
70
+ if (names && names[s] !== undefined) s = names[s];
71
+ if (allowed.indexOf(s) < 0) throw new Error(label + " 取值非法:" + value);
72
+ return s;
73
+ }
74
+
75
+ export function sourceCode(value) {
76
+ if (value === undefined || value === null || value === "") return "0";
77
+ if (SOURCES[String(value)] !== undefined) return SOURCES[String(value)];
78
+ const s = String(value);
79
+ if (["0", "1", "2"].indexOf(s) < 0) throw new Error("source 取值非法:" + value);
80
+ return s;
81
+ }
82
+
83
+ export function putTypeCode(value) {
84
+ if (value === undefined || value === null || value === "") return null;
85
+ if (PUT_TYPES[String(value)] !== undefined) return PUT_TYPES[String(value)];
86
+ const s = String(value);
87
+ if (["0", "1", "2", "3", "4"].indexOf(s) < 0) throw new Error("type 取值非法:" + value);
88
+ return s;
89
+ }
90
+
91
+ export { priorityForStatus } from "./task-priority.js";
92
+
93
+ export function clampDifficulty(value, fallback) {
94
+ if (value === undefined || value === null || value === "") return fallback;
95
+ const n = Number(value);
96
+ if (!Number.isFinite(n)) throw new Error("difficulty 必须是数字");
97
+ if (n < 0 || n > 5) throw new Error("difficulty 必须在 0..5");
98
+ return n;
99
+ }
100
+
101
+ export function dateArg(value, label) {
102
+ if (value === undefined || value === null || value === "") return null;
103
+ const d = dateText(value);
104
+ if (!d) throw new Error(label + " 不是有效日期:" + value);
105
+ return d;
106
+ }
107
+
108
+ export function getTask(db, id) {
109
+ const key = idOf(id);
110
+ if (!key) return null;
111
+ return db.prepare("SELECT * FROM task WHERE id=? AND deleted_at IS NULL").get(key) || null;
112
+ }
113
+
114
+ export function defaultTable(db) {
115
+ const row = db.prepare(
116
+ "SELECT * FROM task_node WHERE type='1' AND deleted_at IS NULL ORDER BY depth ASC, sort ASC LIMIT 1",
117
+ ).get();
118
+ if (!row) throw new Error("还没有任务表,请先在任务树中新建任务表");
119
+ return row;
120
+ }
121
+
122
+ import { requireOwnedTable } from '../write/task-target.js';
123
+ export function requireTable(db, tableId) {
124
+ return requireOwnedTable(db, tableId);
125
+ }
126
+
127
+ export function insertTaskRow(db, row) {
128
+ db.prepare(
129
+ "INSERT INTO task(id,title,description,status,priority,difficulty,review,table_id,timeline_key,restart_key,publish_date,target_date,done_date,shutdown_date,dedupe_key,created_at,updated_at,deleted_at,rev) " +
130
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
131
+ ).run(
132
+ String(row.id),
133
+ String(row.title),
134
+ String(row.description || ""),
135
+ String(row.status),
136
+ Number(row.priority || 0),
137
+ row.difficulty === undefined ? null : row.difficulty,
138
+ String(row.review || ""),
139
+ String(row.table_id),
140
+ row.timeline_key === undefined ? null : row.timeline_key,
141
+ row.restart_key === undefined ? null : row.restart_key,
142
+ String(row.publish_date),
143
+ String(row.target_date),
144
+ row.done_date === undefined ? null : row.done_date,
145
+ row.shutdown_date === undefined ? null : row.shutdown_date,
146
+ row.dedupe_key === undefined ? null : row.dedupe_key,
147
+ Number(row.created_at),
148
+ Number(row.updated_at),
149
+ row.deleted_at === undefined ? null : row.deleted_at,
150
+ Number(row.rev || 1),
151
+ );
152
+ }
153
+
154
+ export function saveTaskRow(db, row) {
155
+ db.prepare(
156
+ "UPDATE task SET title=?,description=?,status=?,priority=?,difficulty=?,review=?,table_id=?,timeline_key=?,restart_key=?,publish_date=?,target_date=?,done_date=?,shutdown_date=?,dedupe_key=?,owner=?,claimed_at=?,claim_token=?,updated_at=?,deleted_at=?,rev=? WHERE id=?",
157
+ ).run(
158
+ String(row.title),
159
+ String(row.description || ""),
160
+ String(row.status),
161
+ Number(row.priority || 0),
162
+ row.difficulty === undefined ? null : row.difficulty,
163
+ String(row.review || ""),
164
+ String(row.table_id),
165
+ row.timeline_key === undefined ? null : row.timeline_key,
166
+ row.restart_key === undefined ? null : row.restart_key,
167
+ String(row.publish_date),
168
+ String(row.target_date),
169
+ row.done_date === undefined ? null : row.done_date,
170
+ row.shutdown_date === undefined ? null : row.shutdown_date,
171
+ row.dedupe_key === undefined ? null : row.dedupe_key,
172
+ row.owner === undefined ? null : row.owner,
173
+ row.claimed_at === undefined ? null : row.claimed_at,
174
+ row.claim_token === undefined ? null : row.claim_token,
175
+ Number(row.updated_at),
176
+ row.deleted_at === undefined ? null : row.deleted_at,
177
+ Number(row.rev || 1),
178
+ String(row.id),
179
+ );
180
+ }
181
+
182
+ export function outOne(db, row) {
183
+ return taskOut(row, nodeMap(db));
184
+ }
185
+
186
+ export function emitChange(api, id, op, kind) {
187
+ api.emit(kind || "tasks-changed", { id: String(id), op: op });
188
+ }
189
+
190
+ export function writeChange(db, row, op, origin, api, ts, kind) {
191
+ logChange(db, "task", row.id, op, op === "delete" ? null : row, origin, ts);
192
+ emitChange(api, row.id, op, kind);
193
+ }
194
+
195
+ export function checkRequiredDates(row) {
196
+ if (!row.publish_date) throw new Error("publishDate 不能为空");
197
+ if (!row.target_date) throw new Error("targetDate 不能为空");
198
+ if (row.target_date < row.publish_date) throw new Error("targetDate 不能早于 publishDate");
199
+ if (row.done_date && row.done_date < row.publish_date) throw new Error("doneDate 不能早于 publishDate");
200
+ if (row.shutdown_date && row.shutdown_date < row.publish_date) throw new Error("shutdownDate 不能早于 publishDate");
201
+ }
202
+
203
+ /** 当前任务挂着的标签 id(未删除)。 */
204
+ export function currentTaskTagIds(db, taskId) {
205
+ return db.prepare("SELECT tag_id FROM tag_mapping WHERE item_type='task' AND item_id=? AND deleted_at IS NULL")
206
+ .all(String(taskId)).map(function (r) { return String(r.tag_id); });
207
+ }
208
+
209
+ /**
210
+ * 把「整体替换」与「增量增删」统一成一个期望标签集合。
211
+ * 返回 null 表示这次不动标签。
212
+ */
213
+ export function resolveTagPatch(db, cur, source, ts, origin, dryRun) {
214
+ const hasReplace = source.tagIds !== undefined || source.tags !== undefined;
215
+ const hasMerge = source.addTagIds !== undefined || source.addTags !== undefined
216
+ || source.removeTagIds !== undefined || source.removeTags !== undefined;
217
+ if (!hasReplace && !hasMerge) return null;
218
+ if (hasReplace && hasMerge) throw new Error("tags/tagIds 是整体替换,不能与 addTags/removeTags 同时使用");
219
+ if (hasReplace) {
220
+ const ids = source.tagIds === undefined || source.tagIds === null ? [] : normalizeTagIds(source.tagIds);
221
+ const names = source.tags === undefined || source.tags === null ? [] : normalizeTagNames(source.tags);
222
+ requireKnownTagNames(db, names);
223
+ if (ids.length) requireTagRows(db, ids);
224
+ const out = ids.slice();
225
+ const nameIds = dryRun ? tagIdsByNames(db, names).ids : ensureTagsByNames(db, names, ts, origin);
226
+ for (const id of nameIds) if (out.indexOf(id) < 0) out.push(id);
227
+ return out;
228
+ }
229
+ const addIds = source.addTagIds === undefined || source.addTagIds === null ? [] : normalizeTagIds(source.addTagIds);
230
+ const addNames = source.addTags === undefined || source.addTags === null ? [] : normalizeTagNames(source.addTags);
231
+ const rmIds = source.removeTagIds === undefined || source.removeTagIds === null ? [] : normalizeTagIds(source.removeTagIds);
232
+ const rmNames = source.removeTags === undefined || source.removeTags === null ? [] : normalizeTagNames(source.removeTags);
233
+ requireKnownTagNames(db, addNames.concat(rmNames));
234
+ if (addIds.length) requireTagRows(db, addIds);
235
+ const add = addIds.slice();
236
+ const addByName = dryRun ? tagIdsByNames(db, addNames).ids : ensureTagsByNames(db, addNames, ts, origin);
237
+ for (const id of addByName) if (add.indexOf(id) < 0) add.push(id);
238
+ const drop = rmIds.slice();
239
+ for (const id of (tagIdsByNames(db, rmNames).ids || [])) if (drop.indexOf(id) < 0) drop.push(id);
240
+ const set = currentTaskTagIds(db, cur.id);
241
+ for (const id of add) if (set.indexOf(id) < 0) set.push(id);
242
+ return set.filter(function (id) { return drop.indexOf(id) < 0; });
243
+ }
244
+ /** bulk* 系列允许直接写的字段(与 tasks.update 的自由字段一致)。 */
245
+ export const PATCH_FIELDS = [
246
+ "title", "description", "status", "priority", "difficulty", "review",
247
+ "publishDate", "targetDate", "doneDate", "shutdownDate", "tableId", "tagIds", "tags",
248
+ "addTagIds", "addTags", "removeTagIds", "removeTags",
249
+ ];
250
+
251
+ export const DIFF_COLUMNS = [
252
+ ["title", "title"], ["description", "description"], ["status", "status"],
253
+ ["priority", "priority"], ["difficulty", "difficulty"], ["review", "review"], ["tableId", "table_id"],
254
+ ["publishDate", "publish_date"], ["targetDate", "target_date"],
255
+ ["doneDate", "done_date"], ["shutdownDate", "shutdown_date"],
256
+ ];
@@ -0,0 +1,22 @@
1
+ /** 归属路径:从邻接链派生展示信息;不修改历史 ID path。 */
2
+ import limits from '../../../shared/tree/limits.cjs';
3
+ const { NAME_MAX, PATH_MAX, PATH_LEN_MAX } = limits;
4
+ import { ownershipError } from "../../db/ownership-path.js";
5
+ export { ownershipError, pathFromMap } from "../../db/ownership-path.js";
6
+ export function parseTablePath(value) {
7
+ if (typeof value !== 'string' && !Array.isArray(value)) throw ownershipError('INVALID_PATH', 'tablePath 必须为字符串或字符串数组');
8
+ const raw = Array.isArray(value) ? value : value.split('/');
9
+ if (!raw.length || raw.length > PATH_MAX || raw.some(s => typeof s !== 'string') || raw.join('/').length > PATH_LEN_MAX) throw ownershipError('INVALID_PATH', `路径最多 ${PATH_MAX} 段、总长 ${PATH_LEN_MAX} 字符,且必须是字符串段`);
10
+ const parts = raw.map(s => s.trim());
11
+ if (parts.some(s => !s || s === '.' || s === '..' || s.length > NAME_MAX)) throw ownershipError('INVALID_PATH', `禁止空段、点段、首尾斜杠;每段最多 ${NAME_MAX} 字符`);
12
+ return parts;
13
+ }
14
+ export function ownershipFields(task) {
15
+ return { tableId: task.tableId, tablePath: task.tablePath, pathSegments: task.pathSegments, tableDescription: task.tableDescription };
16
+ }
17
+ export function renderOwnership(result, verb = '已创建') {
18
+ const task = result.task;
19
+ const path = (task.pathSegments || []).map(n => n.name).join(' / ');
20
+ if (result.dryRun) return '预览(未写入):' + task.title + ' → ' + path + (result.deduped ? '(复用已有任务)' : '(新建记录及节点 ID 为临时值)');
21
+ return (result.deduped ? '任务已存在' : verb + '任务') + ':' + task.title + '(id=' + task.id + ')。已放入 ' + path + ' 表;若不属于,请告诉我目标表或新节点名。纠正:tasks.update({id:' + JSON.stringify(task.id) + ',tableId:"目标表id"})' + (result.notices?.length ? '\n' + result.notices.map(n => n.code + ':' + n.message).join(';') : '');
22
+ }