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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export function clampPriority(value, fallback) {
|
|
2
|
+
if (value === undefined || value === null || value === "") return fallback;
|
|
3
|
+
const n = Number(value);
|
|
4
|
+
if (!Number.isFinite(n)) throw new Error("priority 必须是数字");
|
|
5
|
+
const v = Math.round(n);
|
|
6
|
+
if (v < 0 || v > 10) throw new Error("priority 必须在 0..10");
|
|
7
|
+
return v;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 优先级状态机(唯一入口):
|
|
12
|
+
* - 已开启(status=0):P1..P10,显式传 0 是错误(0 只表示「没有优先级」);
|
|
13
|
+
* - 已关闭/已完成/已重启:一律 P0,写入什么都被忽略;
|
|
14
|
+
* - 已接取(4):仍持有 P1..P10,与已开启同规;
|
|
15
|
+
* - 开启但历史值为 0(旧数据)且本次没有显式传值:回落到 P1。
|
|
16
|
+
*/
|
|
17
|
+
export function priorityForStatus(status, requested, fallback) {
|
|
18
|
+
// 已接取(4)仍持有优先级,按「开启类」处理。
|
|
19
|
+
if (status !== "0" && status !== "4") return 0;
|
|
20
|
+
if (requested !== undefined && requested !== null && requested !== "" && Number(requested) === 0) {
|
|
21
|
+
throw new Error("已开启任务的优先级必须在 1..10(0 仅用于已完成/已关闭)");
|
|
22
|
+
}
|
|
23
|
+
const p = clampPriority(requested, fallback);
|
|
24
|
+
return p > 0 ? p : 1;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 重启创建的默认值固定 P1;调用方可显式传入原任务有效优先级。 */
|
|
28
|
+
export function priorityForCreate(status, requested, source) {
|
|
29
|
+
if (source === "2" && requested !== undefined && requested !== null && requested !== "" && Number(requested) === 0) {
|
|
30
|
+
throw new Error("重启任务的优先级必须是 1–10;已完成/已关闭任务才用 0");
|
|
31
|
+
}
|
|
32
|
+
return priorityForStatus(status, requested, 1);
|
|
33
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { DIFFICULTY_GUIDANCE } from "../model/task-difficulty.js";
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { nodeMap } from '../../db/db.js';
|
|
4
|
+
import { tagsAvailable } from '../../tagging/tagging.js';
|
|
5
|
+
import { ownershipError, pathFromMap } from '../model/task-ownership-path.js';
|
|
6
|
+
|
|
7
|
+
export const GUIDANCE = [
|
|
8
|
+
DIFFICULTY_GUIDANCE,
|
|
9
|
+
'已有具体开发、修复、设计任务:先核对职责、完整路径与描述,显式 domain→tableId 映射优先,选择后带 tableId 创建。',
|
|
10
|
+
'已确认的新子模块:先核对组/表形态,无合适表且获授权才用 tablePath + createMissing:true + pathDescriptions;不要每条任务新建表。',
|
|
11
|
+
'一次性问答、临时查询不建任务;物品登记走 storage.create,开发 storage 功能才走 tasks。',
|
|
12
|
+
'目标不确定或多候选:展示路径与描述请用户选;唯一候选也仅建议核对,不按第一项、热度或分数自动写入。',
|
|
13
|
+
'结论要标注来源:运行时 action 返回用于判断当前能力,源码只说明实现,历史任务只说明意图;三者冲突时先做只读核对再下结论。',
|
|
14
|
+
];
|
|
15
|
+
export const NO_MATCH_STEPS = [
|
|
16
|
+
'taskNodes.overview({}):读取完整节点树(名称、类型、完整路径、职责描述、子树任务数),确认是否已有合适任务表',
|
|
17
|
+
'tasks.capabilities({limit:200}):分页浏览全部任务表;truncated=true 时按 nextCursor 继续,不能把一页当作全部',
|
|
18
|
+
'核对确属新路径且已获授权:tasks.create 传 tablePath + createMissing:true + pathDescriptions;不要每条任务新建表',
|
|
19
|
+
];
|
|
20
|
+
export const EVIDENCE_NOTE = '本次结果来自当前实例运行时数据;未配置 domain→tableId 映射、关键词未命中、任务表不存在是三件不同的事,不能互相推断。';
|
|
21
|
+
export function tableCatalog(db, api) {
|
|
22
|
+
const map = nodeMap(db), tables = [], diagnostics = [];
|
|
23
|
+
const tagDomainAvailable = tagsAvailable(db, api);
|
|
24
|
+
for (const row of map.values()) {
|
|
25
|
+
if (row.deleted_at != null || String(row.type) !== '1') continue;
|
|
26
|
+
let path;
|
|
27
|
+
try { path = pathFromMap(row.id, map); }
|
|
28
|
+
catch (error) { diagnostics.push({ id: String(row.id), code: error.code, message: error.message }); continue; }
|
|
29
|
+
const counts = db.prepare("SELECT COUNT(*) AS total, SUM(CASE WHEN status='0' THEN 1 ELSE 0 END) AS active, MAX(updated_at) AS used FROM task WHERE table_id=? AND deleted_at IS NULL").get(String(row.id));
|
|
30
|
+
const commonTags = tagDomainAvailable ? db.prepare("SELECT g.id,g.name,COUNT(DISTINCT t.id) AS count FROM task t JOIN tag_mapping m ON m.item_type='task' AND m.item_id=t.id AND m.deleted_at IS NULL JOIN tag g ON g.id=m.tag_id AND g.deleted_at IS NULL WHERE t.table_id=? AND t.deleted_at IS NULL GROUP BY g.id,g.name ORDER BY count DESC,g.id ASC LIMIT 5").all(String(row.id)).map(g => ({ id: String(g.id), name: g.name, count: Number(g.count) })) : [];
|
|
31
|
+
tables.push({ id: String(row.id), name: row.name, ...path, description: String(row.description || ''), taskCount: Number(counts.total), activeTaskCount: Number(counts.active || 0), lastUsedAt: counts.used == null ? null : Number(counts.used), lastUsedBasis: 'MAX(updated_at) of non-deleted tasks; not reading/access time', commonTags, commonTagsStatus: tagDomainAvailable ? 'available' : 'unavailable' });
|
|
32
|
+
}
|
|
33
|
+
tables.sort((candidateA,candidateB) => candidateA.id < candidateB.id ? -1 : candidateA.id > candidateB.id ? 1 : 0);
|
|
34
|
+
return { tables, diagnostics, tagDomainAvailable };
|
|
35
|
+
}
|
|
36
|
+
// 规则 v1:有限停用短语与显式同义词,不声称自然语言语义理解。
|
|
37
|
+
export const MATCH_RULE_VERSION = 'terms-v1';
|
|
38
|
+
const SYNONYMS = [['存储', 'storage'], ['任务', 'tasks'], ['标签', 'tags'], ['站点', 'sites']];
|
|
39
|
+
function termsOf(query) {
|
|
40
|
+
const cleaned = query.toLowerCase().replace(/相关的|相关|的待办|待办|请帮我|帮我|我要|一个|任务$/g, ' ').trim();
|
|
41
|
+
const terms = cleaned.split(/[\s,,。;;]+/).filter(Boolean);
|
|
42
|
+
for (const pair of SYNONYMS) if (pair.some(s => cleaned.includes(s))) for (const s of pair) if (!terms.includes(s)) terms.push(s);
|
|
43
|
+
return terms;
|
|
44
|
+
}
|
|
45
|
+
export function resolveTable(db, args, api) {
|
|
46
|
+
if (typeof args.query !== 'string' || !args.query.trim()) throw ownershipError('INVALID_QUERY', 'query 必须是非空字符串');
|
|
47
|
+
const query = args.query.trim(), terms = termsOf(query);
|
|
48
|
+
const limit = limitArg(args.limit, 5, 20);
|
|
49
|
+
const catalog = tableCatalog(db, api);
|
|
50
|
+
const candidates = [];
|
|
51
|
+
for (const table of catalog.tables) {
|
|
52
|
+
const matchedOn = [], reasons = [];
|
|
53
|
+
let score = 0;
|
|
54
|
+
if (table.name.toLowerCase() === query.toLowerCase()) { score = 1000; matchedOn.push('nameExact'); reasons.push('表名精确匹配'); }
|
|
55
|
+
for (const [field, text, weight] of [['name', table.name, 100], ['path', table.path, 30], ['description', table.description, 10], ['commonTags', table.commonTags.map(g => g.name).join(' '), 3]]) {
|
|
56
|
+
const hits = terms.filter(term => String(text).toLowerCase().includes(term));
|
|
57
|
+
if (hits.length) { score += weight; matchedOn.push(field); reasons.push(field + ' 词项匹配:' + hits.join('、')); }
|
|
58
|
+
}
|
|
59
|
+
if (score) candidates.push({ ...table, score, matchedOn, reasons });
|
|
60
|
+
}
|
|
61
|
+
candidates.sort((candidateA,candidateB) => candidateB.score-candidateA.score || (candidateB.lastUsedAt || 0)-(candidateA.lastUsedAt || 0) || (candidateA.id < candidateB.id ? -1 : candidateA.id > candidateB.id ? 1 : 0));
|
|
62
|
+
const noMatch = candidates.length === 0;
|
|
63
|
+
const notice = noMatch
|
|
64
|
+
? '本次关键词未命中,不代表不存在任务表:当前实例共有 ' + catalog.tables.length + ' 张存活任务表可浏览,请按 nextActions 只读核对后再决定是否新建。'
|
|
65
|
+
: '候选按确定性词项打分,仅供核对;不存在自动选择或自动写入。';
|
|
66
|
+
return {
|
|
67
|
+
candidates: candidates.slice(0,limit), total: candidates.length, truncated: candidates.length > limit,
|
|
68
|
+
needsSelection: true, noMatch: noMatch, catalogSize: catalog.tables.length,
|
|
69
|
+
terms: terms, matchMethod: 'deterministic-terms', matchRuleVersion: MATCH_RULE_VERSION,
|
|
70
|
+
notice: notice, evidence: EVIDENCE_NOTE,
|
|
71
|
+
nextActions: noMatch ? NO_MATCH_STEPS : ['展示 pathSegments 与 description 给用户确认', '确认后用 tasks.capabilities({tableId}) 复核完整祖先链,再带 tableId 创建'],
|
|
72
|
+
diagnostics: catalog.diagnostics, guidance: GUIDANCE,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
function limitArg(value, fallback, max) {
|
|
76
|
+
if (value === undefined) return fallback;
|
|
77
|
+
if (!Number.isInteger(value) || value < 1) throw ownershipError('INVALID_LIMIT', 'limit 必须是正整数');
|
|
78
|
+
return Math.min(max, value);
|
|
79
|
+
}
|
|
80
|
+
export function taskCapabilities(db, args, api) {
|
|
81
|
+
const { tables, diagnostics, tagDomainAvailable } = tableCatalog(db, api);
|
|
82
|
+
const limit = limitArg(args.limit, 50, 200);
|
|
83
|
+
if (args.tableId !== undefined) {
|
|
84
|
+
if (args.cursor !== undefined) throw ownershipError('INVALID_TARGET_OPTIONS', 'tableId 与 cursor 互斥');
|
|
85
|
+
const row = db.prepare('SELECT * FROM task_node WHERE id=? AND deleted_at IS NULL').get(String(args.tableId));
|
|
86
|
+
if (!row) throw ownershipError('TABLE_NOT_FOUND', '任务表不存在:' + args.tableId);
|
|
87
|
+
if (String(row.type) !== '1') throw ownershipError('TARGET_NOT_TABLE', '目标不是任务表:' + args.tableId);
|
|
88
|
+
pathFromMap(row.id, nodeMap(db));
|
|
89
|
+
return { guidance: GUIDANCE, tables: tables.filter(t => t.id === String(args.tableId)), total: 1, nextCursor: null, truncated: false, tagDomainAvailable, diagnostics };
|
|
90
|
+
}
|
|
91
|
+
const fingerprint = createHash('sha256').update(JSON.stringify(tables)).digest('hex');
|
|
92
|
+
let offset = 0;
|
|
93
|
+
if (args.cursor !== undefined) {
|
|
94
|
+
try {
|
|
95
|
+
const cursor = JSON.parse(Buffer.from(args.cursor, 'base64url').toString());
|
|
96
|
+
if (cursor.fingerprint !== fingerprint || !Number.isInteger(cursor.offset) || cursor.offset < 1 || cursor.offset >= tables.length) throw new Error('stale');
|
|
97
|
+
offset = cursor.offset;
|
|
98
|
+
} catch { throw ownershipError('INVALID_CURSOR', '游标已失效,请不带 cursor 重新查询 tasks.capabilities'); }
|
|
99
|
+
}
|
|
100
|
+
const end = Math.min(offset + limit, tables.length);
|
|
101
|
+
const empty = tables.length === 0;
|
|
102
|
+
return {
|
|
103
|
+
guidance: GUIDANCE, tables: tables.slice(offset,end), total: tables.length,
|
|
104
|
+
nextCursor: end < tables.length ? Buffer.from(JSON.stringify({ fingerprint, offset: end })).toString('base64url') : null,
|
|
105
|
+
truncated: end < tables.length, tagDomainAvailable, diagnostics,
|
|
106
|
+
notice: empty
|
|
107
|
+
? '当前没有任何存活任务表(节点树里 type=table 的节点为 0),这与「未配置 domain→tableId 映射」不同。先 taskNodes.overview 查看节点树;确需新表时用 tasks.create 的 tablePath + createMissing:true + pathDescriptions(先获授权)。'
|
|
108
|
+
: (end < tables.length ? '已分页:还有 ' + (tables.length - end) + ' 张表未返回,用 nextCursor 继续,不能把本页当作全部。' : '已返回全部 ' + tables.length + ' 张任务表。'),
|
|
109
|
+
evidence: EVIDENCE_NOTE,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export function registerDiscoveryActions(api) {
|
|
113
|
+
api.action('tasks.capabilities', {
|
|
114
|
+
description: '只读任务归属发现:先核对职责、路径再创建。未配置 domain→tableId 映射不阻断在核对现有表职责后创建任务,也不是「没有任务表」。分页不能当作全部表,truncated 时用 nextCursor;tableId 精确查询与 cursor 互斥。' + GUIDANCE.join(' '),
|
|
115
|
+
input: { type: 'object', properties: { limit: { type: 'integer', minimum: 1, description: '默认50,最大200' }, cursor: { type: 'string', description: '上一页 nextCursor;失效时重新查询' }, tableId: { type: ['string','number'], description: '精确验证存活任务表与完整祖先链;与cursor互斥' } } },
|
|
116
|
+
execute: args => taskCapabilities(api.db, args || {}, api), render: result => JSON.stringify(result),
|
|
117
|
+
});
|
|
118
|
+
api.action('tasks.resolveTable', {
|
|
119
|
+
description: '只读候选检索,确定性词项匹配(非语义推断),只返回合法任务表;即使唯一候选也需核对,不自动创建。候选为空时返回 noMatch、catalogSize、notice 与 nextActions:关键词未命中不代表没有任务表,先按下一步只读核对。' + GUIDANCE.join(' '),
|
|
120
|
+
input: { type: 'object', required: ['query'], properties: { query: { type: 'string', minLength: 1, description: '任务主题,SQL通配符按文字匹配' }, limit: { type: 'integer', minimum: 1, description: '默认5,最大20' } } },
|
|
121
|
+
execute: args => resolveTable(api.db, args || {}, api), render: result => JSON.stringify(result),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** 四组事件日期范围共用真实日期校验;只比较存储值的日期部分。 */
|
|
2
|
+
function rangeDay(value, field) {
|
|
3
|
+
if (value === undefined || value === null || value === "") return null;
|
|
4
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
|
5
|
+
throw new Error(field + " 必须是合法的 YYYY-MM-DD 日期");
|
|
6
|
+
}
|
|
7
|
+
const [year, month, day] = value.split("-").map(Number);
|
|
8
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
9
|
+
if (year < 1 || month < 1 || month > 12 || day < 1 ||
|
|
10
|
+
day > [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]) {
|
|
11
|
+
throw new Error(field + " 必须是合法的 YYYY-MM-DD 日期");
|
|
12
|
+
}
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function dateRangeFilter(from, to, kind) {
|
|
17
|
+
const fromKey = kind + "From", toKey = kind + "To";
|
|
18
|
+
let start = rangeDay(from, fromKey), end = rangeDay(to, toKey);
|
|
19
|
+
const notices = [];
|
|
20
|
+
if (start && end && start > end) {
|
|
21
|
+
[start, end] = [end, start];
|
|
22
|
+
const label = { publish: "发布", done: "完成", shutdown: "关闭", claimed: "接取" }[kind];
|
|
23
|
+
notices.push({ code: kind + "_range_swapped", field: fromKey + "/" + toKey,
|
|
24
|
+
message: label + "日期起始晚于终止,已交换", [fromKey]: start, [toKey]: end });
|
|
25
|
+
}
|
|
26
|
+
return { [fromKey]: start, [toKey]: end, notices };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function publishFilter(from, to) {
|
|
30
|
+
return dateRangeFilter(from, to, "publish");
|
|
31
|
+
}
|