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.
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/cordis.patch.yml +7 -0
- package/lib/client.js +11313 -0
- package/lib/db/db-core.js +432 -0
- package/lib/db/db-legacy.js +473 -0
- package/lib/db/db.js +97 -0
- package/lib/db/ownership-path.js +33 -0
- package/lib/db/timeline-schema.js +7 -0
- package/lib/db/workspace-schema.js +15 -0
- package/lib/index.js +213 -0
- package/lib/infra/backup.js +289 -0
- package/lib/infra/config.js +462 -0
- package/lib/infra/data.js +368 -0
- package/lib/infra/sync.js +189 -0
- package/lib/publisher/brief.js +76 -0
- package/lib/publisher/catalog.js +99 -0
- package/lib/publisher/command.js +81 -0
- package/lib/stats/activity-calendar.js +72 -0
- package/lib/stats/overview.js +99 -0
- package/lib/stats/stats-today.js +26 -0
- package/lib/stats/stats.js +542 -0
- package/lib/stats/timeline-stats.js +174 -0
- package/lib/tagging/tag-options.js +99 -0
- package/lib/tagging/tagging.js +333 -0
- package/lib/task/model/task-difficulty.js +15 -0
- package/lib/task/model/task-model.js +256 -0
- package/lib/task/model/task-ownership-path.js +22 -0
- package/lib/task/model/task-priority.js +33 -0
- package/lib/task/read/task-discovery.js +123 -0
- package/lib/task/read/task-publish-filter.js +31 -0
- package/lib/task/read/task-query.js +351 -0
- package/lib/task/read/task-search-schema.js +34 -0
- package/lib/task/read/task-view.js +146 -0
- package/lib/task/write/task-bulk.js +247 -0
- package/lib/task/write/task-claim.js +229 -0
- package/lib/task/write/task-create-schema.js +34 -0
- package/lib/task/write/task-create.js +178 -0
- package/lib/task/write/task-operations.js +207 -0
- package/lib/task/write/task-target.js +56 -0
- package/lib/task/write/task-transaction.js +18 -0
- package/lib/task/write/task-update.js +104 -0
- package/lib/tasks.js +454 -0
- package/lib/timeline/task-timelines.js +103 -0
- package/lib/timeline/timeline-actions.js +69 -0
- package/lib/timeline/timeline-migration.js +70 -0
- package/lib/timeline/timeline-store.js +57 -0
- package/lib/timeline/timeline-sync.js +46 -0
- package/lib/tree/task-node-write.js +26 -0
- package/lib/tree/tree.js +517 -0
- package/lib/workspace/workspace-actions.js +217 -0
- package/lib/workspace/workspace-store.js +196 -0
- package/package.json +144 -4
- package/shared/tree/limits.cjs +3 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 任务记录业务插件(DSH 原生插件)。
|
|
3
|
+
*
|
|
4
|
+
* 所有业务逻辑都在本地 SQLite 完成;云端只负责备份。
|
|
5
|
+
* 宿主由 dsh-workbench 提供,通过 ctx.workbench.registerDomain 注册。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { registerActivityCalendarAction } from "./stats/activity-calendar.js";
|
|
9
|
+
import { registerTimelineStatsAction } from "./stats/timeline-stats.js";
|
|
10
|
+
import { DIFFICULTY_GUIDANCE } from "./task/model/task-difficulty.js";
|
|
11
|
+
import { bindClock, ensureSchema } from "./db/db.js";
|
|
12
|
+
import { exportTasksData, importTasksData } from "./infra/backup.js";
|
|
13
|
+
import { taskSync } from "./infra/sync.js";
|
|
14
|
+
import { registerTaskActions } from "./tasks.js";
|
|
15
|
+
import { registerTreeActions } from "./tree/tree.js";
|
|
16
|
+
import { registerOverviewAction } from "./stats/overview.js";
|
|
17
|
+
import { registerConfigActions } from "./infra/config.js";
|
|
18
|
+
import { registerDataActions } from "./infra/data.js";
|
|
19
|
+
import { registerPublisherCommand } from "./publisher/command.js";
|
|
20
|
+
import { commandCatalog } from "./publisher/catalog.js";
|
|
21
|
+
|
|
22
|
+
export const inject = ["workbench"];
|
|
23
|
+
|
|
24
|
+
let domainApi = null;
|
|
25
|
+
function requireApi() {
|
|
26
|
+
if (!domainApi) throw new Error("任务模块尚未初始化");
|
|
27
|
+
return domainApi;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 只读「Action」页的数据源完全由插件自己维护:注册时记录 action 定义,
|
|
33
|
+
* 再由本插件注册的 <域>.actionSchema 返回,不经过宿主 schema 接口。
|
|
34
|
+
*/
|
|
35
|
+
function trackActions(api) {
|
|
36
|
+
const defs = new Map();
|
|
37
|
+
const rawAction = typeof api.action === "function" ? api.action.bind(api) : null;
|
|
38
|
+
if (rawAction) {
|
|
39
|
+
api.action = function (name, def) {
|
|
40
|
+
defs.set(name, def || {});
|
|
41
|
+
return rawAction(name, def);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return defs;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 只读命令目录:「命令」页与 agent 都用它发现本插件注册了哪些斜杠命令。
|
|
49
|
+
* 数据来自 publisher/catalog.js 的同一份数组,页面不重复维护文案。
|
|
50
|
+
*/
|
|
51
|
+
function registerCommandsAction(api) {
|
|
52
|
+
api.action("tasks.commands", {
|
|
53
|
+
description: "只读:返回本插件注册的斜杠命令目录(名称、用途、用法、输入提示、字符上限、示例、说明,含只读提示词模板),供「命令」页渲染;不执行命令、不写库、不产生审计",
|
|
54
|
+
input: { type: "object", properties: {}, additionalProperties: false },
|
|
55
|
+
examples: [{}],
|
|
56
|
+
execute: () => {
|
|
57
|
+
const commands = commandCatalog();
|
|
58
|
+
return { count: commands.length, commands: commands };
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function registerActionSchemaAction(api, defs, domain) {
|
|
64
|
+
const prefix = domain.replace(/^wb-addon-/, "");
|
|
65
|
+
api.action(prefix + ".actionSchema", {
|
|
66
|
+
description: "只读:返回本插件运行时注册的 action schema(供「Action」页渲染;不执行任何 action、不写库、不产生审计)",
|
|
67
|
+
input: { type: "object", properties: {}, additionalProperties: false },
|
|
68
|
+
execute: () => ({
|
|
69
|
+
shellVersion: api.shellVersion || "",
|
|
70
|
+
domains: [{ id: domain, version: api.addon && api.addon.version ? api.addon.version : "" }],
|
|
71
|
+
actions: Array.from(defs, ([name, def]) => ({
|
|
72
|
+
name: name,
|
|
73
|
+
domain: domain,
|
|
74
|
+
description: typeof def.description === "string" ? def.description : "",
|
|
75
|
+
input: def.input && typeof def.input === "object" ? def.input : { type: "object", properties: {} },
|
|
76
|
+
examples: Array.isArray(def.examples) ? def.examples : [],
|
|
77
|
+
})),
|
|
78
|
+
}),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 旧 addon 形态的初始化函数,单测/兼容直接调用。 */
|
|
83
|
+
export function setup(api) {
|
|
84
|
+
domainApi = api;
|
|
85
|
+
if (typeof api.now === "function") bindClock(api.now);
|
|
86
|
+
ensureSchema(api.db, api.log);
|
|
87
|
+
const actionDefs = trackActions(api);
|
|
88
|
+
registerTaskActions(api);
|
|
89
|
+
registerActivityCalendarAction(api);
|
|
90
|
+
registerTimelineStatsAction(api);
|
|
91
|
+
registerTreeActions(api);
|
|
92
|
+
registerOverviewAction(api);
|
|
93
|
+
registerConfigActions(api);
|
|
94
|
+
registerDataActions(api);
|
|
95
|
+
registerCommandsAction(api);
|
|
96
|
+
registerActionSchemaAction(api, actionDefs, "wb-addon-tasks");
|
|
97
|
+
api.log("tasks domain ready", api.addon.version);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function apply(ctx) {
|
|
101
|
+
const host = ctx.workbench;
|
|
102
|
+
if (!host) throw new Error("dsh-workbench 未加载:缺少 workbench 服务");
|
|
103
|
+
ctx.effect(
|
|
104
|
+
() =>
|
|
105
|
+
host.registerDomain({
|
|
106
|
+
id: "wb-addon-tasks",
|
|
107
|
+
title: "任务",
|
|
108
|
+
description: "任务树 + 统计/记录/时间线/配置/数据五个视图:紧急/已关闭/已开启/已完成/总览,可按标签筛选(需安装标签插件),附统计报表与只读数据浏览",
|
|
109
|
+
version: "5.2.6",
|
|
110
|
+
tables: ["task", "task_node", "task_timeline", "task_timeline_link", "task_workspace", "task_workspace_link"],
|
|
111
|
+
sync: taskSync,
|
|
112
|
+
views: [
|
|
113
|
+
{ id: "stats", title: { zh: "统计", en: "Stats" } },
|
|
114
|
+
{ id: "tasks", title: { zh: "记录", en: "Records" } },
|
|
115
|
+
{ id: "timeline", title: { zh: "时间线", en: "Timeline" } },
|
|
116
|
+
{ id: "config", title: { zh: "配置", en: "Config" } },
|
|
117
|
+
{ id: "data", title: { zh: "数据", en: "Data" } },
|
|
118
|
+
],
|
|
119
|
+
capability: {
|
|
120
|
+
summary: "记录可执行、可交付的工作项(任务),支持任务树、时间线、重启链与工作区关联。",
|
|
121
|
+
records: [
|
|
122
|
+
{
|
|
123
|
+
kind: "task",
|
|
124
|
+
title: "任务",
|
|
125
|
+
description: "一个有明确结果的工作项;可以归入任务表、时间线或重启链,并挂标签。",
|
|
126
|
+
when: [
|
|
127
|
+
"一个工作项已经完成,或已经有明确下一步,值得进入工作台继续跟进",
|
|
128
|
+
"用户明确说“记一下 / 建个任务 / 加到工作台 / 以后要做”",
|
|
129
|
+
"会话中发现需要后续处理、但当前不立即完成的动作",
|
|
130
|
+
],
|
|
131
|
+
notFor: [
|
|
132
|
+
"纯信息查询或一次性问答,没有可执行结果",
|
|
133
|
+
"没有明确标题或完成标准的模糊想法;先描述清楚再记",
|
|
134
|
+
],
|
|
135
|
+
primaryAction: "tasks.create",
|
|
136
|
+
keyArgs: ["tableId", "tablePath", "createMissing", "pathDescriptions", "title", "description", "priority", "difficulty", "targetDate", "tags", "tagIds", "dedupeKey"],
|
|
137
|
+
dedupe: "同 dedupeKey 的未删除任务会被复用;自动记录建议使用稳定键,如 dsh-session:<id>。",
|
|
138
|
+
relations: [
|
|
139
|
+
{ kind: "taskNode", via: "tableId", description: "先调用 taskNodes.overview 查看全文描述、类型、路径与子树计数,再用 tasks.create 的 tableId 选表;group/root_group 只能装子节点,table 才能直接放任务。创建必须显式tableId或tablePath且互斥;无默认表。优先tasks.capabilities/resolveTable核对职责;新路径授权后用createMissing+pathDescriptions。" },
|
|
140
|
+
{ kind: "tag", via: "tags / tagIds", description: "用标签做主题归类(工作/生活/学习/开发 已是标签);传标签名会自动建。" },
|
|
141
|
+
{ kind: "taskWorkspace", via: "workspaceIds", description: "工作区是本机目录或逻辑分组(可空目录),与任务多对多;先用 taskWorkspaces.list 选,创建时传 workspaceIds。" },
|
|
142
|
+
],
|
|
143
|
+
examples: [
|
|
144
|
+
{
|
|
145
|
+
purpose: "记录一次已完成的工作项",
|
|
146
|
+
args: {
|
|
147
|
+
tableId: "已核对的任务表id",
|
|
148
|
+
title: "整理工作台能力清单",
|
|
149
|
+
description: "梳理各插件 action 与记录边界",
|
|
150
|
+
tags: ["开发"],
|
|
151
|
+
priority: 6,
|
|
152
|
+
difficulty: 3,
|
|
153
|
+
targetDate: "2026-11-08",
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
],
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
fields: [
|
|
160
|
+
{ name: "includeSingletons / timelineKeys", type: "boolean / string[]", description: "tasks.timelines默认20条且只显示多任务线;timelineKeys用于timelineRefactor整线合并,与ids互斥,目标必须在所选keys中;dryRun返回wouldUpdate及total完整计数,无list上限。" },
|
|
161
|
+
{ name: "lastActivityDate", type: "YYYY-MM-DD", description: "时间线有效成员发布/完成/关闭日及创建/修改本地日最大值;不含计划targetDate,排除已重启和已删除成员;openCount仅status0,doneCount仅status2。" },
|
|
162
|
+
{ name: "statuses / urgent", type: "integer[] / boolean", description: "list/非ids export:statuses 为 0/1/2/3/4 整数数组,与 urgent 取 OR,再与其他筛选 AND。紧急为开启且(priority>=6或targetDate<=今天+2)。不传 statuses/urgent 时不过滤状态,返回全部状态(含已重启);空数组且 urgent=false 同样为全部;缺少另一参数时默认 []/false。旧参数 tab、filterRestarted 已移除,传入会报错。" },
|
|
163
|
+
{ name: "publishFrom / publishTo / doneFrom / doneTo / shutdownFrom / shutdownTo / claimedFrom / claimedTo", type: "YYYY-MM-DD", description: "list/非ids export 四组闭区间,两端独立可选,空串不筛,真实日期校验;日期前10位与其他条件AND。完成范围要求状态2,关闭范围要求状态1,接取范围要求状态 IN (2,4) 且按 COALESCE(claimed_at 本地日, 发布日) 比较(历史任务按发布日近似);完成与关闭范围同时非空则交集为空。反序交换后filter回显并返回publish_range_swapped/done_range_swapped/shutdown_range_swapped/claimed_range_swapped notice。" },
|
|
164
|
+
{ name: "year", type: "integer 1900..9999", description: "tasks.activityCalendar 必填年份:独立年度稀疏日历,publish/done/shutdown 三类事件计数及 totals/max(含 total)" },
|
|
165
|
+
{ name: "activityDate / activityType", type: "YYYY-MM-DD / publish|done|shutdown", description: "list/非ids export 活动日筛选;type 缺省 done,有 type 必须有日期。单类事件,与既有条件 AND;与日历同口径,完整日点击请传 statuses=[]" },
|
|
166
|
+
{ name: "status", type: "0|1|2|3", description: "0=已开启 ACTIVE、1=已关闭 SHUTDOWN、2=已完成 DONE、3=已重启 RESTARTED(创建时不允许 3);也接受 open/done。别按“0=未开始”理解:0 是在办" },
|
|
167
|
+
{ name: "priority", type: "1..10(关闭/完成为 0)", description: "数值越大越紧急,不是越小越急;已开启任务必须 P1..P10(显式传 0 会报错,缺省 P1);已关闭/已完成/已重启一律 P0,传值被忽略;>=6 满足紧急谓词;参数优先级 min/max 同样是数值越大越急" },
|
|
168
|
+
{ name: "difficulty", type: "0..5", description: DIFFICULTY_GUIDANCE },
|
|
169
|
+
{ name: "sort", type: "string", description: "priority / target(targetDate)/ publish(publishDate)/ updated / created;前缀 - 表示降序,例如 sort=-priority 才是最紧急在前;不传时未分页按 priority 降序,分页(传 pageNumber/pageSize)按 publishDate 降序" },
|
|
170
|
+
{ name: "order", type: "asc|desc", description: "显式指定排序方向,覆盖 sort 前缀" },
|
|
171
|
+
{ name: "targetDate", type: "YYYY-MM-DD", description: "目标日期(截止);缺省表示未定;targetFrom/targetTo 按它过滤,target<今天且未完成即视为逾期" },
|
|
172
|
+
{ name: "publishDate", type: "YYYY-MM-DD", description: "发布日期,缺省为创建当天" },
|
|
173
|
+
{ name: "doneDate", type: "YYYY-MM-DD|null", description: "完成日期,改成已完成时自动补今天" },
|
|
174
|
+
{ name: "shutdownDate", type: "YYYY-MM-DD|null", description: "关闭日期,改成已关闭时自动补今天" },
|
|
175
|
+
{ name: "titleKey", type: "string", description: "关键词,字面包含匹配标题、描述、感受(OR);%/_/反斜杠按普通字符,ASCII 大小写不敏感;list 与非 ids 导出共用" },
|
|
176
|
+
{ name: "tableKey", type: "string", description: "任务表关键词,同时匹配表名与表描述" },
|
|
177
|
+
{ name: "tableId / groupId", type: "string|number", description: "按任务表 / 任务组过滤;groupId 含义是该组下所有任务表" },
|
|
178
|
+
{ name: "tags / tagIds", type: "string[]", description: "写入时是整体替换(会覆盖原有标签,批量套用最危险);读取时是“命中任一”过滤。tags 传标签名,不存在会自动建" },
|
|
179
|
+
{ name: "addTags / removeTags / addTagIds / removeTagIds", type: "string[]", description: "增量加/减标签,保留其余标签;不能与 tags/tagIds 同时传" },
|
|
180
|
+
{ name: "pageNumber / pageSize", type: "number", description: "页码从 1 开始,每页默认 12、上限 200(超出按 200 截断,filter.pageSizeCapped=true);传 pageNumber 或 pageSize 即分页。返回 total=真实总数、returned=本页条数、truncated=是否还有未返回的;未分页最多 500 条,超出时 truncated=true" },
|
|
181
|
+
{ name: "title", type: "string", description: "任务标题,仅 trim + 非空校验;标题不唯一,允许与其它任务重名,用 id 区分(标签名唯一、任务节点名同级唯一,别混)" },
|
|
182
|
+
{ name: "type", type: "0|1|2|3|4", description: "仅 tasks.update 使用:0=改状态 1=改优先级 2=改标题 3=改描述 4=改感受;这是“更新模式”,不是任务类型(任务没有类型字段,用标签表达)" },
|
|
183
|
+
{ name: "review", type: "string", description: "完成后的感受/复盘自由文本,通常随完成一起写入" },
|
|
184
|
+
{ name: "range / from / to", type: "7d|30d|90d|365d|all / YYYY-MM-DD", description: "仅统计类 action:range 是快捷区间(缺省 30d),from+to 手动区间是闭区间 [from,to],两端都含;同时传时以 from/to 为准" },
|
|
185
|
+
{ name: "dedupeKey", type: "string", description: "去重键:同键的未删除任务会被复用而不是新建,自动记录建议用 dsh-session:<id>" },
|
|
186
|
+
{ name: "source / timelineId / timelineKey / restartKey", type: "0|1|2 / string", description: "来源:0=无时间线普通任务;1=加入手动创建的有效时间线,需要timelineId(timelineKey为deprecated兼容别名);2=重启,需restartKey且原任务已有有效归属,自动继承同一线;无归属先手动建线并关联,失败零写。重启固定开启、优先级1–10缺省1。" },
|
|
187
|
+
],
|
|
188
|
+
notFor: ["不要用它保存聊天记录、日志或临时笔记"],
|
|
189
|
+
notes: [
|
|
190
|
+
"已有开发/修复/设计任务核对完整路径和职责后选择;确认新子模块形态、无合适表且获授权才建路径,不每条新建。一次性问答不建任务;物品登记走storage.create,开发storage功能才走tasks。多候选询问用户,绝不按热度/首项自动选择。",
|
|
191
|
+
"先 taskNodes.overview 再 tasks.create,不要凭感觉选表;overview 默认描述全文,maxDescriptionLength 可选,count 为未删除任务的子树总数(所有状态)。",
|
|
192
|
+
"date 字段均为 YYYY-MM-DD;source=1 需有效 timelineId(兼容 timelineKey);source=2 需 restartKey 且原任务已有有效时间线。",
|
|
193
|
+
"状态机:0 已开启 → 1 已关闭(补 shutdownDate)/ 2 已完成(补 doneDate);1 或 2 可回到 0 继续办理(优先级自动回落到 1)。3 已重启不在创建时使用:重启老任务时先把它置 3,再建 source=2 的新任务。",
|
|
194
|
+
"restart_key = 重启链的链首任务 id:普通任务等于自身 id,source=2 的新任务继承原任务;同一 restart_key 的任务按 publishDate 组成一条重启链,用 tasks.restart 读取。",
|
|
195
|
+
"时间线必须用taskTimelines.create手动创建;普通任务timelineId为null,source=1/attach仅关联现有实体。timelineKey是timelineId的deprecated兼容别名,不再以自身id占位。重启强制继承同一有效线,无关联先提示建立并关联。历史key仅保留待审阅,不自动回填;tasks.timeline读取关联成员,timelineRefactor移动已有关系。",
|
|
196
|
+
"优先级不变量:已开启任务 P1..P10(创建默认 1,显式 0 报错);重启需优先级 >0(source=2 缺省 1,显式 0 报错);UI 重启继承原任务有效优先级,原值为 0 则回落配置默认并限制到 1–10;改成已完成/已关闭自动清零,不必手工传 0;关闭/完成/已重启一律 P0,写入 0..10 都会被忽略。旧库启动时自动回填(关闭态清零、开启态 0→1),幂等。",
|
|
197
|
+
"标签域是可选能力:未安装时不阻断任务读写,写入忽略 tags/tagIds/addTags/removeTags 并在回执带 notices(code=tag_domain_missing);读侧省略 tags 字段、按标签筛选返回空结果、tasks.tags available=false。",
|
|
198
|
+
"任务标题不唯一:允许同名,用 id 区分;与「标签名唯一」「任务节点名同级唯一」是不同规则。",
|
|
199
|
+
"任务没有「类型」字段:工作/生活/学习/开发 已迁成同名标签,用 tags 或 tagIds 归类。",
|
|
200
|
+
"标签写入规则:tags/addTags 传名字,默认自动创建未知名字(配置 form.autoCreateTags 关掉后改为报错并列出可用标签);tagIds/addTagIds 传 id,必须已存在,否则报错并列出可用标签;create/update/bulkCreate/bulkUpdate 共用同一套校验。",
|
|
201
|
+
"标签下拉用 tasks.tagOptions(text 模糊匹配、pageNumber/pageSize 分页,返回 total/hasMore)按需取数;tasks.tags 会一次返回全部标签及计数,只适合导航/统计这类需要全量的场景。",
|
|
202
|
+
],
|
|
203
|
+
},
|
|
204
|
+
setup,
|
|
205
|
+
exportData: () => exportTasksData(requireApi()),
|
|
206
|
+
importData: (raw, _ctx, options) => importTasksData(requireApi(), raw, options),
|
|
207
|
+
}),
|
|
208
|
+
"tasks-domain",
|
|
209
|
+
);
|
|
210
|
+
// 斜杠命令:缺少 commands 服务时 registerPublisherCommand 内部静默跳过,
|
|
211
|
+
// 不影响插件加载(ACP/无 UI 环境没有该服务)。
|
|
212
|
+
ctx.effect(() => registerPublisherCommand(ctx), "tasks-publisher-command");
|
|
213
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 任务模块的备份导出/导入。
|
|
3
|
+
*
|
|
4
|
+
* 模块自己的数据格式由模块决定;宿主只做 zip、manifest 与路由。
|
|
5
|
+
* 导入采用按 updated_at 的 LWW 合并:本地更新或同时间戳的行跳过。
|
|
6
|
+
* 所有行(含软删)都会导出,保证删除标记也能随备份恢复。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { logChange, tableExists, tx } from "../db/db.js";
|
|
10
|
+
import { LEGACY_TYPE_TAGS, addTaskTagByName, tagsAvailable } from "../tagging/tagging.js";
|
|
11
|
+
|
|
12
|
+
const SCHEMA_VERSION = 5;
|
|
13
|
+
|
|
14
|
+
function asText(value, fallback) {
|
|
15
|
+
if (value === undefined || value === null) return fallback === undefined ? "" : fallback;
|
|
16
|
+
return String(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function asInt(value, fallback) {
|
|
20
|
+
const n = Number(value);
|
|
21
|
+
return Number.isFinite(n) ? Math.trunc(n) : fallback;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function asNumOrNull(value) {
|
|
25
|
+
if (value === undefined || value === null || value === "") return null;
|
|
26
|
+
const n = Number(value);
|
|
27
|
+
return Number.isFinite(n) ? n : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function asTextOrNull(value) {
|
|
31
|
+
if (value === undefined || value === null) return null;
|
|
32
|
+
const s = String(value);
|
|
33
|
+
return s === "" ? null : s;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function taskValues(row) {
|
|
37
|
+
const id = asText(row && row.id).trim();
|
|
38
|
+
if (!id) throw new Error("task.id 为空");
|
|
39
|
+
const title = asText(row.title);
|
|
40
|
+
if (!title) throw new Error("task.title 为空:" + id);
|
|
41
|
+
const updated = asInt(row.updated_at, Date.now());
|
|
42
|
+
return [
|
|
43
|
+
id,
|
|
44
|
+
title,
|
|
45
|
+
asText(row.description),
|
|
46
|
+
asText(row.status, "0"),
|
|
47
|
+
asInt(row.priority, 0),
|
|
48
|
+
asNumOrNull(row.difficulty),
|
|
49
|
+
asText(row.review),
|
|
50
|
+
asText(row.table_id),
|
|
51
|
+
row.timeline_key === undefined || row.timeline_key === null ? null : String(row.timeline_key),
|
|
52
|
+
asTextOrNull(row.restart_key),
|
|
53
|
+
asText(row.publish_date),
|
|
54
|
+
asText(row.target_date),
|
|
55
|
+
asTextOrNull(row.done_date),
|
|
56
|
+
asTextOrNull(row.shutdown_date),
|
|
57
|
+
asTextOrNull(row.dedupe_key),
|
|
58
|
+
asTextOrNull(row.owner),
|
|
59
|
+
row.claimed_at === undefined || row.claimed_at === null ? null : asInt(row.claimed_at, 0),
|
|
60
|
+
asTextOrNull(row.claim_token),
|
|
61
|
+
asInt(row.created_at, updated),
|
|
62
|
+
updated,
|
|
63
|
+
row.deleted_at === null || row.deleted_at === undefined ? null : asInt(row.deleted_at, updated),
|
|
64
|
+
Math.max(1, asInt(row.rev, 1)),
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function nodeValues(row) {
|
|
69
|
+
const id = asText(row && row.id).trim();
|
|
70
|
+
if (!id) throw new Error("task_node.id 为空");
|
|
71
|
+
const updated = asInt(row.updated_at, Date.now());
|
|
72
|
+
return [
|
|
73
|
+
id,
|
|
74
|
+
asText(row.name, "未命名"),
|
|
75
|
+
asText(row.description),
|
|
76
|
+
asText(row.type, "0"),
|
|
77
|
+
asText(row.parent_id, "0"),
|
|
78
|
+
asText(row.path),
|
|
79
|
+
asInt(row.sort, 0),
|
|
80
|
+
asInt(row.depth, 0),
|
|
81
|
+
asInt(row.created_at, updated),
|
|
82
|
+
updated,
|
|
83
|
+
row.deleted_at === null || row.deleted_at === undefined ? null : asInt(row.deleted_at, updated),
|
|
84
|
+
Math.max(1, asInt(row.rev, 1)),
|
|
85
|
+
];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function workspaceValues(row) {
|
|
89
|
+
return [identity(row.id, "task_workspace.id"), asText(row.title), asText(row.name), asText(row.description),
|
|
90
|
+
asTextOrNull(row.dir), ...stamps(row)];
|
|
91
|
+
}
|
|
92
|
+
function workspaceLinkValues(row) {
|
|
93
|
+
const workspaceId = identity(row.workspace_id, "task_workspace_link.workspace_id");
|
|
94
|
+
const taskId = identity(row.task_id, "task_workspace_link.task_id");
|
|
95
|
+
const expected = workspaceId + ":" + taskId;
|
|
96
|
+
if (identity(row.id, "task_workspace_link.id") !== expected) throw new Error("WORKSPACE_LINK_ID_MISMATCH: link.id 必须等于 workspace_id + ':' + task_id");
|
|
97
|
+
return [expected, workspaceId, taskId, ...stamps(row)];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const DEFINITIONS = [
|
|
101
|
+
["task_node", "taskNodes", "id,name,description,type,parent_id,path,sort,depth,created_at,updated_at,deleted_at,rev", nodeValues],
|
|
102
|
+
["task_timeline", "taskTimelines", "id,title,description,created_at,updated_at,deleted_at,rev", timelineValues],
|
|
103
|
+
["task", "tasks", "id,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,created_at,updated_at,deleted_at,rev", taskValues],
|
|
104
|
+
["task_timeline_link", "taskTimelineLinks", "id,task_id,timeline_id,created_at,updated_at,deleted_at,rev", linkValues],
|
|
105
|
+
["task_workspace", "taskWorkspaces", "id,title,name,description,dir,created_at,updated_at,deleted_at,rev", workspaceValues],
|
|
106
|
+
["task_workspace_link", "taskWorkspaceLinks", "id,workspace_id,task_id,created_at,updated_at,deleted_at,rev", workspaceLinkValues],
|
|
107
|
+
];
|
|
108
|
+
|
|
109
|
+
function identity(value, field) {
|
|
110
|
+
if (typeof value !== "string" || !value.length) throw new Error(field + " 必须为非空字符串");
|
|
111
|
+
return value; // 不 trim、不数值化:001 和 1 是不同实体。
|
|
112
|
+
}
|
|
113
|
+
function stamps(row) {
|
|
114
|
+
for (const key of ["created_at", "updated_at", "rev"]) {
|
|
115
|
+
if (!Number.isSafeInteger(row[key]) || (key === "rev" && row[key] < 1)) throw new Error("非法时间线字段:" + key);
|
|
116
|
+
}
|
|
117
|
+
if (row.deleted_at != null && !Number.isSafeInteger(row.deleted_at)) throw new Error("非法 deleted_at");
|
|
118
|
+
return [row.created_at, row.updated_at, row.deleted_at ?? null, row.rev];
|
|
119
|
+
}
|
|
120
|
+
function timelineValues(row) {
|
|
121
|
+
return [identity(row.id, "task_timeline.id"), asText(row.title), asText(row.description), ...stamps(row)];
|
|
122
|
+
}
|
|
123
|
+
function linkValues(row) {
|
|
124
|
+
const taskId = identity(row.task_id, "task_timeline_link.task_id");
|
|
125
|
+
if (identity(row.id, "task_timeline_link.id") !== taskId) throw new Error("TIMELINE_LINK_ID_MISMATCH: link.id 必须等于 task_id");
|
|
126
|
+
return [taskId, taskId, identity(row.timeline_id, "task_timeline_link.timeline_id"), ...stamps(row)];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function exportTasksData(api) {
|
|
130
|
+
return tx(api.db, () => {
|
|
131
|
+
const timelineMigrationRecords = tableExists(api.db, "meta") ? api.db.prepare("SELECT k,v FROM meta WHERE k LIKE ? ORDER BY k").all("task_timeline_migration:%") : [];
|
|
132
|
+
const data = { schemaVersion: SCHEMA_VERSION, timelineMigrationVersion: 1, timelineMigrationRecords };
|
|
133
|
+
for (const [table, key] of DEFINITIONS) {
|
|
134
|
+
data[key] = tableExists(api.db, table) ? api.db.prepare("SELECT * FROM " + table + " ORDER BY id ASC").all() : [];
|
|
135
|
+
}
|
|
136
|
+
return data;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function prepareBackup(data) {
|
|
141
|
+
if (!data || ![1, 2, 3, 4, 5].includes(Number(data.schemaVersion))) throw new Error("任务备份版本不兼容:需要 1、2、3、4 或 5");
|
|
142
|
+
const droppedDeps = !Array.isArray(data.taskDeps) ? 0 : data.taskDeps.length;
|
|
143
|
+
const legacy = Number(data.schemaVersion) === 1;
|
|
144
|
+
const prepared = [];
|
|
145
|
+
for (const [table, key, columnText, convert] of DEFINITIONS) {
|
|
146
|
+
if (legacy && (table === "task_timeline" || table === "task_timeline_link")) continue;
|
|
147
|
+
// 5 之前的备份没有工作区两张表,缺键按空数组处理,不阻断恢复。
|
|
148
|
+
const rows = key === "taskDeps" ? [] : (data[key] === undefined && table === "task_workspace" || data[key] === undefined && table === "task_workspace_link" ? [] : data[key]);
|
|
149
|
+
if (!Array.isArray(rows)) throw new Error("任务备份结构不完整:" + key);
|
|
150
|
+
const columns = columnText.split(",");
|
|
151
|
+
const ids = new Set();
|
|
152
|
+
const values = rows.map(row => {
|
|
153
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) throw new Error("非法备份行:" + table);
|
|
154
|
+
const v = convert(row);
|
|
155
|
+
if (ids.has(v[0])) throw new Error("备份行 ID 重复:" + table + "/" + v[0]);
|
|
156
|
+
ids.add(v[0]);
|
|
157
|
+
return { row: Object.fromEntries(columns.map((col, i) => [col, v[i]])), original: row };
|
|
158
|
+
});
|
|
159
|
+
prepared.push({ table, columns, values });
|
|
160
|
+
}
|
|
161
|
+
const migrationRecords = legacy ? [] : (data.timelineMigrationRecords ?? []);
|
|
162
|
+
if (!Array.isArray(migrationRecords) || migrationRecords.some(r => !r || typeof r.k !== "string" || !r.k.startsWith("task_timeline_migration:") || typeof r.v !== "string")) throw new Error("非法时间线迁移记录");
|
|
163
|
+
return { legacy, prepared, migrationRecords, droppedDeps };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function legacyCandidates(tasks) {
|
|
167
|
+
const groups = new Map();
|
|
168
|
+
for (const task of tasks) {
|
|
169
|
+
const key = task.timeline_key;
|
|
170
|
+
if (key === null || key === undefined || key === "") continue;
|
|
171
|
+
const list = groups.get(String(key)) || [];
|
|
172
|
+
list.push(String(task.id)); groups.set(String(key), list);
|
|
173
|
+
}
|
|
174
|
+
return [...groups].map(([timelineKey, taskIds]) => ({ timelineKey, taskIds,
|
|
175
|
+
reason: taskIds.length === 1 && taskIds[0] === timelineKey ? "ambiguousSelfId" : "legacyGrouped",
|
|
176
|
+
requiresApproval: true }));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 校验合并后的引用,而非只看输入包;newest/skip 可能保留本地墓碑。
|
|
180
|
+
function validateLinks(db, ids) {
|
|
181
|
+
for (const id of ids) {
|
|
182
|
+
const link = db.prepare("SELECT * FROM task_timeline_link WHERE id=?").get(id);
|
|
183
|
+
if (!link) continue;
|
|
184
|
+
const task = db.prepare("SELECT * FROM task WHERE id=?").get(link.task_id);
|
|
185
|
+
const timeline = db.prepare("SELECT * FROM task_timeline WHERE id=?").get(link.timeline_id);
|
|
186
|
+
if (!task || !timeline) throw new Error("TIMELINE_REFERENCE_NOT_FOUND: " + id + " -> " + link.timeline_id);
|
|
187
|
+
// 墓碑父行保留完整同步状态;活性由 task/link/entity 三方 join 决定,导入不复活。
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function importTasksData(api, raw, options) {
|
|
192
|
+
const db = api.db;
|
|
193
|
+
const policy = ["skip", "overwrite"].includes(options?.policy) ? options.policy : "newest";
|
|
194
|
+
let data, plan;
|
|
195
|
+
try { data = JSON.parse(String(raw || "{}")); plan = prepareBackup(data); }
|
|
196
|
+
catch (error) { return { ok: false, imported: 0, skipped: 0, failed: 1, message: error.message, errors: [error.message] }; }
|
|
197
|
+
const counts = {};
|
|
198
|
+
const importedTaskIds = new Set();
|
|
199
|
+
let imported = 0, skipped = 0;
|
|
200
|
+
try {
|
|
201
|
+
tx(db, () => {
|
|
202
|
+
const changed = [];
|
|
203
|
+
const affectedTasks = new Set();
|
|
204
|
+
const affectedTimelines = new Set();
|
|
205
|
+
for (const { table, columns, values } of plan.prepared) {
|
|
206
|
+
counts[table] = { imported: 0, skipped: 0 };
|
|
207
|
+
const select = db.prepare("SELECT * FROM " + table + " WHERE id=?");
|
|
208
|
+
const upsert = db.prepare("INSERT INTO " + table + " (" + columns.join(",") + ") VALUES(" + columns.map(() => "?").join(",") + ") ON CONFLICT(id) DO UPDATE SET " + columns.slice(1).map(c => c + "=excluded." + c).join(","));
|
|
209
|
+
for (const { row, original } of values) {
|
|
210
|
+
const local = select.get(row.id);
|
|
211
|
+
if (local && (policy === "skip" || (policy === "newest" && local.updated_at >= row.updated_at) || columns.every(c => local[c] === row[c]))) {
|
|
212
|
+
counts[table].skipped++; skipped++; continue;
|
|
213
|
+
}
|
|
214
|
+
upsert.run(...columns.map(c => row[c]));
|
|
215
|
+
if (table === "task" || table === "task_timeline_link") affectedTasks.add(table === "task" ? row.id : row.task_id);
|
|
216
|
+
if (table === "task_timeline") affectedTimelines.add(row.id);
|
|
217
|
+
counts[table].imported++; imported++;
|
|
218
|
+
if (table === "task") importedTaskIds.add(row.id);
|
|
219
|
+
changed.push({ table, row, original, local, columns });
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for (const id of affectedTimelines) {
|
|
223
|
+
for (const link of db.prepare("SELECT task_id FROM task_timeline_link WHERE timeline_id=?").all(id)) affectedTasks.add(link.task_id);
|
|
224
|
+
}
|
|
225
|
+
validateLinks(db, affectedTasks);
|
|
226
|
+
// v1 不把 key 翻译为关系;已有新版归属不被旧备份覆盖。v2 同样以最终 link 为准。
|
|
227
|
+
for (const id of affectedTasks) {
|
|
228
|
+
const link = db.prepare("SELECT * FROM task_timeline_link WHERE task_id=?").get(id);
|
|
229
|
+
if (!link) continue;
|
|
230
|
+
const timeline = db.prepare("SELECT * FROM task_timeline WHERE id=?").get(link.timeline_id);
|
|
231
|
+
const task = db.prepare("SELECT * FROM task WHERE id=?").get(id);
|
|
232
|
+
const key = link.deleted_at == null && timeline && timeline.deleted_at == null && task && task.deleted_at == null ? link.timeline_id : null;
|
|
233
|
+
if (!task || task.timeline_key === key) continue;
|
|
234
|
+
const taskChange = changed.find(record => record.table === "task" && record.row.id === id);
|
|
235
|
+
const local = taskChange?.local;
|
|
236
|
+
const projected = { ...task, timeline_key: key };
|
|
237
|
+
// overwrite 同一旧包可能临时写回旧 key;最终业务内容相同时恢复本地版本,避免反复 bump。
|
|
238
|
+
const unchanged = local && Object.keys(projected).filter(c => c !== "updated_at" && c !== "rev").every(c => projected[c] === local[c]);
|
|
239
|
+
const updated = unchanged ? local.updated_at : Math.max(task.updated_at, local?.updated_at ?? 0, link.updated_at, timeline?.updated_at ?? 0) + 1;
|
|
240
|
+
const rev = unchanged ? local.rev : Math.max(task.rev, local?.rev ?? 0) + 1;
|
|
241
|
+
db.prepare("UPDATE task SET timeline_key=?,updated_at=?,rev=? WHERE id=?").run(key, updated, rev, id);
|
|
242
|
+
if (!taskChange) {
|
|
243
|
+
const stored = { ...projected, updated_at: updated, rev };
|
|
244
|
+
logChange(db, "task", id, stored.deleted_at == null ? "upsert" : "delete", stored, "import", updated);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
for (const record of plan.migrationRecords) {
|
|
248
|
+
const existing = db.prepare("SELECT v FROM meta WHERE k=?").get(record.k);
|
|
249
|
+
if (existing && existing.v !== record.v) throw new Error("TIMELINE_MIGRATION_RECORD_CONFLICT: " + record.k);
|
|
250
|
+
if (!existing) db.prepare("INSERT INTO meta(k,v) VALUES(?,?)").run(record.k, record.v);
|
|
251
|
+
}
|
|
252
|
+
for (const { table, row, original, local, columns } of changed) {
|
|
253
|
+
const stored = db.prepare("SELECT * FROM " + table + " WHERE id=?").get(row.id);
|
|
254
|
+
if (local && columns.every(c => local[c] === stored[c])) {
|
|
255
|
+
counts[table].imported--; counts[table].skipped++; imported--; skipped++; continue;
|
|
256
|
+
}
|
|
257
|
+
logChange(db, table, row.id, stored.deleted_at == null ? "upsert" : "delete", stored, "import", stored.updated_at);
|
|
258
|
+
if (table === "task") {
|
|
259
|
+
const legacyName = LEGACY_TYPE_TAGS[String(original.type)];
|
|
260
|
+
if (legacyName && tagsAvailable(db, api)) addTaskTagByName(db, row.id, legacyName, row.updated_at, "import");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
} catch (error) {
|
|
265
|
+
return { ok: false, imported: 0, skipped: 0, failed: 1, rolledBack: true, message: error.message, errors: [error.message] };
|
|
266
|
+
}
|
|
267
|
+
if (imported > 0) {
|
|
268
|
+
api.emit?.("tasks-changed", { source: "import" });
|
|
269
|
+
api.emit?.("task-nodes-changed", { source: "import" });
|
|
270
|
+
api.emit?.("task-timelines-changed", { source: "import" });
|
|
271
|
+
}
|
|
272
|
+
// 接取列不变量:旧备份没有 owner/claim_token,status=4 的行恢复后需要人工补齐。
|
|
273
|
+
const claimBroken = [];
|
|
274
|
+
for (const id of importedTaskIds) {
|
|
275
|
+
const row = db.prepare("SELECT id,status,owner,claim_token FROM task WHERE id=?").get(id);
|
|
276
|
+
if (!row || String(row.status) !== "4") continue;
|
|
277
|
+
if (!row.owner || !row.claim_token) claimBroken.push(String(row.id));
|
|
278
|
+
}
|
|
279
|
+
return { ok: true, imported, skipped, failed: 0, tables: counts,
|
|
280
|
+
claimWarnings: claimBroken.length ? [{
|
|
281
|
+
code: "CLAIM_FIELDS_MISSING",
|
|
282
|
+
message: "恢复的 " + claimBroken.length + " 条任务状态为「已接取」但缺少 owner/claim_token(旧备份无此列):请用 tasks.get 核对后重新接取或关闭",
|
|
283
|
+
ids: claimBroken,
|
|
284
|
+
}] : [],
|
|
285
|
+
timelineCandidates: plan.legacy ? legacyCandidates(data.tasks) : [],
|
|
286
|
+
message: plan.droppedDeps
|
|
287
|
+
? "5.0.0 起任务依赖已移除,备份中的 " + plan.droppedDeps + " 条 taskDeps 已忽略" + (plan.legacy ? ";历史时间线候选需用户批准,未自动实体化" : "")
|
|
288
|
+
: plan.legacy ? "旧字段已保留;历史时间线候选需用户批准,未自动实体化" : "任务备份已原子恢复" };
|
|
289
|
+
}
|