dsh-workbench-tasks 0.0.0-stage → 5.2.6

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 (54) 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 +11313 -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 +213 -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 +72 -0
  20. package/lib/stats/overview.js +99 -0
  21. package/lib/stats/stats-today.js +26 -0
  22. package/lib/stats/stats.js +542 -0
  23. package/lib/stats/timeline-stats.js +174 -0
  24. package/lib/tagging/tag-options.js +99 -0
  25. package/lib/tagging/tagging.js +333 -0
  26. package/lib/task/model/task-difficulty.js +15 -0
  27. package/lib/task/model/task-model.js +256 -0
  28. package/lib/task/model/task-ownership-path.js +22 -0
  29. package/lib/task/model/task-priority.js +33 -0
  30. package/lib/task/read/task-discovery.js +123 -0
  31. package/lib/task/read/task-publish-filter.js +31 -0
  32. package/lib/task/read/task-query.js +351 -0
  33. package/lib/task/read/task-search-schema.js +34 -0
  34. package/lib/task/read/task-view.js +146 -0
  35. package/lib/task/write/task-bulk.js +247 -0
  36. package/lib/task/write/task-claim.js +229 -0
  37. package/lib/task/write/task-create-schema.js +34 -0
  38. package/lib/task/write/task-create.js +178 -0
  39. package/lib/task/write/task-operations.js +207 -0
  40. package/lib/task/write/task-target.js +56 -0
  41. package/lib/task/write/task-transaction.js +18 -0
  42. package/lib/task/write/task-update.js +104 -0
  43. package/lib/tasks.js +454 -0
  44. package/lib/timeline/task-timelines.js +103 -0
  45. package/lib/timeline/timeline-actions.js +69 -0
  46. package/lib/timeline/timeline-migration.js +70 -0
  47. package/lib/timeline/timeline-store.js +57 -0
  48. package/lib/timeline/timeline-sync.js +46 -0
  49. package/lib/tree/task-node-write.js +26 -0
  50. package/lib/tree/tree.js +517 -0
  51. package/lib/workspace/workspace-actions.js +217 -0
  52. package/lib/workspace/workspace-store.js +196 -0
  53. package/package.json +144 -4
  54. package/shared/tree/limits.cjs +3 -0
@@ -0,0 +1,247 @@
1
+ import { taskTransaction } from './task-transaction.js';
2
+ import { validateTargetArgs } from './task-target.js';
3
+ import { ownershipFields, renderOwnership } from '../model/task-ownership-path.js';
4
+ /**
5
+ * 批量写入:bulkUpdate / bulkCreate / bulkDelete。
6
+ *
7
+ * 复用 tasks.js 的字段校验与行写入助手;这里只管批量语义(dryRun、skipMissing、逐条 change)。
8
+ * 与 tasks.js 是允许的循环依赖:两边都只在调用期取对方的函数,顶层不做求值。
9
+ */
10
+
11
+ import { setMembership, touchTimelines } from "../../timeline/timeline-store.js";
12
+ import { now, idOf, todayStr, logChange, taskOut, nodeMap } from "../../db/db.js";
13
+ import { tagsAvailable, replaceTaskTags } from "../../tagging/tagging.js";
14
+ import {
15
+ PATCH_FIELDS,
16
+ DIFF_COLUMNS,
17
+ STATUSES,
18
+ STATUS_NAMES,
19
+ asCode,
20
+ priorityForStatus,
21
+ clampDifficulty,
22
+ dateArg,
23
+ requireTable,
24
+ checkRequiredDates,
25
+ getTask,
26
+ saveTaskRow,
27
+ writeChange,
28
+ currentTaskTagIds,
29
+ resolveTagPatch,
30
+ withNotices,
31
+ tagMissingNotices,
32
+ createTask,
33
+ emitChange,
34
+ } from "../../tasks.js";
35
+
36
+ export function idList(argsIds) {
37
+ const ids = Array.isArray(argsIds) ? argsIds.map(function (x) { return idOf(x); }).filter(Boolean) : [];
38
+ const seen = new Set();
39
+ const out = [];
40
+ for (const id of ids) {
41
+ if (seen.has(id)) continue;
42
+ seen.add(id);
43
+ out.push(id);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ export function patchOf(raw) {
49
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("patch 必须是对象");
50
+ const patch = {};
51
+ for (const key of Object.keys(raw)) {
52
+ if (PATCH_FIELDS.indexOf(key) >= 0) patch[key] = raw[key];
53
+ }
54
+ const unknown = Object.keys(raw).filter(function (k) { return PATCH_FIELDS.indexOf(k) < 0; });
55
+ if (unknown.length) throw new Error("patch 含不支持的字段:" + unknown.join(", ") + "(可用:" + PATCH_FIELDS.join(", ") + ")");
56
+ if (!Object.keys(patch).length) throw new Error("patch 不能为空");
57
+ return patch;
58
+ }
59
+
60
+ export function diffRow(before, after) {
61
+ const out = {};
62
+ for (const pair of DIFF_COLUMNS) {
63
+ const a = before[pair[1]];
64
+ const b = after[pair[1]];
65
+ if (String(a === undefined ? null : a) !== String(b === undefined ? null : b)) {
66
+ out[pair[0]] = { from: a === undefined ? null : a, to: b === undefined ? null : b };
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /**
73
+ * 按 patch 生成下一版任务行(不落库)。
74
+ * 不复用 updateTask:它的 type 参数是“更新模式”,与任务字段 type 冲突。
75
+ */
76
+ export function applyPatchRow(db, cur, patch, ts) {
77
+ const next = Object.assign({}, cur);
78
+ if ("title" in patch) {
79
+ const title = String(patch.title === null || patch.title === undefined ? "" : patch.title).trim();
80
+ if (!title) throw new Error("title 不能为空");
81
+ next.title = title;
82
+ }
83
+ if ("description" in patch) next.description = String(patch.description === null || patch.description === undefined ? "" : patch.description);
84
+ if ("status" in patch) next.status = asCode(patch.status, STATUS_NAMES, STATUSES, "status");
85
+ if (next.status === "4") {
86
+ const error = new Error("状态「已接取」不能通过 bulkUpdate 直接写入,请使用 tasks.claimBatch 接取");
87
+ error.code = "CLAIM_REQUIRED";
88
+ throw error;
89
+ }
90
+ if ("priority" in patch) next.priority = priorityForStatus(next.status, patch.priority, Number(cur.priority) || 1);
91
+ if ("difficulty" in patch) next.difficulty = clampDifficulty(patch.difficulty, null);
92
+ if ("review" in patch) next.review = String(patch.review === null || patch.review === undefined ? "" : patch.review);
93
+ if ("tableId" in patch) next.table_id = String(requireTable(db, patch.tableId).id);
94
+ if ("publishDate" in patch) next.publish_date = dateArg(patch.publishDate, "publishDate") || String(cur.publish_date);
95
+ if ("targetDate" in patch) next.target_date = dateArg(patch.targetDate, "targetDate") || String(cur.target_date);
96
+ if ("doneDate" in patch) next.done_date = dateArg(patch.doneDate, "doneDate");
97
+ if ("shutdownDate" in patch) next.shutdown_date = dateArg(patch.shutdownDate, "shutdownDate");
98
+ // tagIds 不是 task 列,由 bulkUpdate 在行写入后同步 tag_mapping。
99
+ if (next.status === "2" && !next.done_date) next.done_date = todayStr();
100
+ if (next.status === "2" && (next.difficulty === null || next.difficulty === undefined)) next.difficulty = 0;
101
+ if (next.status !== "0" && next.status !== "4") next.priority = 0;
102
+ else if (!next.priority) next.priority = 1;
103
+ if (next.status === "1" || next.status === "2") { next.owner = null; next.claimed_at = null; next.claim_token = null; }
104
+ if (next.status === "1" && !next.shutdown_date) next.shutdown_date = todayStr();
105
+ checkRequiredDates(next);
106
+ next.updated_at = ts;
107
+ next.rev = Number(cur.rev) + 1;
108
+ return next;
109
+ }
110
+
111
+ export function bulkUpdate(db, args, origin, api, opts) {
112
+ if (!opts?.skipTx) return taskTransaction(db, api, buffered => bulkUpdate(db,args,origin,buffered,{skipTx:true}), args.dryRun === true);
113
+ const ids = idList(args.ids);
114
+ if (!ids.length) throw new Error("ids 不能为空");
115
+ const patch = patchOf(args.patch);
116
+ const wantsTagWrite = patch.tagIds !== undefined || patch.tags !== undefined
117
+ || patch.addTagIds !== undefined || patch.addTags !== undefined
118
+ || patch.removeTagIds !== undefined || patch.removeTags !== undefined;
119
+ const tagWritable = tagsAvailable(db, api);
120
+ const dryRun = args.dryRun === true;
121
+ const skipMissing = args.skipMissing === true;
122
+ const ts = now();
123
+ const changes = [];
124
+ const missing = [];
125
+ const plan = function () {
126
+ for (const id of ids) {
127
+ const cur = getTask(db, id);
128
+ if (!cur) {
129
+ if (skipMissing) {
130
+ missing.push(id);
131
+ continue;
132
+ }
133
+ throw new Error("任务不存在:" + id + "(可用 skipMissing:true 忽略)");
134
+ }
135
+ const next = applyPatchRow(db, cur, patch, ts);
136
+ // 标签名只在真正写入时补建;dryRun 只认已存在的同名标签。
137
+ const desired = wantsTagWrite && tagWritable ? resolveTagPatch(db, cur, patch, ts, origin, dryRun) : null;
138
+ const diff = diffRow(cur, next);
139
+ if (desired) diff.tagIds = { from: currentTaskTagIds(db, id), to: desired };
140
+ const task = taskOut(next,nodeMap(db));
141
+ changes.push({ id: id, changes: diff, task, ...ownershipFields(task) });
142
+ if (!dryRun) {
143
+ saveTaskRow(db, next);
144
+ if (desired) replaceTaskTags(db, id, desired, ts, origin);
145
+ writeChange(db, next, "update", origin, api, ts);
146
+ }
147
+ }
148
+ };
149
+ plan();
150
+ return withNotices({
151
+ dryRun: dryRun,
152
+ updated: dryRun ? 0 : changes.length,
153
+ wouldUpdate: dryRun ? changes.length : undefined,
154
+ changes: changes,
155
+ missing: missing,
156
+ }, tagMissingNotices(patch, tagWritable));
157
+ }
158
+
159
+ export function bulkCreate(db, args, origin, api) {
160
+ const records = Array.isArray(args.records) ? args.records : [];
161
+ if (!records.length) throw new Error("records 不能为空");
162
+ const dryRun = args.dryRun === true;
163
+ return taskTransaction(db,api,buffered => {
164
+ // 先校验每条目标,保证无目标不受前一条记录的临时写入影响。
165
+ for (const rec of records) validateTargetArgs(db,rec || {},buffered);
166
+ const touchedTimelines = new Set();
167
+ const results = records.map(rec => createTask(db, rec || {}, origin, buffered, {skipTx:true,touchedTimelines}));
168
+ touchTimelines(db,touchedTimelines,origin,buffered);
169
+ const actual = results.filter(r=>!r.deduped).length;
170
+ const createdNodes = results.flatMap(r=>r.createdNodes || []);
171
+ return { dryRun, created:dryRun ? 0 : actual, wouldCreate:dryRun ? actual : undefined,
172
+ deduped: results.length-actual, results, tasks:results.map(r=>r.task),
173
+ createdNodes:dryRun ? [] : createdNodes, wouldCreateNodes:dryRun ? createdNodes.map(n=>({...n,temporary:true})) : undefined,
174
+ temporaryIds:dryRun ? [...createdNodes.map(n=>n.id),...results.filter(r=>!r.deduped).map(r=>r.id)] : undefined,
175
+ notices:results.flatMap(r=>r.notices || []),
176
+ };
177
+ },dryRun);
178
+ }
179
+
180
+ export function bulkDelete(db, args, origin, api) {
181
+ const ids = idList(args.ids);
182
+ if (!ids.length) throw new Error("ids 不能为空");
183
+ const dryRun = args.dryRun === true;
184
+ const skipMissing = args.skipMissing === true;
185
+ const ts = now();
186
+ const deleted = [];
187
+ const missing = [];
188
+ const items = [];
189
+ const plan = function (buffered = api) {
190
+ const touched = new Set();
191
+ for (const id of ids) {
192
+ const cur = getTask(db, id);
193
+ if (!cur) {
194
+ if (skipMissing) {
195
+ missing.push(id);
196
+ continue;
197
+ }
198
+ throw new Error("任务不存在:" + id + "(可用 skipMissing:true 忽略)");
199
+ }
200
+ deleted.push(id);
201
+ items.push({ id: id, title: String(cur.title || "") });
202
+ if (!dryRun) {
203
+ setMembership(db,id,null,origin,buffered,{ts,project:false,touched});
204
+ const next = Object.assign({}, cur, { timeline_key:null, deleted_at: ts, updated_at: ts, rev: Number(cur.rev) + 1 });
205
+ saveTaskRow(db, next);
206
+ logChange(db, "task", next.id, "delete", null, origin, ts);
207
+ emitChange(buffered, next.id, "delete");
208
+ }
209
+ }
210
+ if (!dryRun) touchTimelines(db,touched,origin,buffered,ts);
211
+ };
212
+ if (dryRun) plan();
213
+ else taskTransaction(db, api, plan);
214
+ return {
215
+ dryRun: dryRun,
216
+ deleted: dryRun ? 0 : deleted.length,
217
+ wouldDelete: dryRun ? deleted.length : undefined,
218
+ ids: deleted,
219
+ items: items,
220
+ missing: missing,
221
+ };
222
+ }
223
+
224
+ export function renderBulkUpdate(r) {
225
+ const lines = [r.dryRun ? "预览:将更新 " + r.wouldUpdate + " 条任务(未写库)" : "已更新 " + r.updated + " 条任务"];
226
+ for (const c of r.changes) {
227
+ const parts = Object.keys(c.changes).map(function (k) {
228
+ return k + " " + String(c.changes[k].from) + "→" + String(c.changes[k].to);
229
+ });
230
+ lines.push("- " + renderOwnership({task:c.task,dryRun:r.dryRun}, "已更新") + (parts.length ? ":" + parts.join(",") : "(无变化)"));
231
+ }
232
+ if (r.missing && r.missing.length) lines.push("跳过不存在的 id:" + r.missing.join(", "));
233
+ return lines.join("\n");
234
+ }
235
+
236
+ export function renderBulkCreate(r) {
237
+ const lines = [r.dryRun ? "预览:将创建 " + r.wouldCreate + " 条任务(未写库)" : "已创建 " + r.created + " 条任务"];
238
+ for (const result of r.results || r.tasks.map(task=>({task}))) lines.push("- " + renderOwnership({...result,dryRun:r.dryRun}));
239
+ return lines.join("\n");
240
+ }
241
+
242
+ export function renderBulkDelete(r) {
243
+ const lines = [r.dryRun ? "预览:将删除 " + r.wouldDelete + " 条任务(未写库)" : "已删除 " + r.deleted + " 条任务"];
244
+ for (const it of r.items) lines.push("- " + it.title + "(id=" + it.id + ")");
245
+ if (r.missing && r.missing.length) lines.push("跳过不存在的 id:" + r.missing.join(", "));
246
+ return lines.join("\n");
247
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * 接取(claim)/ 批量接取(claimBatch)/ 抢夺(grab)。
3
+ *
4
+ * 并发语义是 CAS 抢占:一律用带 `status=` 条件的 UPDATE,读 `run().changes`
5
+ * 判断是否抢到,不做「先 SELECT 判断、再 UPDATE」的两步写法。SELECT 只用于
6
+ * 返回回执与失败原因,不参与抢锁决策。
7
+ */
8
+ import { randomUUID } from "node:crypto";
9
+ import { now, idOf, logChange } from "../../db/db.js";
10
+ import { ownershipError } from "../model/task-ownership-path.js";
11
+ import { getTask, outOne, emitChange } from "../model/task-model.js";
12
+
13
+ import { taskTransaction } from "./task-transaction.js";
14
+
15
+ const OWNER_MAX = 120;
16
+ const STATUS_CLAIMED = "4";
17
+ const STATUS_OPEN = "0";
18
+ const CLAIMABLE = ["0"];
19
+ const GRABBABLE = ["0", "4"];
20
+
21
+ function claimError(code, message, extra) {
22
+ const error = new Error(message);
23
+ error.code = code;
24
+ if (extra) Object.assign(error, extra);
25
+ return error;
26
+ }
27
+
28
+ function normalizeOwner(value) {
29
+ if (value === undefined || value === null || value === "") return "local";
30
+ if (typeof value !== "string") throw claimError("INVALID_OWNER", "owner 必须是字符串");
31
+ const owner = value.trim();
32
+ if (!owner) return "local";
33
+ if (owner.length > OWNER_MAX) throw claimError("INVALID_OWNER", "owner 最多 " + OWNER_MAX + " 个字符");
34
+ return owner;
35
+ }
36
+
37
+ function loadRow(db, id) {
38
+ return db.prepare("SELECT * FROM task WHERE id=?").get(id) || null;
39
+ }
40
+
41
+ function notFoundMessage(id) {
42
+ return "任务不存在:" + id;
43
+ }
44
+
45
+ function notClaimableError(id, row) {
46
+ const status = String(row.status);
47
+ return claimError("TASK_NOT_CLAIMABLE", "任务 " + id + " 当前状态是 " + status + ",只有「已开启」的任务可以接取", {
48
+ status: status,
49
+ nextActions: ["tasks.get({id:\"" + id + "\"}) 查看当前状态", "换一个已开启的任务", "如果是别人已接取,请先与该 owner 协商"],
50
+ });
51
+ }
52
+
53
+ function failReason(row) {
54
+ if (!row) return "not_found";
55
+ if (row.deleted_at) return "deleted";
56
+ if (String(row.status) === STATUS_CLAIMED) return "already_claimed";
57
+ return "not_claimable";
58
+ }
59
+
60
+ /** 单条 CAS:WHERE status='0' AND deleted_at IS NULL,changes===1 才算抢到。 */
61
+ export function claimTask(db, args, origin, api) {
62
+ const id = idOf(args.id || args.taskId);
63
+ if (!id) throw claimError("INVALID_ID", "任务 id 不能为空");
64
+ const owner = normalizeOwner(args.owner);
65
+ const cur = loadRow(db, id);
66
+ if (!cur || cur.deleted_at) throw claimError("TASK_NOT_FOUND", notFoundMessage(id), { id: id });
67
+ const ts = now();
68
+ const token = randomUUID();
69
+ const result = db.prepare(
70
+ "UPDATE task SET status=?,owner=?,claimed_at=?,claim_token=?,updated_at=?,rev=rev+1 " +
71
+ "WHERE id=? AND status=? AND deleted_at IS NULL",
72
+ ).run(STATUS_CLAIMED, owner, ts, token, ts, id, STATUS_OPEN);
73
+ if (result.changes !== 1) {
74
+ const after = loadRow(db, id);
75
+ if (!after || after.deleted_at) throw claimError("TASK_NOT_FOUND", notFoundMessage(id), { id: id });
76
+ throw notClaimableError(id, after);
77
+ }
78
+ const row = Object.assign({}, cur, {
79
+ status: STATUS_CLAIMED, owner: owner, claimed_at: ts, claim_token: token, updated_at: ts, rev: Number(cur.rev) + 1,
80
+ });
81
+ writeClaimChange(db, row, origin, api, ts, "claim");
82
+ return { claimed: true, id: id, task: outOne(db, row), previousStatus: STATUS_OPEN, owner: owner, claimToken: token };
83
+ }
84
+
85
+ function writeClaimChange(db, row, origin, api, ts, kind) {
86
+ logChange(db, "task", row.id, "update", row, origin, ts);
87
+ emitChange(api, row.id, kind || "tasks-changed");
88
+ }
89
+
90
+ function previewBatch(db, ids) {
91
+ const claimed = [], failed = [];
92
+ for (const id of ids) {
93
+ const row = loadRow(db, id);
94
+ if (row && !row.deleted_at && String(row.status) === STATUS_OPEN) claimed.push({ id: id, title: String(row.title || "") });
95
+ else failed.push({ id: id, reason: failReason(row), status: row ? String(row.status) : undefined });
96
+ }
97
+ return { claimed: claimed, failed: failed };
98
+ }
99
+
100
+ export function claimBatch(db, args, origin, api) {
101
+ const raw = Array.isArray(args.ids) ? args.ids : [];
102
+ const ids = [];
103
+ const seen = new Set();
104
+ for (const value of raw) {
105
+ const id = idOf(value);
106
+ if (!id || seen.has(id)) continue;
107
+ seen.add(id);
108
+ ids.push(id);
109
+ }
110
+ if (!ids.length) throw claimError("INVALID_ID", "ids 不能为空");
111
+ const owner = normalizeOwner(args.owner);
112
+ if (args.dryRun === true) {
113
+ const preview = previewBatch(db, ids);
114
+ return {
115
+ dryRun: true,
116
+ requested: ids.length,
117
+ claimed: preview.claimed,
118
+ failed: preview.failed,
119
+ counts: countOf(preview.claimed, preview.failed),
120
+ };
121
+ }
122
+ const claimed = [], failed = [];
123
+ taskTransaction(db, api, function (buffered) {
124
+ const ts = now();
125
+ for (const id of ids) {
126
+ const cur = loadRow(db, id);
127
+ if (!cur || cur.deleted_at) {
128
+ failed.push({ id: id, reason: failReason(cur), status: cur ? String(cur.status) : undefined });
129
+ continue;
130
+ }
131
+ const token = randomUUID();
132
+ const result = db.prepare(
133
+ "UPDATE task SET status=?,owner=?,claimed_at=?,claim_token=?,updated_at=?,rev=rev+1 " +
134
+ "WHERE id=? AND status=? AND deleted_at IS NULL",
135
+ ).run(STATUS_CLAIMED, owner, ts, token, ts, id, STATUS_OPEN);
136
+ if (result.changes !== 1) {
137
+ const after = loadRow(db, id);
138
+ failed.push({ id: id, reason: failReason(after), status: after ? String(after.status) : undefined });
139
+ continue;
140
+ }
141
+ const row = Object.assign({}, cur, {
142
+ status: STATUS_CLAIMED, owner: owner, claimed_at: ts, claim_token: token, updated_at: ts, rev: Number(cur.rev) + 1,
143
+ });
144
+ logChange(db, "task", row.id, "update", row, origin, ts);
145
+ claimed.push({ id: id, task: outOne(db, row), previousStatus: STATUS_OPEN });
146
+ }
147
+ // 整批只发一次变更事件;事件在事务提交后由 taskTransaction 统一发出。
148
+ if (claimed.length) buffered.emit("tasks-changed", { op: "claimBatch", ids: claimed.map(function (x) { return x.id; }), count: claimed.length });
149
+ });
150
+ return { requested: ids.length, claimed: claimed, failed: failed, counts: countOf(claimed, failed) };
151
+ }
152
+
153
+ function countOf(claimed, failed) {
154
+ const counts = { claimed: claimed.length, alreadyClaimed: 0, notClaimable: 0, notFound: 0, deleted: 0, busy: 0 };
155
+ for (const item of failed) {
156
+ if (item.reason === "already_claimed") counts.alreadyClaimed += 1;
157
+ else if (item.reason === "not_found") counts.notFound += 1;
158
+ else if (item.reason === "deleted") counts.deleted += 1;
159
+ else if (item.reason === "busy") counts.busy += 1;
160
+ else counts.notClaimable += 1;
161
+ }
162
+ return counts;
163
+ }
164
+
165
+ /** 抢夺:只允许从「已开启」「已接取」覆盖,返回被覆盖的 owner/token 供审计。 */
166
+ export function grabTask(db, args, origin, api) {
167
+ const id = idOf(args.id || args.taskId);
168
+ if (!id) throw claimError("INVALID_ID", "任务 id 不能为空");
169
+ const owner = normalizeOwner(args.owner);
170
+ const cur = loadRow(db, id);
171
+ if (!cur || cur.deleted_at) throw claimError("TASK_NOT_FOUND", notFoundMessage(id), { id: id });
172
+ if (GRABBABLE.indexOf(String(cur.status)) < 0) {
173
+ throw claimError("TASK_NOT_CLAIMABLE", "任务 " + id + " 当前状态是 " + cur.status + ",无法抢夺", {
174
+ status: String(cur.status),
175
+ nextActions: ["tasks.get({id:\"" + id + "\"}) 查看当前状态", "已关闭/已完成/已重启的任务不能抢夺"],
176
+ });
177
+ }
178
+ const ts = now();
179
+ const token = randomUUID();
180
+ const result = db.prepare(
181
+ "UPDATE task SET status=?,owner=?,claimed_at=?,claim_token=?,updated_at=?,rev=rev+1 " +
182
+ "WHERE id=? AND status IN ('0','4') AND deleted_at IS NULL",
183
+ ).run(STATUS_CLAIMED, owner, ts, token, ts, id);
184
+ if (result.changes !== 1) {
185
+ const after = loadRow(db, id);
186
+ throw claimError("TASK_CLAIM_LOST", "任务 " + id + " 在抢夺过程中被其他会话改写,请重新读取后再试", {
187
+ status: after ? String(after.status) : null,
188
+ retryable: true,
189
+ });
190
+ }
191
+ const row = Object.assign({}, cur, {
192
+ status: STATUS_CLAIMED, owner: owner, claimed_at: ts, claim_token: token, updated_at: ts, rev: Number(cur.rev) + 1,
193
+ });
194
+ writeClaimChange(db, row, origin, api, ts, "grab");
195
+ return {
196
+ grabbed: true,
197
+ id: id,
198
+ task: outOne(db, row),
199
+ previousStatus: String(cur.status),
200
+ previousOwner: cur.owner === undefined || cur.owner === null ? null : String(cur.owner),
201
+ previousClaimToken: cur.claim_token === undefined || cur.claim_token === null ? null : String(cur.claim_token),
202
+ owner: owner,
203
+ claimToken: token,
204
+ reason: args.reason === undefined || args.reason === null ? null : String(args.reason),
205
+ };
206
+ }
207
+
208
+ /** 自动化写路径的 ABA 防护:token 必须与当前接取记录一致。 */
209
+ export function assertClaimToken(db, id, token) {
210
+ const cur = getTask(db, id);
211
+ if (!cur) throw claimError("TASK_NOT_FOUND", notFoundMessage(id), { id: id });
212
+ if (String(cur.status) !== STATUS_CLAIMED || String(cur.claim_token || "") !== String(token || "")) {
213
+ throw claimError("TASK_CLAIM_LOST", "任务的接取凭据已失效(已释放、已转移或已进入终态),请重新 tasks.get 后再写", {
214
+ status: String(cur.status),
215
+ retryable: true,
216
+ });
217
+ }
218
+ }
219
+
220
+ /** 进入终态(关闭/完成/重启)时清空接取字段,保持列不变量。 */
221
+ export function clearClaimFields(row) {
222
+ const next = Object.assign({}, row);
223
+ next.owner = null;
224
+ next.claimed_at = null;
225
+ next.claim_token = null;
226
+ return next;
227
+ }
228
+
229
+ export { claimError, ownershipError };
@@ -0,0 +1,34 @@
1
+ import limits from '../../../shared/tree/limits.cjs';
2
+ const { NAME_MAX, PATH_MAX, PATH_LEN_MAX } = limits;
3
+ import { DIFFICULTY_SCHEMA } from "../model/task-difficulty.js";
4
+ /** 单条与批量创建共用的完整参数契约。 */
5
+ export const TASK_CREATE_SCHEMA = {
6
+ type: "object",
7
+ required: ["title"],
8
+ oneOf: [{required:["tableId"],not:{required:["tablePath"]}},{required:["tablePath"],not:{required:["tableId"]}}],
9
+ properties: {
10
+ title: { type: "string", description: "标题;只 trim + 非空校验,不做重名判重(标题不唯一,用 id 区分)" },
11
+ description: { type: "string" },
12
+ review: { type: "string", description: "完成后的感受/复盘(自由文本,默认空)" },
13
+ tableId: { type: ["string", "number"], description: "目标存活任务表 id;与 tablePath 恰选一个,无默认表" },
14
+ tablePath: { type: ['string','array'], maxLength: PATH_LEN_MAX, maxItems: PATH_MAX, items: {type:'string', maxLength: NAME_MAX}, description: `从逻辑根下一层起的精确名称路径;斜杠分隔字符串或字符串数组(名称含斜杠必须用数组);禁止空段/点段,最多${PATH_MAX}段、每段${NAME_MAX}字符、总长${PATH_LEN_MAX}(JS length)` },
15
+ createMissing: {type:'boolean',description:'仅tablePath可用;true时事务内建缺失组/表,默认false,不自动推断授权'},
16
+ pathDescriptions: {type:'array',items:{type:'string'},description:'仅createMissing=true可用,长度与路径段相同;每个新节点职责描述必须非空且最多2000字符,已有节点不覆盖'},
17
+ status: { type: ["string", "number"], description: "0=已开启/1=已关闭/2=已完成(不能直接创建 RESTARTED);source=2 固定为 0;关闭/完成时优先级自动清零,不必手工传 0" },
18
+ priority: { type: "number", description: "1..10(重启需优先级 >0,source=2 缺省 1,显式 0 报错;普通开启同样缺省 1;关闭/完成自动清零,不必手工传 0)" },
19
+ difficulty: DIFFICULTY_SCHEMA,
20
+ publishDate: { type: "string", description: "YYYY-MM-DD,缺省今天" },
21
+ targetDate: { type: "string", description: "YYYY-MM-DD,缺省同 publishDate" },
22
+ doneDate: { type: "string" },
23
+ shutdownDate: { type: "string" },
24
+ source: { type: ["string", "number"], description: "0 普通 / 1 时间线 / 2 重启(固定开启状态,priority 必须 1–10,缺省 1,不能传 0)" },
25
+ timelineId: { type: ["string", "number"], description: "source=1 必须指定已有有效线;source=0 不可传;source=2 仅可等于原任务有效归属,无归属报 TIMELINE_REQUIRED_FOR_RESTART 且零写" },
26
+ timelineKey: { type: ["string", "number"], description: "deprecated:timelineId 别名,同时传必须相同;source=1 二者至少一个" },
27
+ restartKey: { type: ["string", "number"], description: "source=2 必填:原任务 id" },
28
+ originTaskId: { type: ["string", "number"], description: "restartKey 的别名" },
29
+ workspaceIds: { type: "array", items: { type: "string" }, description: "创建时关联的工作区 id:可多个;任一不存在/已删除则整条创建回滚;空数组或不传表示不关联" },
30
+ tagIds: { type: "array", items: { type: "string" }, description: "创建时挂标签(需要标签域;未安装时忽略并在回执 notices 说明);id 必须已存在,否则报错并列出可用标签" },
31
+ tags: { type: "array", items: { type: "string" }, description: "创建时按标签名挂标签;默认自动创建未知名字,form.autoCreateTags=false 时未知名字报错并列出可用标签;标签域未安装时忽略并回执 notices" },
32
+ dedupeKey: { type: "string", description: "幂等键:同键未删除任务存在时直接返回已有任务(deduped:true)" },
33
+ },
34
+ };