nx-kv 0.24.6 → 0.26.0

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 (68) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/assets/kv-get/SKILL.md +11 -13
  3. package/assets/kv-get/references/localget.md +8 -8
  4. package/assets/kv-get/references/timegoal-workflow.md +2 -3
  5. package/assets/kv-get/references/timegoal.md +5 -26
  6. package/assets/kv-get/references/wait-workflow.md +24 -40
  7. package/assets/kv-get/references/waitloop.md +19 -29
  8. package/assets/kv-submit/SKILL.md +2 -2
  9. package/assets/kv-submit/references/submit-workflow.md +1 -1
  10. package/assets/nx-kv/SKILL.md +6 -25
  11. package/assets/nx-kv/references/repo-registry.md +1 -5
  12. package/assets/nx-kv/references/todo-commands.md +3 -3
  13. package/package.json +1 -1
  14. package/src/core/json-store.js +219 -0
  15. package/src/modules/localtask/index.js +168 -14
  16. package/src/modules/localtask/panel-presence.js +7 -7
  17. package/src/modules/localtask/store-io.js +42 -107
  18. package/src/modules/localtask/task-lifecycle.js +128 -54
  19. package/src/modules/localtask/task-ops.js +43 -2
  20. package/src/modules/localtask/task-view.js +189 -8
  21. package/src/modules/repos/service.js +32 -47
  22. package/src/modules/tasktool/add.js +5 -0
  23. package/src/modules/tasktool/attach.js +6 -2
  24. package/src/modules/tasktool/delivery-text.js +23 -0
  25. package/src/modules/tasktool/plugins/taskgoal-store.js +42 -0
  26. package/src/modules/tasktool/plugins/timegoal-store.js +19 -33
  27. package/src/modules/tasktool/preview.js +96 -0
  28. package/src/modules/tasktool/wait.js +35 -11
  29. package/src/modules/templates/service.js +23 -37
  30. package/src/web/frontend/App.jsx +4 -0
  31. package/src/web/frontend/components/md/sel-menu.jsx +112 -19
  32. package/src/web/frontend/components/md/task-chain.jsx +75 -0
  33. package/src/web/frontend/components/md/tool-bar.jsx +14 -0
  34. package/src/web/frontend/components/sidebar/index.jsx +1 -9
  35. package/src/web/frontend/components/sidebar/model.js +9 -20
  36. package/src/web/frontend/modules/board/ack-nodes.js +2 -2
  37. package/src/web/frontend/modules/md/lightbox.js +97 -0
  38. package/src/web/frontend/modules/md/style.css +85 -0
  39. package/src/web/frontend/page/dir/index.jsx +32 -15
  40. package/src/web/frontend/page/dir/landing.jsx +2 -2
  41. package/src/web/frontend/page/dir/task.jsx +440 -75
  42. package/src/web/frontend/page/group/index.jsx +4 -4
  43. package/src/web/frontend/page/progress/index.jsx +19 -9
  44. package/src/web/frontend/page/settings/index.jsx +7 -0
  45. package/src/web/frontend/page/settings/sidebar-section.jsx +72 -0
  46. package/src/web/frontend/panels.jsx +13 -4
  47. package/src/web/public/assets/{Introduction-B_U-xbb9.js → Introduction-ka0UxW_S.js} +1 -1
  48. package/src/web/public/assets/{cloud-zp3n4ola.js → cloud-y1mZIdlN.js} +1 -1
  49. package/src/web/public/assets/{dag-Clekc4yJ.js → dag-CiMSs7uT.js} +1 -1
  50. package/src/web/public/assets/dir-DKzzrY8P.js +3 -0
  51. package/src/web/public/assets/group-DOLdLkaj.js +1 -0
  52. package/src/web/public/assets/{index-3r8gg9d1.js → index-CbZfbzqr.js} +3 -3
  53. package/src/web/public/assets/{index-B1yzxhtQ.css → index-DUvCgdUV.css} +1 -1
  54. package/src/web/public/assets/{md-history-DUYRtww_.js → md-history-Ddk04A_2.js} +1 -1
  55. package/src/web/public/assets/{member-picker-Bw2AsF1j.js → member-picker-Dsy1GH0E.js} +1 -1
  56. package/src/web/public/assets/{overview-B4pRZYIr.js → overview-ty9m-bCh.js} +1 -1
  57. package/src/web/public/assets/{progress-Bwcg-x19.js → progress-BQJhISlF.js} +2 -2
  58. package/src/web/public/assets/{repos-BO0Eoktc.js → repos-Di5InllN.js} +1 -1
  59. package/src/web/public/assets/{route-crumb-DWHcDjTH.js → route-crumb-g3leiQhY.js} +1 -1
  60. package/src/web/public/assets/{settings-BUSNdkTd.js → settings-CE-rlcXr.js} +3 -3
  61. package/src/web/public/assets/task-D97dEZdc.js +6 -0
  62. package/src/web/public/assets/{template-slots-D6x4JKZ3.js → template-slots-D40ponA2.js} +1 -1
  63. package/src/web/public/assets/{templates-CESTAUsK.js → templates-Ca1jXhnO.js} +1 -1
  64. package/src/web/public/assets/{upload-d5Uchr6Y.js → upload-BeiJetbd.js} +1 -1
  65. package/src/web/public/index.html +2 -2
  66. package/src/web/public/assets/dir-Cll78K45.js +0 -3
  67. package/src/web/public/assets/group-dtrdwnRv.js +0 -1
  68. package/src/web/public/assets/task-DrUzpfEg.js +0 -5
@@ -2,10 +2,11 @@
2
2
  // normalizeTask(含 ready 徽标)、topicView、跨队列依赖解析器(foreignResolver)、
3
3
  // 队列内关系清单(queueRelationsOf)与搬家(relocateInStore)。
4
4
  import { basename } from 'node:path';
5
+ import { badInput, notFound } from '../../core/errors.js';
5
6
  import { sanitizeTaskGoal } from '../tasktool/taskgoal.js';
6
7
  import { normalizeBlockBy, isReadyToClaim } from './dag.js';
7
- import { isGlobalKey, topicKeyFor } from './paths.js';
8
- import { stampNow, parseStampMs, topicOf, nextTaskId } from './store-io.js';
8
+ import { isGlobalKey, topicKeyFor, resolveTaskKey } from './paths.js';
9
+ import { stampNow, parseStampMs, topicOf, nextTaskId, loadStore } from './store-io.js';
9
10
  // 领取耗时(秒):**发布 → 被领取**的时间差。
10
11
  // 数据本来就在(createdAt / consumedAt),这里算成派生字段,省得每个使用方自己算,
11
12
  // 也省得存一份会漂移的冗余副本。
@@ -95,8 +96,8 @@ export function normalizeTask(t, siblings, readyOpts = {}) {
95
96
  const base = {
96
97
  id: Number(t.id) || 0,
97
98
  text: String(t.text ?? ''),
98
- // 状态词汇:pending → consumed(已领取)→ archived(终态:被新任务取代)。
99
- // **单向**:没有回退边——完成等待验收之后只能往前(归档),不能回 pending(#59)。
99
+ // 状态词汇:pending → consumed(已领取);完成验收后可就地回 pending(#74)。
100
+ // archived 仍保留给旧口径(#59 fork 取代)的残留行,不再由 reopen 写入。
100
101
  status: t.status === 'consumed' ? 'consumed' : t.status === 'archived' ? 'archived' : 'pending',
101
102
  roundSummary: String(t.roundSummary ?? ''),
102
103
  createdAt: String(t.createdAt ?? ''),
@@ -122,11 +123,14 @@ export function normalizeTask(t, siblings, readyOpts = {}) {
122
123
  timegoal: sanitizeTaskGoal(t.timegoal),
123
124
  // 完成标记(localtask done 写入):带时间目标的任务未到点会被拒绝,写不进来。
124
125
  completedAt: String(t.completedAt ?? ''),
125
- // 重开轨迹:现在重开 = **新建一条任务**,旧任务归档(#59)。
126
- // forkOf 这条是从哪一条派生的('队列key:旧编号')
127
- // supersededBy 被哪一条取代(归档那条的落点:{ key, id })
128
- // archivedAt / archivedReason 归档时刻与原因
126
+ // 重开轨迹(#74):就地重开,历史进 history[];forkOf 仅兼容旧 #59/#69 派生数据。
127
+ // history 同任务内的链节点(origin / reopen / comment),点开可旁路查看
128
+ // forkOf 旧派生链('队列key:旧编号')——新 reopen 不再写
129
+ // forkKind 最近一次事件种类(reopen / comment),或旧派生种类
130
+ // supersededBy / archived* 旧归档残留字段
131
+ history: normalizeHistory(t.history),
129
132
  forkOf: String(t.forkOf ?? ''),
133
+ forkKind: t.forkKind === 'reopen' || t.forkKind === 'comment' ? t.forkKind : '',
130
134
  supersededBy: t.supersededBy && typeof t.supersededBy === 'object' ? t.supersededBy : null,
131
135
  archivedAt: String(t.archivedAt ?? ''),
132
136
  archivedReason: String(t.archivedReason ?? ''),
@@ -222,3 +226,180 @@ export function topicView(t, repoCtx = null, readyOpts = {}) {
222
226
  tasks,
223
227
  };
224
228
  }
229
+
230
+ // ─── 任务链(#69) ────────────────────────────────────────────────────
231
+ /** 规范化任务内 history 链(#74)。非法项丢弃,顺序保留。 */
232
+ export function normalizeHistory(raw) {
233
+ if (!Array.isArray(raw)) return [];
234
+ const out = [];
235
+ for (const h of raw) {
236
+ if (!h || typeof h !== 'object') continue;
237
+ const kind = h.kind === 'comment' || h.kind === 'origin' ? h.kind : 'reopen';
238
+ const attachments = Array.isArray(h.attachments)
239
+ ? h.attachments
240
+ .filter((a) => a && typeof a === 'object')
241
+ .map((a) => ({
242
+ id: String(a.id || ''),
243
+ name: String(a.name || ''),
244
+ type: a.type === 'image' ? 'image' : 'file',
245
+ size: String(a.size || ''),
246
+ url: a.url ? String(a.url) : '',
247
+ }))
248
+ : [];
249
+ out.push({
250
+ id: Number(h.id) || out.length + 1,
251
+ kind,
252
+ at: String(h.at ?? ''),
253
+ text: String(h.text ?? ''),
254
+ summary: String(h.summary ?? ''),
255
+ status: String(h.status ?? ''),
256
+ completedAt: String(h.completedAt ?? ''),
257
+ quote: String(h.quote ?? ''),
258
+ feedback: String(h.feedback ?? ''),
259
+ attachments,
260
+ excerpt: String(h.excerpt ?? '')
261
+ .replace(/^#+\s*/, '')
262
+ .slice(0, 100),
263
+ });
264
+ }
265
+ return out;
266
+ }
267
+
268
+ // 任务链两套来源(#74 / 兼容 #69):
269
+ // history[] —— 同任务内就地重开/评论节点(主路径)
270
+ // forkOf 派生 —— 旧「新建任务」链(祖先 + 子任务)
271
+ // 三个原语:
272
+ // resolveForkRef —— 发布侧:裸数字(同主题)/'key:id'(跨主题)规范化 + 验证父任务存在
273
+ // forkRow —— 按引用取行(内部;软删/迁出不算存在)
274
+ // taskChain —— 查询侧:history 节点 + 祖先链 + 子任务
275
+
276
+ function forkRow(store, ref) {
277
+ const m = /^(.+):(\d+)$/.exec(String(ref || ''));
278
+ if (!m) return null;
279
+ const topic = store.topics[m[1]];
280
+ if (!topic) return null;
281
+ const task = (topic.tasks || []).find(
282
+ (x) => Number(x.id) === Number(m[2]) && !x.deletedAt && !x.migratedTo,
283
+ );
284
+ return task ? { topic, task } : null;
285
+ }
286
+
287
+ /** 发布侧把 forkOf 引用规范化成 'key:id'。父任务不存在直接报错(链就是拿来查的,虚链没意义)。 */
288
+ export function resolveForkRef(store, raw, defaultKey) {
289
+ const s = String(raw ?? '').trim();
290
+ if (!s) throw badInput('forkOf 不能为空');
291
+ const m = /^(.+):(\d+)$/.exec(s);
292
+ const key = m ? m[1] : String(defaultKey || '');
293
+ const id = Number(m ? m[2] : s);
294
+ if (!key) throw badInput(`forkOf 跨主题引用必须带主题: ${s}('key:id')`);
295
+ if (!Number.isFinite(id) || id <= 0) {
296
+ throw badInput(`forkOf 无法解析: ${s}(裸数字=同主题父任务编号,或 'key:id'=跨主题)`);
297
+ }
298
+ if (!forkRow(store, `${key}:${id}`)) {
299
+ throw badInput(`forkOf 指向的任务不存在: ${key}:${id}`);
300
+ }
301
+ return `${key}:${id}`;
302
+ }
303
+
304
+ // 链条节点的人读视图:不吐正文全文(链上可能一长串),给首行节选。
305
+ function chainLite(topic, t) {
306
+ const firstLine =
307
+ String(t.text ?? '')
308
+ .split('\n')
309
+ .map((l) => l.trim())
310
+ .find(Boolean) || '';
311
+ return {
312
+ key: topic.key,
313
+ name: topic.name,
314
+ id: Number(t.id) || 0,
315
+ status: t.status,
316
+ forkKind: t.forkKind === 'reopen' || t.forkKind === 'comment' ? t.forkKind : '',
317
+ forkOf: String(t.forkOf ?? ''),
318
+ createdAt: String(t.createdAt ?? ''),
319
+ excerpt: firstLine.replace(/^#+\s*/, '').slice(0, 100),
320
+ };
321
+ }
322
+
323
+ /** 任务链查询:同任务 history 节点 + 旧 forkOf 祖先/子任务。 */
324
+ export async function taskChain({ id, cwd, key } = {}) {
325
+ const k = resolveTaskKey({ key, cwd });
326
+ const want = Number(id);
327
+ if (!Number.isFinite(want) || want <= 0) throw badInput('缺少参数 --id <任务编号>');
328
+ const store = await loadStore();
329
+ const t = store.topics[k];
330
+ if (!t) throw notFound('主题不存在: ' + k);
331
+ const self = (t.tasks || []).find((x) => Number(x.id) === want && !x.deletedAt && !x.migratedTo);
332
+ if (!self) throw notFound('任务不存在或已删除: #' + want);
333
+
334
+ const history = normalizeHistory(self.history);
335
+ // nodes:history 按时间序 + 当前尖(live)。面板链图只吃这一列。
336
+ const nodes = history.map((h) => ({
337
+ historyId: h.id,
338
+ kind: h.kind,
339
+ at: h.at,
340
+ excerpt: h.excerpt || h.feedback?.slice(0, 100) || '',
341
+ feedback: h.feedback,
342
+ quote: h.quote,
343
+ summary: h.summary,
344
+ status: h.status,
345
+ completedAt: h.completedAt,
346
+ attachmentCount: (h.attachments || []).length,
347
+ current: false,
348
+ }));
349
+ const tipExcerpt =
350
+ String(self.text ?? '')
351
+ .split('\n')
352
+ .map((l) => l.trim())
353
+ .find(Boolean) || '';
354
+ nodes.push({
355
+ historyId: null,
356
+ kind: 'current',
357
+ at: String(self.lastReopenedAt || self.createdAt || ''),
358
+ excerpt: tipExcerpt.replace(/^#+\s*/, '').slice(0, 100),
359
+ feedback: '',
360
+ quote: '',
361
+ summary: String(self.roundSummary || ''),
362
+ status: self.status,
363
+ completedAt: String(self.completedAt || ''),
364
+ attachmentCount: 0,
365
+ current: true,
366
+ });
367
+
368
+ // 祖先链:visited 防环;上限 32(这是条链不是树,合理深度远小于它——超限即数据异常)
369
+ const ancestors = [];
370
+ const seen = new Set([`${k}:${want}`]);
371
+ let cur = String(self.forkOf || '');
372
+ while (cur && ancestors.length < 32) {
373
+ if (seen.has(cur)) break;
374
+ seen.add(cur);
375
+ const row = forkRow(store, cur);
376
+ if (!row) {
377
+ // 引用还在、行没了(软删 / 迁出 / 旧格式)——如实标注,不静默吞
378
+ ancestors.push({ ref: cur, missing: true });
379
+ break;
380
+ }
381
+ ancestors.push(chainLite(row.topic, row.task));
382
+ cur = String(row.task.forkOf || '');
383
+ }
384
+ // 子任务:派生落点可能换主题(旧 reopen 带 moveTo / 评论跨队列),所以全 store 扫
385
+ const ref = `${k}:${want}`;
386
+ const children = [];
387
+ for (const topic of Object.values(store.topics)) {
388
+ for (const x of topic.tasks || []) {
389
+ if (x.deletedAt || x.migratedTo) continue;
390
+ if (String(x.forkOf || '') === ref) children.push(chainLite(topic, x));
391
+ }
392
+ }
393
+ children.sort((a, b) => a.id - b.id);
394
+ return {
395
+ status: 'ok',
396
+ key: k,
397
+ name: t.name,
398
+ id: want,
399
+ task: normalizeTask(self, t.tasks),
400
+ nodes,
401
+ history,
402
+ ancestors,
403
+ children,
404
+ };
405
+ }
@@ -12,6 +12,7 @@
12
12
  import { basename, join, resolve } from 'node:path';
13
13
  import fsp from 'node:fs/promises';
14
14
  import { APP_DIR } from '../../core/paths.js';
15
+ import { createJsonStore } from '../../core/json-store.js';
15
16
  import { openPath } from '../../core/open.js';
16
17
  import { badInput, notFound, conflict } from '../../core/errors.js';
17
18
  import { sanitizeDocRef, withLinkMeta } from '../docs/docref.js';
@@ -28,57 +29,41 @@ function emptyStore() {
28
29
  return { version: 1, repos: [], boards: [] };
29
30
  }
30
31
 
31
- // 原子写 + 进程内串行化(与 localtask / timegoal 同一模式:Windows 上 rename
32
- // 偶发 EPERM,重试几次即可;串行化避免并发写互相覆盖)。
33
- let saveQueue = Promise.resolve();
34
- function saveStore(data) {
35
- const run = saveQueue.then(async () => {
36
- const p = storePath();
37
- await fsp.mkdir(join(p, '..'), { recursive: true });
38
- const tmp = p + '.tmp';
39
- await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');
40
- for (let i = 0; ; i++) {
41
- try {
42
- await fsp.rename(tmp, p);
43
- return;
44
- } catch (err) {
45
- if (i >= 4 || (err.code !== 'EPERM' && err.code !== 'EACCES')) throw err;
46
- await new Promise((r) => setTimeout(r, 25 * (i + 1)));
47
- }
48
- }
49
- });
50
- saveQueue = run.then(
51
- () => {},
52
- () => {}
53
- );
54
- return run;
32
+ // 原子写 / 串行队列 / EPERM 退避收口到 core/json-store.js(任务 #66,SQLite 迁移只换那层)。
33
+ // 语义:缺失或损坏 → 空 store(无隔离备份,本 store 写频率低、可重建);形状不认识 → 空 store。
34
+ function normalizeRawStore(data) {
35
+ if (!data || typeof data !== 'object') return null;
36
+ const store = {
37
+ // v2 起 store 携带文档绑定字段(doc / docLinks / repoDocs,DocRef 形状)
38
+ version: 2,
39
+ repos: Array.isArray(data.repos) ? data.repos : [],
40
+ boards: Array.isArray(data.boards) ? data.boards : [],
41
+ // prefixGroups(前缀分组规则)已废除(2026-11-02):规则改一次性命令
42
+ // (board prefix),命中结果固化成显式成员(repoKeys),盘上残留字段下次
43
+ // 落盘时随本白名单一起丢弃。
44
+ };
45
+ normalizeDocRefs(store);
46
+ return store;
47
+ }
48
+
49
+ const store = createJsonStore({
50
+ path: storePath,
51
+ empty: emptyStore,
52
+ normalize: normalizeRawStore,
53
+ });
54
+
55
+ export function saveStore(data) {
56
+ return store.save(data);
55
57
  }
56
58
 
57
59
  export async function loadStore() {
58
- try {
59
- const raw = await fsp.readFile(storePath(), 'utf8');
60
- const data = JSON.parse(raw);
61
- if (!data || typeof data !== 'object') return emptyStore();
62
- const store = {
63
- // v2 起 store 携带文档绑定字段(doc / docLinks / repoDocs,DocRef 形状)
64
- version: 2,
65
- repos: Array.isArray(data.repos) ? data.repos : [],
66
- boards: Array.isArray(data.boards) ? data.boards : [],
67
- // prefixGroups(前缀分组规则)已废除(2026-11-02):规则改一次性命令
68
- // (board prefix),命中结果固化成显式成员(repoKeys),盘上残留字段下次
69
- // 落盘时随本白名单一起丢弃。
70
- };
71
- normalizeDocRefs(store);
72
- // 老结构(看板成员存随机 id)→ 新结构(存 key):读时改写并落盘。
73
- // 放这里 = 唯一入口,任何读路径都自动看到迁移后的数据。
74
- if (migrateStoreKeys(store)) {
75
- await saveStore(store).catch(() => {});
76
- }
77
- return store;
78
- } catch {
79
- /* 缺失或损坏 → 空 store */
80
- return emptyStore();
60
+ const s = await store.load();
61
+ // 老结构(看板成员存随机 id)→ 新结构(存 key):读时改写并落盘。
62
+ // 放这里 = 唯一入口,任何读路径都自动看到迁移后的数据。
63
+ if (migrateStoreKeys(s)) {
64
+ await saveStore(s).catch(() => {});
81
65
  }
66
+ return s;
82
67
  }
83
68
 
84
69
  // v2 文档绑定归一:非法 DocRef 形状直接丢弃(盘上脏数据不炸读取)。
@@ -55,6 +55,8 @@ export async function submitTask({
55
55
  goalPrompt,
56
56
  blockBy,
57
57
  blocksFollowing = false,
58
+ forkOf,
59
+ forkKind,
58
60
  } = {}) {
59
61
  let text = String(rawText ?? '');
60
62
  let cwd = rawCwd;
@@ -98,5 +100,8 @@ export async function submitTask({
98
100
  timegoal,
99
101
  blockBy,
100
102
  blocksFollowing: !!blocksFollowing,
103
+ // 任务链(#69):这条任务从哪条派生(裸数字=同主题父任务,'key:id'=跨主题)
104
+ forkOf,
105
+ forkKind,
101
106
  });
102
107
  }
@@ -38,10 +38,14 @@ async function todoAttachMod() {
38
38
  * 领取/查看时刻的附件标注:本机仓优先 → 云端镜像兜底 → 标注本地路径。
39
39
  *
40
40
  * @param {object|null} task 库存任务(normalizeTask 形状)
41
+ * @param {object} [opts]
42
+ * @param {boolean} [opts.sync=true] 是否允许为未命中的附件跑一次云端同步。
43
+ * 预览(面板「预览 get 提示词」)传 false——**只读盘、不发网**:预览不该因为
44
+ * 打开一次就悄悄下载一堆附件,也不该凭预览改变本机缓存状态。
41
45
  * @returns {Promise<null|{task:object, sync:object|null}>} null = 正文没有附件引用
42
46
  * (调用方据此保持载荷原样);sync 只在真的跑过云端同步时非 null。
43
47
  */
44
- export async function annotateTaskDelivery(task) {
48
+ export async function annotateTaskDelivery(task, { sync: allowSync = true } = {}) {
45
49
  if (!task) return null;
46
50
  const { attachmentRefs } = await todoAttachMod();
47
51
  const refs = attachmentRefs(task.text);
@@ -55,7 +59,7 @@ export async function annotateTaskDelivery(task) {
55
59
  // 不在本机仓的 id 才考虑云端镜像;自动下载关(或全命中)就一次网都不碰
56
60
  const cloudIds = refs.filter((r) => !store.index.has(r.id)).map((r) => r.id);
57
61
  let sync = null;
58
- if (cloudIds.length && cfg.autoSyncAttachments) {
62
+ if (allowSync && cloudIds.length && cfg.autoSyncAttachments) {
59
63
  // 说明文字 → 本地文件名:`![季度报表.docx](id)` 落盘就叫「季度报表.docx」
60
64
  // (与 todo 读任务的同一套语义,见 todo/service.js annotateAttachments)。
61
65
  const names = {};
@@ -0,0 +1,23 @@
1
+ // tasktool/delivery-text.js —— 交付载荷的人读正文(**唯一出处**)。
2
+ //
3
+ // 谁会用到:
4
+ // - CLI `localtask get/wait` 的人读输出(localtask/index.js 的 renderWait)
5
+ // - CLI `localtask preview` 与面板「预览提示词」(tasktool/preview.js)
6
+ //
7
+ // 为什么单独抽出来:预览的全部价值在于「所见即所得」——如果面板自己拼一遍排版,
8
+ // 迟早与 CLI 漂移,用户看到的就不是 agent 收到的那一份。同一份代码 = 同一份文本。
9
+ //
10
+ // 排版口径:instruction 自包含正文(模板含 {{task.text}},服务端给出 coversBody)
11
+ // 时直接替掉正文块(否则正文会出现两遍);否则「正文 + ── 收尾指令 ──」两段。
12
+ export function deliveryBodyText(r) {
13
+ const indent = (s) => String(s).replace(/\n/g, '\n ');
14
+ const taskText = (r && r.task && r.task.text) || '';
15
+ if (r && r.instruction && r.coversBody) return ` ${indent(r.instruction)}`;
16
+ const body = ` ${indent(taskText)}`;
17
+ return r && r.instruction ? `${body}\n ── 收尾指令 ──\n ${indent(r.instruction)}` : body;
18
+ }
19
+
20
+ /** 去缩进版本(面板 <pre> 用;CLI 保留两格缩进贴合既有输出)。 */
21
+ export function deliveryPlainText(r) {
22
+ return deliveryBodyText(r).replace(/^ {2}/gm, '');
23
+ }
@@ -97,4 +97,46 @@ export async function ensureTaskGoal(p) {
97
97
  };
98
98
  }
99
99
 
100
+ /**
101
+ * 预览用的 goal 上下文(**零副作用**:不起表、不写盘)。
102
+ *
103
+ * 「预览 get 提示词」必须与真实领取**逐字一致**,否则预览就没有意义:
104
+ * - 已经起过表 → 回显固化后的 prompt(领取时写死在 goal 里的那份原文);
105
+ * - 还没起表(pending 任务)→ 按声明现算(= 领取那一刻会固化的同一份文本)。
106
+ */
107
+ export async function previewTaskGoal({ topicKey, taskId, name, timegoal }) {
108
+ if (!timegoal || !topicKey || taskId === undefined || taskId === null) return null;
109
+ let durationSec;
110
+ try {
111
+ durationSec = parseDuration(timegoal.duration);
112
+ } catch {
113
+ return null;
114
+ }
115
+ const state = await taskGoalState({ topicKey, taskId }).catch(() => null);
116
+ if (state && state.hasGoal && state.goal) {
117
+ return {
118
+ name: state.goal.name || name || `任务 #${taskId}`,
119
+ deadline: state.goal.deadline || '',
120
+ prompt: state.goal.prompt || '',
121
+ goalKey: taskGoalKey(topicKey, taskId),
122
+ durationSec,
123
+ started: true,
124
+ };
125
+ }
126
+ const goalKey = taskGoalKey(topicKey, taskId);
127
+ return {
128
+ name: name || `任务 #${taskId}`,
129
+ deadline: '',
130
+ prompt: taskGoalPrompt({
131
+ goalKey,
132
+ taskId,
133
+ durationHuman: formatDuration(durationSec),
134
+ extra: timegoal.prompt,
135
+ }),
136
+ goalKey,
137
+ durationSec,
138
+ started: false,
139
+ };
140
+ }
141
+
100
142
  export { taskGoalState, recordTaskCheck, taskGoalKey };
@@ -17,10 +17,10 @@
17
17
  // - 与 localtask wait 互不感知:timegoal 不阻塞、不依赖面板是否存在,
18
18
  // agent 按 `reached` 自行决定下一轮动作。
19
19
  import crypto from 'node:crypto';
20
- import fsp from 'node:fs/promises';
21
- import { basename, dirname, join, resolve } from 'node:path';
20
+ import { basename, join, resolve } from 'node:path';
22
21
  import { APP_DIR } from '../../../core/paths.js';
23
22
  import { badInput } from '../../../core/errors.js';
23
+ import { createJsonStore } from '../../../core/json-store.js';
24
24
 
25
25
  export const MIN_DURATION_SEC = 60; // 最小 1 分钟(避免误设 0 立即到点)
26
26
  // 上限从「24 小时」放宽到「365 天」。真实场景里"跑一晚上""连续优化几天"是常态,
@@ -85,42 +85,28 @@ function emptyStore() {
85
85
  }
86
86
 
87
87
  async function loadStore() {
88
- let goals = null;
89
- try {
90
- const raw = await fsp.readFile(storePath(), 'utf8');
91
- const data = JSON.parse(raw);
92
- if (data && typeof data === 'object' && data.goals && typeof data.goals === 'object') {
93
- goals = data.goals;
94
- }
95
- } catch {
96
- /* 缺失或损坏 → 空 store */
97
- }
98
- if (!goals) return emptyStore();
99
- return { version: 1, goals };
88
+ return store.load();
100
89
  }
101
90
 
102
- // 原子写 + 进程内串行化队列;与 localtask service 同模式(Windows 锁偶发 EPERM 重试)。
103
- let saveQueue = Promise.resolve();
104
91
  function saveStore(data) {
105
- const run = saveQueue.then(async () => {
106
- const p = storePath();
107
- await fsp.mkdir(dirname(p), { recursive: true });
108
- const tmp = p + '.tmp';
109
- await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');
110
- for (let i = 0; ; i++) {
111
- try {
112
- await fsp.rename(tmp, p);
113
- return;
114
- } catch (err) {
115
- if (i >= 4 || (err.code !== 'EPERM' && err.code !== 'EACCES')) throw err;
116
- await new Promise((r) => setTimeout(r, 25 * (i + 1)));
117
- }
118
- }
119
- });
120
- saveQueue = run.catch(() => {});
121
- return run;
92
+ return store.save(data);
122
93
  }
123
94
 
95
+ // 原子写 / 串行队列 / EPERM 退避收口到 core/json-store.js(任务 #66)。
96
+ // 语义:缺失或损坏 → 空 store(无隔离备份);形状不认识(goals 不是对象)→ 空 store。
97
+ function normalizeRawStore(data) {
98
+ if (!data || typeof data !== 'object' || !data.goals || typeof data.goals !== 'object') {
99
+ return null;
100
+ }
101
+ return { version: 1, goals: data.goals };
102
+ }
103
+
104
+ const store = createJsonStore({
105
+ path: storePath,
106
+ empty: emptyStore,
107
+ normalize: normalizeRawStore,
108
+ });
109
+
124
110
  function goalView(g, { withPrompt = true } = {}) {
125
111
  const view = {
126
112
  key: g.key,
@@ -0,0 +1,96 @@
1
+ // tasktool/preview.js —— 「预览 get 提示词」(任务 #65)。
2
+ //
3
+ // 用户的诉求是**可观测**:「当前具体会获得怎么样的字符串?」——
4
+ // 编辑页「更多 → 预览 get 提示词」点开就应该看到 agent 领取时会拿到的**那一份原文**,
5
+ // 而不是再去猜「模板 + 参数 + 开关」拼起来大概长什么样。
6
+ //
7
+ // 三条纪律:
8
+ // 1. **零副作用**:不领取、不写盘、不启动时间目标计时、不为附件发网。
9
+ // 预览是只读操作,打开一次不该改变任何状态(见 wait.js 的 preview 分支)。
10
+ // 2. **不复制渲染逻辑**:整条链路就是 buildTaskDelivery + getTask 的持续 get 叠加,
11
+ // 与真实领取走同一份代码——复制一份「预览专用渲染」迟早与真实交付漂移,
12
+ // 那种预览比没有更糟。
13
+ // 3. **分段可追溯**:每段标明来源(交付上下文 / 收尾指令 / check 指令 / 附件 /
14
+ // ack / 持续 get),并附带各项开关的当前状态——用户要能看出「这段是哪来的、
15
+ // 想关该关哪个开关」。
16
+ import { hasTemplateMarkers, renderInstruction } from '../../core/instruction-template.js';
17
+ import { getSettings } from '../localtask/service.js';
18
+ import { deliveryPlainText } from './delivery-text.js';
19
+ import { DEFAULT_GET_LOOP_TEMPLATE, getLoopForCwd } from './getloop.js';
20
+ import { buildTaskDelivery } from './wait.js';
21
+
22
+ /**
23
+ * 预览一条任务的交付载荷。
24
+ *
25
+ * @param {object} p
26
+ * @param {object} p.task 任务行(库存形状;草稿由调用方合成 { id:0, text })
27
+ * @param {string} [p.cwd] 等待方目录(决定组上下文与项目级「持续 get」)
28
+ * @param {string} [p.key] 主题 key(任务级 timegoal 寻址用)
29
+ * @param {string} [p.summary] 现状(模板占位符 {{summary}})
30
+ * @param {object} [p.params] 外部参数(与 --param 同语义)
31
+ * @returns {Promise<object>} { task, instruction, coversBody, segments, getLoop, switches }
32
+ */
33
+ export async function previewTaskDelivery({ task, cwd, key, summary, params } = {}) {
34
+ const settings = (await getSettings().catch(() => null)) || {};
35
+ const segments = [];
36
+ const delivery = await buildTaskDelivery(task, settings.taskSuffix, {
37
+ source: 'local',
38
+ summary: summary || '',
39
+ cwd,
40
+ name: '',
41
+ topicKey: key,
42
+ params: params || {},
43
+ preview: true,
44
+ trace: segments,
45
+ });
46
+
47
+ const previewTask = delivery.task || task;
48
+ let instruction = delivery.instruction || '';
49
+
50
+ // 项目级「持续 get」模板:与 tasktool/get.js 的叠加口径一致(只在开启时出现)
51
+ const loop = await getLoopForCwd(cwd).catch(() => ({ enabled: false }));
52
+ let getLoopText = '';
53
+ if (loop.enabled) {
54
+ const tpl = loop.template || DEFAULT_GET_LOOP_TEMPLATE;
55
+ try {
56
+ if (hasTemplateMarkers(tpl)) {
57
+ getLoopText = renderInstruction(tpl, {
58
+ task: previewTask ? { id: previewTask.id, text: String(previewTask.text || '') } : null,
59
+ source: 'local',
60
+ summary: summary || '',
61
+ cwd: cwd || '',
62
+ name: '',
63
+ goal: null,
64
+ });
65
+ }
66
+ } catch {
67
+ getLoopText = '';
68
+ }
69
+ }
70
+ if (getLoopText) {
71
+ instruction = instruction ? `${instruction}\n\n${getLoopText}` : getLoopText;
72
+ segments.push({ id: 'getloop', label: '持续 get 模板(项目级)', text: getLoopText });
73
+ }
74
+
75
+ const suffixList = settings.taskSuffixList || [];
76
+ const ackList = settings.ackPromptList || [];
77
+ return {
78
+ task: previewTask,
79
+ instruction,
80
+ coversBody: !!delivery.coversBody,
81
+ // 面板 <pre> 直接显示这段:与 CLI 取任务时的正文排版同一份代码
82
+ rendered: deliveryPlainText({ ...delivery, instruction, task: previewTask }),
83
+ segments,
84
+ getLoop: {
85
+ enabled: !!loop.enabled,
86
+ waitMinutes: loop.waitMinutes || 0,
87
+ customTemplate: !!(loop.template && loop.template.trim()),
88
+ },
89
+ switches: {
90
+ suffix: { on: suffixList.length > 0, count: suffixList.length },
91
+ ack: { on: ackList.length > 0, count: ackList.length },
92
+ deliveryTemplate: { custom: !!(settings.deliveryTemplate || '').trim() },
93
+ attachments: delivery.attachmentsSync ? { synced: delivery.attachmentsSync } : null,
94
+ },
95
+ };
96
+ }