nx-kv 0.28.0 → 0.32.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 (214) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +15 -1
  3. package/assets/kv-get/SKILL.md +3 -1
  4. package/assets/kv-get/references/localget.md +4 -3
  5. package/assets/kv-get/references/timegoal.md +2 -1
  6. package/assets/kv-get/references/wait-workflow.md +44 -14
  7. package/assets/kv-get/references/waitloop.md +6 -4
  8. package/bin/cli.mjs +18 -1
  9. package/package.json +7 -4
  10. package/src/core/atomic-file.js +45 -0
  11. package/src/core/attachmentdb.js +726 -0
  12. package/src/core/attachstore.js +123 -80
  13. package/src/core/config.js +83 -13
  14. package/src/core/db/bootstrap.js +424 -0
  15. package/src/core/db/driver.js +234 -0
  16. package/src/core/db/errors.js +144 -0
  17. package/src/core/db/import-json.js +1224 -0
  18. package/src/core/db/index.js +122 -0
  19. package/src/core/db/migrations/index.js +103 -0
  20. package/src/core/db/migrations/v1.sql +850 -0
  21. package/src/core/db/migrations/v2-data.js +149 -0
  22. package/src/core/db/migrations/v2.sql +89 -0
  23. package/src/core/db/migrator.js +203 -0
  24. package/src/core/db/quiet.js +19 -0
  25. package/src/core/db/seed-templates.js +265 -0
  26. package/src/core/db/settings.js +54 -0
  27. package/src/core/db/time.js +96 -0
  28. package/src/core/db/tx.js +188 -0
  29. package/src/core/db/verify.js +295 -0
  30. package/src/core/db/version.js +59 -0
  31. package/src/core/errors.js +7 -0
  32. package/src/core/instruction-template.js +129 -94
  33. package/src/core/keys.js +21 -20
  34. package/src/core/localatt.js +76 -57
  35. package/src/core/paths.js +39 -2
  36. package/src/core/topic-key.js +43 -0
  37. package/src/core/workflow/project.js +3 -2
  38. package/src/core/workflow/readiness.js +13 -6
  39. package/src/core/workflow/types.js +6 -5
  40. package/src/modules/db/index.js +54 -0
  41. package/src/modules/db/service.js +273 -0
  42. package/src/modules/docs/brief.js +11 -1
  43. package/src/modules/docs/index.js +292 -7
  44. package/src/modules/docs/knowledge.js +8 -1
  45. package/src/modules/docs/paths.js +2 -1
  46. package/src/modules/docs/refs.js +1 -1
  47. package/src/modules/docs/store.js +19 -1
  48. package/src/modules/file/index.js +20 -0
  49. package/src/modules/file/service.js +68 -0
  50. package/src/modules/localtask/deletion.js +14 -10
  51. package/src/modules/localtask/events.js +16 -7
  52. package/src/modules/localtask/index.js +161 -81
  53. package/src/modules/localtask/move-prims.js +68 -38
  54. package/src/modules/localtask/move.js +1 -1
  55. package/src/modules/localtask/panel-presence.js +5 -5
  56. package/src/modules/localtask/paths.js +16 -18
  57. package/src/modules/localtask/repo/goals.js +154 -0
  58. package/src/modules/localtask/repo/index.js +42 -0
  59. package/src/modules/localtask/repo/links.js +136 -0
  60. package/src/modules/localtask/repo/open.js +71 -0
  61. package/src/modules/localtask/repo/presence.js +117 -0
  62. package/src/modules/localtask/repo/rows.js +157 -0
  63. package/src/modules/localtask/repo/settings.js +384 -0
  64. package/src/modules/localtask/repo/snapshot.js +154 -0
  65. package/src/modules/localtask/repo/tasks.js +333 -0
  66. package/src/modules/localtask/repo/topics.js +293 -0
  67. package/src/modules/localtask/service.js +15 -0
  68. package/src/modules/localtask/store/index.js +8 -9
  69. package/src/modules/localtask/store/topic-adapter.js +8 -43
  70. package/src/modules/localtask/store-io.js +19 -161
  71. package/src/modules/localtask/task-lifecycle.js +216 -148
  72. package/src/modules/localtask/task-ops.js +195 -114
  73. package/src/modules/localtask/task-remove.js +151 -79
  74. package/src/modules/localtask/task-templates.js +41 -62
  75. package/src/modules/localtask/task-view.js +165 -151
  76. package/src/modules/localtask/topics.js +89 -80
  77. package/src/modules/localtask/waiters.js +6 -14
  78. package/src/modules/localtask/waiting.js +31 -44
  79. package/src/modules/repos/boards.js +44 -14
  80. package/src/modules/repos/index.js +28 -2
  81. package/src/modules/repos/keys.js +2 -1
  82. package/src/modules/repos/ref.js +6 -6
  83. package/src/modules/repos/repo/index.js +53 -0
  84. package/src/modules/repos/repo/open.js +84 -0
  85. package/src/modules/repos/repo/refs.js +165 -0
  86. package/src/modules/repos/repo/repos.js +177 -0
  87. package/src/modules/repos/repo/rows.js +174 -0
  88. package/src/modules/repos/service.js +375 -130
  89. package/src/modules/repos/transfer.js +43 -14
  90. package/src/modules/tasktool/attach.js +732 -86
  91. package/src/modules/tasktool/delivery-template.js +50 -64
  92. package/src/modules/tasktool/get.js +6 -27
  93. package/src/modules/tasktool/groupctx.js +5 -2
  94. package/src/modules/tasktool/plugins/timegoal-store.js +476 -363
  95. package/src/modules/tasktool/plugins/waitgoal-config.js +1 -1
  96. package/src/modules/tasktool/preview.js +28 -34
  97. package/src/modules/tasktool/system-blocks.js +78 -0
  98. package/src/modules/tasktool/wait.js +113 -125
  99. package/src/modules/templates/index.js +19 -4
  100. package/src/modules/templates/repo/index.js +16 -0
  101. package/src/modules/templates/repo/open.js +65 -0
  102. package/src/modules/templates/repo/templates.js +133 -0
  103. package/src/modules/templates/service.js +130 -119
  104. package/src/runtime/registry.js +2 -1
  105. package/src/shared/prompt-blocks.js +307 -0
  106. package/src/shared/repo-key.js +57 -0
  107. package/src/shared/task-status.js +105 -0
  108. package/src/web/frontend/App.jsx +78 -45
  109. package/src/web/frontend/components/Introduction/docs-modal.jsx +306 -0
  110. package/src/web/frontend/components/Introduction/index.jsx +23 -72
  111. package/src/web/frontend/components/Introduction/style.css +35 -28
  112. package/src/web/frontend/components/board/member-picker.jsx +13 -3
  113. package/src/web/frontend/components/button/index.jsx +91 -0
  114. package/src/web/frontend/components/button/style.css +45 -0
  115. package/src/web/frontend/components/doc/doc-head.jsx +110 -0
  116. package/src/web/frontend/components/layout/breadcrumb.jsx +24 -13
  117. package/src/web/frontend/components/layout/crumbs.js +22 -0
  118. package/src/web/frontend/components/layout/route-crumb.jsx +2 -2
  119. package/src/web/frontend/components/md/attach-area.jsx +307 -0
  120. package/src/web/frontend/components/md/attach-common.js +95 -0
  121. package/src/web/frontend/components/md/attach-modal.jsx +387 -0
  122. package/src/web/frontend/components/md/attach-picker.jsx +274 -0
  123. package/src/web/frontend/components/md/composer-launch.js +68 -0
  124. package/src/web/frontend/components/md/composer-panel.jsx +167 -0
  125. package/src/web/frontend/components/md/md-panes.jsx +337 -46
  126. package/src/web/frontend/components/md/sel-menu.jsx +37 -210
  127. package/src/web/frontend/components/md/task-chain.jsx +2 -5
  128. package/src/web/frontend/components/md/tool-bar.jsx +75 -40
  129. package/src/web/frontend/components/repos/desc-modal.jsx +1 -1
  130. package/src/web/frontend/components/repos/transfer-panel.jsx +4 -0
  131. package/src/web/frontend/components/sidebar/index.jsx +5 -16
  132. package/src/web/frontend/components/sidebar/panel.jsx +2 -0
  133. package/src/web/frontend/components/sidebar/task-children.jsx +11 -1
  134. package/src/web/frontend/modules/board/board-view.js +31 -13
  135. package/src/web/frontend/modules/md/attach-mention.js +48 -0
  136. package/src/web/frontend/modules/md/md-edit-ops.js +24 -0
  137. package/src/web/frontend/modules/md/md-parse.js +40 -10
  138. package/src/web/frontend/modules/md/style.css +283 -39
  139. package/src/web/frontend/modules/md/use-templates.js +3 -1
  140. package/src/web/frontend/modules/prompts/placeholders.js +0 -13
  141. package/src/web/frontend/modules/prompts/prompt-editor.jsx +12 -111
  142. package/src/web/frontend/modules/prompts/style.css +0 -14
  143. package/src/web/frontend/page/dag/index.jsx +3 -1
  144. package/src/web/frontend/page/dir/deleted-panel.jsx +63 -0
  145. package/src/web/frontend/page/dir/index.jsx +137 -4
  146. package/src/web/frontend/page/dir/landing.jsx +136 -8
  147. package/src/web/frontend/page/dir/task.jsx +153 -83
  148. package/src/web/frontend/page/doc/index.jsx +150 -19
  149. package/src/web/frontend/page/group/index.jsx +39 -2
  150. package/src/web/frontend/page/overview/index.jsx +11 -5
  151. package/src/web/frontend/page/refs/index.jsx +122 -0
  152. package/src/web/frontend/page/refs/style.css +41 -0
  153. package/src/web/frontend/page/repos/index.jsx +565 -161
  154. package/src/web/frontend/page/settings/index.jsx +133 -105
  155. package/src/web/frontend/page/settings/prompt-templates-section.jsx +622 -0
  156. package/src/web/frontend/page/settings/style.css +161 -12
  157. package/src/web/frontend/page/settings/task-templates-section.jsx +120 -0
  158. package/src/web/frontend/page/templates/index.jsx +8 -34
  159. package/src/web/frontend/panels.jsx +24 -0
  160. package/src/web/frontend/route-map.js +67 -0
  161. package/src/web/frontend/style-v2.css +45 -19
  162. package/src/web/frontend/style.css +443 -15
  163. package/src/web/frontend/workspace/areas.js +3 -0
  164. package/src/web/frontend/workspace.js +148 -17
  165. package/src/web/public/assets/Introduction-BcPrmROW.css +1 -0
  166. package/src/web/public/assets/Introduction-MAkTZvUX.js +1 -0
  167. package/src/web/public/assets/{attach-v8BxRJ7p.js → attach-Bw0necIf.js} +1 -1
  168. package/src/web/public/assets/{cloud-DMotpyNl.js → cloud-CG_hgVn9.js} +3 -3
  169. package/src/web/public/assets/composer-launch-q1uPzWGo.js +1 -0
  170. package/src/web/public/assets/composer-panel-S2d6A3fG.js +1 -0
  171. package/src/web/public/assets/dag-CwY66RrZ.js +1 -0
  172. package/src/web/public/assets/dir-B_ySdQT1.js +5 -0
  173. package/src/web/public/assets/group-6sWouRDt.js +1 -0
  174. package/src/web/public/assets/index-DKncYqtS.js +54 -0
  175. package/src/web/public/assets/index-DO7b1M3E.css +1 -0
  176. package/src/web/public/assets/{md-edit-ops-BIXUZ5BM.js → md-edit-ops-ZwnwtEax.js} +10 -10
  177. package/src/web/public/assets/md-history-BxbOQtPI.js +1 -0
  178. package/src/web/public/assets/md-panes-Cso2NHbG.js +7 -0
  179. package/src/web/public/assets/member-picker-BpB9ZpWx.js +1 -0
  180. package/src/web/public/assets/overview-Bo8ivqRU.js +1 -0
  181. package/src/web/public/assets/{progress-DRI-n9Gb.js → progress-DPkGjn0P.js} +3 -3
  182. package/src/web/public/assets/refs-CY4i7PoC.css +1 -0
  183. package/src/web/public/assets/refs-CskU6rI7.js +1 -0
  184. package/src/web/public/assets/repos-B_tskNGw.js +9 -0
  185. package/src/web/public/assets/route-crumb-BZ6ffDRj.js +1 -0
  186. package/src/web/public/assets/settings-BMTd_p9Y.js +7 -0
  187. package/src/web/public/assets/settings-qCi-niJC.css +1 -0
  188. package/src/web/public/assets/task-Cs-9RNQn.js +7 -0
  189. package/src/web/public/assets/task-status-Bgo2Nfiw.js +1 -0
  190. package/src/web/public/assets/template-editor-CRxfV218.js +1 -0
  191. package/src/web/public/assets/templates-Apc3JKXa.js +2 -0
  192. package/src/web/public/assets/{upload-F3aoeT7X.js → upload-C83Bwy06.js} +1 -1
  193. package/src/web/public/index.html +4 -3
  194. package/src/core/json-store.js +0 -219
  195. package/src/web/frontend/modules/prompts/template-slots.jsx +0 -87
  196. package/src/web/frontend/page/settings/prompts-section.jsx +0 -531
  197. package/src/web/public/assets/Introduction-9gBNccF6.js +0 -1
  198. package/src/web/public/assets/Introduction-B4k08SH9.css +0 -1
  199. package/src/web/public/assets/dag-B9_B7rnK.js +0 -1
  200. package/src/web/public/assets/dir-DdMpgTHK.js +0 -3
  201. package/src/web/public/assets/group-BF2tfUqG.js +0 -1
  202. package/src/web/public/assets/index-BbAo8n1E.js +0 -50
  203. package/src/web/public/assets/index-DUxHMjZA.css +0 -1
  204. package/src/web/public/assets/md-history-DunAB9Pp.js +0 -5
  205. package/src/web/public/assets/member-picker-CD66NFHl.js +0 -1
  206. package/src/web/public/assets/overview-_Xza9umy.js +0 -1
  207. package/src/web/public/assets/repos-BfbPRMJ0.js +0 -10
  208. package/src/web/public/assets/route-crumb-BHjAXhIY.js +0 -1
  209. package/src/web/public/assets/settings-CVOnFmxp.js +0 -12
  210. package/src/web/public/assets/settings-knWtG9Kc.css +0 -1
  211. package/src/web/public/assets/task-Nw-0PEB4.js +0 -7
  212. package/src/web/public/assets/template-slots-UVa4FnPn.css +0 -1
  213. package/src/web/public/assets/template-slots-bXUEg7EO.js +0 -1
  214. package/src/web/public/assets/templates-cWbR2cCh.js +0 -2
@@ -0,0 +1,65 @@
1
+ // templates 仓储的连接管理(打开 / reset / 事务入口)。
2
+ //
3
+ // 与 repos/repo/open.js 同一模式(T05/T06 定下的形状):
4
+ // - repo 的每个公开函数都经这里的 db()/txw() 拿连接(自动打开库);
5
+ // - templates 域**没有**独立的存储文件(JSON 时代的 templates.json 已消失),
6
+ // 库就是进程共享的那一个 nxkv.db,路径由 NX_KV_DB / NX_KV_HOME 决定;
7
+ // - **无 env 覆盖时必须复用进程内已开的连接**:localtask / repos / config 都
8
+ // 可能先打开了库(各指自己的测试目录),这里再关了重开 = 读路径静默换库
9
+ // (T05 在 repos/repo/open.js 踩过的坑,不要再写一遍)。
10
+ import { rmSync } from 'node:fs';
11
+ import { openStore, getDb, closeDb, isStoreOpen, tx } from '../../../core/db/index.js';
12
+ import { checkNodeVersion } from '../../../core/db/version.js';
13
+
14
+ let openedFor = null;
15
+
16
+ /** 按当前环境解析库路径(每次现取 —— 测试会在用例间改 NX_KV_DB)。 */
17
+ export function resolveTemplatesDb() {
18
+ const path = process.env.NX_KV_DB || undefined;
19
+ return { path, appDir: path ? undefined : undefined, explicit: !!process.env.NX_KV_DB };
20
+ }
21
+
22
+ /** 打开(或复用)连接;env 显式指定了另一个库 → 关旧连接、开新库。 */
23
+ export function openTemplatesStore() {
24
+ const check = checkNodeVersion();
25
+ if (!check.ok) throw new Error(check.message);
26
+ if (isStoreOpen()) {
27
+ const target = resolveTemplatesDb();
28
+ if (!target.explicit || openedFor === target.path) return getDb();
29
+ closeDb();
30
+ }
31
+ const target = resolveTemplatesDb();
32
+ openStore({ path: target.path, importLegacyData: true });
33
+ openedFor = target.path;
34
+ return getDb();
35
+ }
36
+
37
+ /** 当前连接(自动打开)。repo 内部一律用这个。 */
38
+ export function db() {
39
+ return openTemplatesStore();
40
+ }
41
+
42
+ /** 事务入口(自动打开;嵌套自动 SAVEPOINT —— 见 core/db/tx.js)。 */
43
+ export function txw(fn, opts = {}) {
44
+ openTemplatesStore();
45
+ return tx(fn, opts);
46
+ }
47
+
48
+ /**
49
+ * 测试 reset:关连接 + 删库文件。**生产代码不要调**(它会把库清空)。
50
+ */
51
+ export function resetTemplatesStore() {
52
+ const path = process.env.NX_KV_DB;
53
+ closeDb();
54
+ if (!path) return;
55
+ for (const suffix of ['', '-wal', '-shm', '-journal']) {
56
+ try {
57
+ rmSync(path + suffix, { force: true });
58
+ } catch {
59
+ /* Windows 偶发句柄残留:留给下一次 */
60
+ }
61
+ }
62
+ openedFor = null;
63
+ }
64
+
65
+ export { getDb, closeDb, isStoreOpen };
@@ -0,0 +1,133 @@
1
+ // 模板表的窄仓储:一次调用 = 一条(或一小簇)语句。
2
+ //
3
+ // 与 localtask/repos 的 repo 同一纪律:返回纯对象;不存在返回 null(不抛);
4
+ // 写路径经 txw;SQL 只出现在 repo 层。
5
+ //
6
+ // 「默认模板」的落点:schema 的 `is_default` 列(每 category 唯一,由
7
+ // ux_templates_default 部分索引强制)——它就是旧 store 的 defaultId,
8
+ // 一列两用:`WHERE category=:c AND is_default=1` 即 defaultId。
9
+ // (T06 任务书里写的是落 settings 表 `tpl.defaultId`;实际落 is_default 列,
10
+ // 理由见 service.js 头注释的偏差说明。)
11
+ import { db, txw } from './open.js';
12
+
13
+ /** 全部模板行(含禁用;软删的排除)。稳定序:category → sort_order → id。 */
14
+ export function listRows(conn = db(), { category = '' } = {}) {
15
+ const where = category
16
+ ? "WHERE deleted_at IS NULL AND category = :category"
17
+ : 'WHERE deleted_at IS NULL';
18
+ return conn.all(
19
+ `SELECT * FROM templates ${where} ORDER BY category, sort_order, id`,
20
+ category ? { category } : {}
21
+ );
22
+ }
23
+
24
+ /** 按 id 取行(软删的查不到)。 */
25
+ export function getRow(id, conn = db()) {
26
+ return (
27
+ conn.get('SELECT * FROM templates WHERE id = :id AND deleted_at IS NULL', { id: String(id || '') }) ||
28
+ null
29
+ );
30
+ }
31
+
32
+ /** 某类目的默认模板行(没有则 null)。 */
33
+ export function getDefaultRow(category, conn = db()) {
34
+ return (
35
+ conn.get(
36
+ 'SELECT * FROM templates WHERE category = :c AND is_default = 1 AND deleted_at IS NULL LIMIT 1',
37
+ { c: String(category || '') }
38
+ ) || null
39
+ );
40
+ }
41
+
42
+ /**
43
+ * upsert 一行(INSERT OR IGNORE —— **绝不覆盖已有行**:内置模板的出厂 seed 与
44
+ * legacy 导入都走这里,用户改过的 body / vars 不能被任何引导逻辑覆盖)。
45
+ */
46
+ export function insertIfAbsent(conn, row) {
47
+ conn.run(
48
+ `INSERT INTO templates (id, category, name, slot, body, vars_schema, vars, is_default,
49
+ enabled, sort_order, builtin, state, version, deleted_at,
50
+ created_at, updated_at)
51
+ VALUES (:id, :category, :name, :slot, :body, :schema, :vars, :isDefault,
52
+ :enabled, :sort, :builtin, '', 0, NULL, :created, :updated)
53
+ ON CONFLICT(id) DO NOTHING`,
54
+ {
55
+ id: row.id,
56
+ category: row.category || 'newtask',
57
+ name: row.name || row.id,
58
+ slot: row.slot || 'suffix',
59
+ body: row.body,
60
+ schema: rowJson(row.varsSchema, '[]'),
61
+ vars: rowJson(row.vars, '{}'),
62
+ isDefault: row.isDefault ? 1 : 0,
63
+ enabled: row.enabled === 0 ? 0 : 1,
64
+ sort: Number(row.sortOrder) || 0,
65
+ builtin: row.builtin ? 1 : 0,
66
+ created: row.createdAtMs,
67
+ updated: row.updatedAtMs,
68
+ }
69
+ );
70
+ }
71
+
72
+ /** 更新内容列(只动传入的字段)。返回是否存在。 */
73
+ export function updateRow(conn, id, patch, atMs) {
74
+ const sets = [];
75
+ const params = { id: String(id || ''), at: atMs };
76
+ if (patch.name !== undefined) {
77
+ sets.push('name = :name');
78
+ params.name = String(patch.name);
79
+ }
80
+ if (patch.body !== undefined) {
81
+ sets.push('body = :body');
82
+ params.body = String(patch.body);
83
+ }
84
+ if (patch.vars !== undefined) {
85
+ sets.push('vars = :vars');
86
+ params.vars = rowJson(patch.vars);
87
+ }
88
+ if (patch.enabled !== undefined) {
89
+ sets.push('enabled = :enabled');
90
+ params.enabled = patch.enabled ? 1 : 0;
91
+ }
92
+ if (!sets.length) return !!getRow(id, conn);
93
+ sets.push('updated_at = :at');
94
+ const r = conn.run(`UPDATE templates SET ${sets.join(', ')} WHERE id = :id AND deleted_at IS NULL`, params);
95
+ return Number(r.changes) > 0;
96
+ }
97
+
98
+ const rowJson = (v, fallback) => {
99
+ if (v === undefined || v === null) return fallback;
100
+ return typeof v === 'string' ? v : JSON.stringify(v);
101
+ };
102
+
103
+ /**
104
+ * 设某类目的默认模板:先摘掉该类目现默认,再点亮目标。
105
+ * ux_templates_default(每 category 唯一)保证不会出现两个默认。
106
+ */
107
+ export function setDefault(conn, category, id, atMs) {
108
+ conn.run(
109
+ 'UPDATE templates SET is_default = 0, updated_at = :at WHERE category = :c AND is_default = 1',
110
+ { c: String(category || ''), at: atMs }
111
+ );
112
+ conn.run(
113
+ 'UPDATE templates SET is_default = 1, updated_at = :at WHERE id = :id AND deleted_at IS NULL',
114
+ { id: String(id || ''), at: atMs }
115
+ );
116
+ }
117
+
118
+ /** 硬删一行(内置模板不可删是 service 层的规则)。返回是否存在。 */
119
+ export function deleteRow(conn, id) {
120
+ const r = conn.run('DELETE FROM templates WHERE id = :id', { id: String(id || '') });
121
+ return Number(r.changes) > 0;
122
+ }
123
+
124
+ /** 该类目下一个可用的 sort_order(追加到末尾)。 */
125
+ export function nextSortOrder(conn, category) {
126
+ const row = conn.get('SELECT COALESCE(MAX(sort_order), -1) AS m FROM templates WHERE category = :c', {
127
+ c: String(category || ''),
128
+ });
129
+ return Number((row && row.m) || -1) + 1;
130
+ }
131
+
132
+ /** 事务入口的窄转发。 */
133
+ export { txw };
@@ -1,94 +1,86 @@
1
1
  // 任务模板:MD 工作台「新建页」的起始正文。
2
2
  //
3
- // 存 ~/.nx-kv/templates.json(NX_KV_TEMPLATES_STORE 可覆盖,测试隔离)。
4
- // 与本机队列一样是**本机数据**:不进云端、不随工作空间走。内置一条默认模板
5
- // (不可删,可被设为默认的其他模板顶替——删掉的模板若是默认,默认回落到内置)。
3
+ // 存储是 `templates` 表(T06 起进库;templates.json 已消失,legacy 由
4
+ // core/db/import-json 的 importTemplates 迁入 —— values→vars、id 原样)。
5
+ // 与本机队列一样是**本机数据**:不进云端、不随工作空间走。
6
6
  //
7
- // 模板正文是 Markdown,第一行若写 `# 标题`,提交时就是任务标题(与 md-parse
8
- // 的 titleFromMd 约定一致)。内置正文刻意与前端 md-parse 的 NEW_TEMPLATE 保持
9
- // 同构——那是 API 不可达时(版本偏差)前端的兜底,两边谁先改都不破坏行为。
7
+ // 内置模板(`builtin=1`,由 core/db/seed-templates 在开库时 INSERT OR IGNORE
8
+ // seed,永远在场):**不可删,可编辑**。T06 起骨架也可改 —— 用户改了
9
+ // builtin 的 body / 槽位后重启原样保留(seed 是 OR IGNORE,绝不覆盖用户编辑)。
10
+ // 内置正文出厂态仍与前端 md-parse 的 NEW_TEMPLATE 保持同构 —— 那是 API
11
+ // 不可达时(版本偏差)前端的兜底,两边谁先改都不破坏行为。
12
+ //
13
+ // ── 与 schema 列的映射 ────────────────────────────────────────────────
14
+ // 旧 JSON 字段 → 列
15
+ // values(槽位值对象) → vars(JSON;**列名换了**,对外视图仍叫 values ——
16
+ // 调用方与测试一行不改;vars_schema 声明「有哪些变量」,
17
+ // vars 填值,声明里不放默认值)
18
+ // builtin → builtin 列
19
+ // defaultId → 同类目 `is_default=1` 的那行(ux_templates_default
20
+ // 保证每类目最多一个默认;**没有**另落 settings 键 ——
21
+ // 任务书原定 `tpl.defaultId`,实际用 is_default 列:
22
+ // 它就是为这个语义建的列,且部分索引免费给「每类目
23
+ // 唯一」的约束,settings 键反而多出一个无约束的真相源)
24
+ // — → category 固定 'newtask'(本文件只管新建页骨架;
25
+ // delivery/enhance/context 三个 tab 的内置模板由
26
+ // seed 提供,编辑走同一张表)
10
27
  import crypto from 'node:crypto';
11
- import fsp from 'node:fs/promises'; // 仅用于读用户 --body-file(store 读写已走 json-store)
28
+ import fsp from 'node:fs/promises'; // 仅用于读用户 --body-file(存储已进库)
12
29
  import { readFileSync } from 'node:fs';
13
- import { join } from 'node:path';
14
- import { APP_DIR } from '../../core/paths.js';
15
30
  import { badInput, notFound } from '../../core/errors.js';
16
- import { createJsonStore } from '../../core/json-store.js';
31
+ import { nowMs } from '../../core/db/time.js';
32
+ import { NEWTASK_BODY, NEWTASK_VARS } from '../../core/db/seed-templates.js';
33
+ import repoLayer from './repo/index.js';
17
34
 
18
35
  export const BUILTIN_ID = 'default';
36
+ const NEWTASK_CATEGORY = 'newtask';
19
37
 
20
- // 与前端 md-parse.js 的 NEW_TEMPLATE 保持同构(见文件头注释)。
21
- //
22
- // 正文里的 {{占位符}} 是**模板的槽位**:骨架(章节结构)固定不可改,用户只填
23
- // 槽位里的文字(设置面板「提示词 / 模板」一栏 / template update --values)。
24
- // 槽位默认文字放在 BUILTIN_VALUES——渲染时用它填回,于是「不填也能用」。
25
- const BUILTIN_BODY = `## 背景
26
-
27
- {{背景}}
28
-
29
- ## 验收
30
- - [ ] {{验收}}
31
-
32
- ## 约束
33
- - {{约束}}
34
-
35
- ## 附件
36
- `;
37
-
38
- // 内置模板各槽位的默认文字(渲染时的兜底:没填就显示这些)。
39
- export const BUILTIN_VALUES = {
40
- 背景: '(一句话说清要改什么)',
41
- 验收: '…',
42
- 约束: '…',
43
- 附件: '',
44
- };
45
-
46
- const builtin = () => ({
47
- id: BUILTIN_ID,
48
- name: '默认模板',
49
- body: BUILTIN_BODY,
50
- values: { ...BUILTIN_VALUES },
51
- builtin: true,
52
- });
53
-
54
- export function storePath() {
55
- return process.env.NX_KV_TEMPLATES_STORE || join(APP_DIR, 'templates.json');
56
- }
38
+ const repo = repoLayer;
57
39
 
58
- function emptyStore() {
59
- return { version: 1, defaultId: BUILTIN_ID, templates: [builtin()] };
60
- }
40
+ export const BUILTIN_BODY = NEWTASK_BODY;
41
+ export const BUILTIN_VALUES = { ...NEWTASK_VARS };
61
42
 
62
- // 原子写 / 串行队列 / 锁退避收口到 core/json-store.js(任务 #66)。
63
- // 语义:缺失/损坏 → 出厂态(内置模板兜底);templates 不是数组(形状不认识)→ 出厂态。
64
- function normalizeRawStore(data) {
65
- if (!data || !Array.isArray(data.templates)) return null;
66
- // 内置模板永远在场(被旧版本 store 漏掉时补回);builtin 标记以代码为准
67
- const templates = data.templates.filter((t) => t && t.id && !t.builtin);
68
- templates.unshift(builtin());
69
- let defaultId = typeof data.defaultId === 'string' ? data.defaultId : BUILTIN_ID;
70
- if (!templates.some((t) => t.id === defaultId)) defaultId = BUILTIN_ID;
71
- return { version: 1, defaultId, templates };
72
- }
43
+ // ─── 视图:行 ⇄ 旧 JSON 形状(调用方消费的是 values/builtin 这些旧字段)──
73
44
 
74
- const store = createJsonStore({
75
- path: storePath,
76
- empty: emptyStore,
77
- normalize: normalizeRawStore,
78
- });
45
+ /** 行 → 旧 store 形状的模板对象(vars 列对外仍叫 values,契约不变)。 */
46
+ function rowToView(row) {
47
+ const vars = safeParse(row.vars, {});
48
+ const out = {
49
+ id: String(row.id),
50
+ name: String(row.name || ''),
51
+ body: String(row.body || ''),
52
+ values: vars,
53
+ builtin: !!row.builtin,
54
+ };
55
+ if (row.category && row.category !== NEWTASK_CATEGORY) out.category = String(row.category);
56
+ if (row.enabled === 0) out.enabled = false;
57
+ return out;
58
+ }
79
59
 
80
- async function loadStore() {
81
- return store.load();
60
+ function safeParse(text, fallback) {
61
+ try {
62
+ const v = JSON.parse(String(text ?? ''));
63
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : fallback;
64
+ } catch {
65
+ return fallback;
66
+ }
82
67
  }
83
68
 
84
- function saveStore(data) {
85
- return store.save(data);
69
+ function defaultIdOf(conn) {
70
+ const row = repo.templates.getDefaultRow(NEWTASK_CATEGORY, conn);
71
+ return row ? String(row.id) : BUILTIN_ID;
86
72
  }
87
73
 
88
74
  /** 列表视图:templates + defaultId(面板「新建页」按 defaultId 取起始正文) */
89
75
  export async function listTemplates() {
90
- const store = await loadStore();
91
- return { defaultId: store.defaultId, templates: store.templates };
76
+ return repo.txw((conn) => {
77
+ const defaultId = defaultIdOf(conn);
78
+ const templates = repo.templates
79
+ .listRows(conn)
80
+ .filter((r) => r.category === NEWTASK_CATEGORY)
81
+ .map(rowToView);
82
+ return { defaultId, templates };
83
+ });
92
84
  }
93
85
 
94
86
  function normalizeName(raw) {
@@ -152,18 +144,38 @@ async function resolveBody({ body, bodyFile } = {}) {
152
144
  export async function addTemplate({ name: rawName, body: rawBody, bodyFile, values, setDefault = false } = {}) {
153
145
  const name = normalizeName(rawName);
154
146
  const body = normalizeBody(await resolveBody({ body: rawBody, bodyFile }));
155
- const store = await loadStore();
156
- const t = {
157
- id: 't_' + crypto.randomBytes(5).toString('hex'),
158
- name,
159
- body,
160
- // 槽位值:正文里 {{名字}} 处填的文字;未给的槽位按正文里的原样渲染
161
- values: normalizeValues(values),
162
- };
163
- store.templates.push(t);
164
- if (setDefault) store.defaultId = t.id;
165
- await saveStore(store);
166
- return { status: 'ok', template: t, defaultId: store.defaultId };
147
+ const at = nowMs();
148
+ return repo.txw((conn) => {
149
+ const t = {
150
+ id: 't_' + crypto.randomBytes(5).toString('hex'),
151
+ name,
152
+ body,
153
+ // 槽位值:正文里 {{名字}} 处填的文字;未给的槽位按正文里的原样渲染
154
+ values: normalizeValues(values),
155
+ };
156
+ repo.templates.insertIfAbsent(conn, {
157
+ id: t.id,
158
+ category: NEWTASK_CATEGORY,
159
+ name: t.name,
160
+ body: t.body,
161
+ varsSchema: [],
162
+ vars: t.values,
163
+ isDefault: 0,
164
+ sortOrder: repo.templates.nextSortOrder(conn, NEWTASK_CATEGORY),
165
+ builtin: 0,
166
+ createdAtMs: at,
167
+ updatedAtMs: at,
168
+ });
169
+ const defaultId = setDefault
170
+ ? t.id
171
+ : String((repo.templates.getDefaultRow(NEWTASK_CATEGORY, conn) || {}).id || BUILTIN_ID);
172
+ if (setDefault) repo.templates.setDefault(conn, NEWTASK_CATEGORY, t.id, at);
173
+ return {
174
+ status: 'ok',
175
+ template: rowToView(repo.templates.getRow(t.id, conn)),
176
+ defaultId,
177
+ };
178
+ });
167
179
  }
168
180
 
169
181
  /** 删除模板。内置模板不可删(它是「删光后」的兜底);删默认则默认回落到内置。 */
@@ -171,51 +183,50 @@ export async function removeTemplate({ id } = {}) {
171
183
  const want = String(id || '').trim();
172
184
  if (!want) throw badInput('需要模板 id');
173
185
  if (want === BUILTIN_ID) throw badInput('内置默认模板不可删除(可新增自己的模板并设为默认)');
174
- const store = await loadStore();
175
- const idx = store.templates.findIndex((t) => t.id === want);
176
- if (idx < 0) throw notFound(`没有 id 为 ${want} 的模板(template list 可查)`);
177
- const [removed] = store.templates.splice(idx, 1);
178
- const wasDefault = store.defaultId === want;
179
- if (wasDefault) store.defaultId = BUILTIN_ID;
180
- await saveStore(store);
181
- return { status: 'ok', removed, wasDefault, defaultId: store.defaultId };
186
+ return repo.txw((conn) => {
187
+ const row = repo.templates.getRow(want, conn);
188
+ if (!row) throw notFound(`没有 id 为 ${want} 的模板(template list 可查)`);
189
+ const removed = rowToView(row);
190
+ const wasDefault = Number(row.is_default) === 1;
191
+ repo.templates.deleteRow(conn, want);
192
+ // 删掉的是默认 → 默认回落到内置(把 is_default 也点亮回去,保持
193
+ // 「每类目恰一个默认」的不变量;与 JSON 时代同一行为)
194
+ if (wasDefault) repo.templates.setDefault(conn, NEWTASK_CATEGORY, BUILTIN_ID, nowMs());
195
+ const defaultId = wasDefault
196
+ ? BUILTIN_ID
197
+ : String((repo.templates.getDefaultRow(NEWTASK_CATEGORY, conn) || {}).id || BUILTIN_ID);
198
+ return { status: 'ok', removed, wasDefault, defaultId };
199
+ });
182
200
  }
183
201
 
184
- /** 编辑模板(改名 / 改正文;只改传入的字段)。内置模板不可编辑——它是「删光后」的兜底。 */
202
+ /** 编辑模板(改名 / 改正文 / 改槽位;只改传入的字段)。 */
185
203
  export async function updateTemplate({ id, name: rawName, body: rawBody, bodyFile, values } = {}) {
186
204
  const want = String(id || '').trim();
187
205
  if (!want) throw badInput('需要模板 id');
188
- const store = await loadStore();
189
- const t = store.templates.find((x) => x.id === want);
190
- if (!t) throw notFound(`没有 id 为 ${want} 的模板(template list 可查)`);
191
- // 内置模板:**骨架不可改**(它是「删光后」的兜底),但槽位值可填——
192
- // 用户要改的从来是「背景/验收」里写什么,不是章节结构本身。
193
- if (want === BUILTIN_ID) {
194
- if (rawName !== undefined || rawBody !== undefined || bodyFile) {
195
- throw badInput('内置默认模板的骨架不可改(可改槽位内容:template update default --values)');
206
+ const bodyIn = rawBody !== undefined || bodyFile ? await resolveBody({ body: rawBody, bodyFile }) : undefined;
207
+ return repo.txw((conn) => {
208
+ const row = repo.templates.getRow(want, conn);
209
+ if (!row) throw notFound(`没有 id 为 ${want} 的模板(template list 可查)`);
210
+ const patch = {};
211
+ if (rawName !== undefined) patch.name = normalizeName(rawName);
212
+ if (bodyIn !== undefined) patch.body = normalizeBody(bodyIn);
213
+ if (values !== undefined) {
214
+ // 内置模板:槽位未给的项回落出厂默认(渲染时的兜底语义与 JSON 时代一致)
215
+ patch.vars = normalizeValues(values, row.builtin ? BUILTIN_VALUES : rowToView(row).values);
196
216
  }
197
- if (values === undefined) throw badInput('内置模板只能改槽位内容(--values)');
198
- t.values = normalizeValues(values, BUILTIN_VALUES);
199
- await saveStore(store);
200
- return { status: 'ok', template: t };
201
- }
202
- if (rawName !== undefined) t.name = normalizeName(rawName);
203
- if (rawBody !== undefined || bodyFile) {
204
- t.body = normalizeBody(await resolveBody({ body: rawBody, bodyFile }));
205
- }
206
- if (values !== undefined) t.values = normalizeValues(values, t.values);
207
- await saveStore(store);
208
- return { status: 'ok', template: t };
217
+ repo.templates.updateRow(conn, want, patch, nowMs());
218
+ return { status: 'ok', template: rowToView(repo.templates.getRow(want, conn)) };
219
+ });
209
220
  }
210
221
 
211
222
  /** 设默认模板:新建页的起始正文换成它。 */
212
223
  export async function setDefaultTemplate({ id } = {}) {
213
224
  const want = String(id || '').trim();
214
225
  if (!want) throw badInput('需要模板 id');
215
- const store = await loadStore();
216
- const t = store.templates.find((x) => x.id === want);
217
- if (!t) throw notFound(`没有 id 为 ${want} 的模板(template list 可查)`);
218
- store.defaultId = want;
219
- await saveStore(store);
220
- return { status: 'ok', defaultId: store.defaultId, template: t };
226
+ return repo.txw((conn) => {
227
+ const row = repo.templates.getRow(want, conn);
228
+ if (!row) throw notFound(`没有 id 为 ${want} 的模板(template list 可查)`);
229
+ repo.templates.setDefault(conn, NEWTASK_CATEGORY, want, nowMs());
230
+ return { status: 'ok', defaultId: want, template: rowToView(repo.templates.getRow(want, conn)) };
231
+ });
221
232
  }
@@ -27,10 +27,11 @@ import docs from '../modules/docs/index.js';
27
27
  import file from '../modules/file/index.js';
28
28
  import templates from '../modules/templates/index.js';
29
29
  import bundled from '../modules/bundled/index.js';
30
+ import db from '../modules/db/index.js';
30
31
 
31
32
  // 工作空间(group)已于 2026-10-23 并入 todo 模块:它是**清单的设置**,
32
33
  // 不该单独占一个模块/一个 tab。命令与路由一字未改。
33
- export const MODULES = [system, setting, auth, localtask, tasktool, todo, repos, docs, file, templates, bundled].sort(
34
+ export const MODULES = [system, setting, auth, localtask, tasktool, todo, repos, docs, file, templates, bundled, db].sort(
34
35
  (a, b) => (a.order ?? 100) - (b.order ?? 100)
35
36
  );
36
37