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
@@ -1,22 +1,22 @@
1
- // 附件的「本地镜像」:把某个用户空间(group)里的附件落到本机,
2
- // 好让 agent **直接读本地文件**,不再依赖网络与出图地址。
1
+ // 云端附件的「本地镜像」:把某个用户空间(group)里的附件落到本机,
2
+ // 好让 agent 直接读本地文件,不再依赖网络与出图地址。
3
3
  //
4
- // 目录(刻意落在 nx-kv 的用户目录下):
4
+ // 目录:
5
5
  // ~/.nx-kv/attachments/<groupId|default>/ ← NX_KV_ATTACHMENTS 可改根目录
6
- // 台账:
7
- // 同目录 manifest.json → { groupId, dir, updatedAt, files: { <fileId>: {name, size, contentType, syncedAt} } }
8
6
  //
9
- // 为什么需要台账:后端 FileInfoRes **不回传原始文件名**,本地落点只能自己定;
10
- // 台账把「fileId → 本地文件名 + 大小」固定下来,于是反复同步能跳过未变更的,
11
- // 也不会每 sync 一次就换一个名字(那样等于每次重新下载)。
7
+ // 元数据(schema v2 起):**唯一真相在 attachments 表**(kind='file', storage='cloud',
8
+ // group_id=<groupId>)。旧的 manifest.json 只在 v1→v2 迁移时读一次,之后归档。
9
+ //
10
+ // 为什么早先需要台账:后端 FileInfoRes 不回传原始文件名,本地落点只能自己定。
11
+ // 现在 attachments.name / local_path 承担同一职责,且能与任务/文档关系 JOIN。
12
12
  import fsp from 'node:fs/promises';
13
13
  import { existsSync } from 'node:fs';
14
14
  import { dirname, extname, join, parse as parsePath, resolve } from 'node:path';
15
15
  import { attachmentsRootFromEnv } from './paths.js';
16
16
  import { normalizeGroupId } from './config.js';
17
17
  import { downloadFile, listAllFiles } from './fileapi.js';
18
-
19
- export const MANIFEST_NAME = 'manifest.json';
18
+ import { getDb } from './db/index.js';
19
+ import { upsertFileAttachment } from './attachmentdb.js';
20
20
 
21
21
  const nowIso = () => new Date().toISOString();
22
22
 
@@ -27,33 +27,6 @@ export function localDirFor(groupId, override = '') {
27
27
  return join(attachmentsRootFromEnv(), n === undefined ? 'default' : String(n));
28
28
  }
29
29
 
30
- export function manifestPath(dir) {
31
- return join(dir, MANIFEST_NAME);
32
- }
33
-
34
- export async function readManifest(dir) {
35
- try {
36
- const raw = JSON.parse(await fsp.readFile(manifestPath(dir), 'utf8'));
37
- return {
38
- groupId: Number(raw.groupId) || 0,
39
- dir: String(raw.dir || dir),
40
- updatedAt: String(raw.updatedAt || ''),
41
- files: raw.files && typeof raw.files === 'object' ? raw.files : {},
42
- };
43
- } catch {
44
- // 台账不存在或损坏:当成空台账。它只是缓存,不是真相源 —— 真相源是后端。
45
- return { groupId: 0, dir, updatedAt: '', files: {} };
46
- }
47
- }
48
-
49
- export async function writeManifest(dir, data) {
50
- await fsp.mkdir(dir, { recursive: true });
51
- const tmp = manifestPath(dir) + '.tmp';
52
- await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');
53
- await fsp.rename(tmp, manifestPath(dir));
54
- return data;
55
- }
56
-
57
30
  // Windows 保留设备名做文件名会让文件无法访问
58
31
  const RESERVED = new Set([
59
32
  'con', 'prn', 'aux', 'nul',
@@ -90,7 +63,6 @@ const EXT_BY_TYPE = {
90
63
  /**
91
64
  * 本地落点文件名。优先用调用方给的「人读名字」(任务里 markdown 的说明/链接文字),
92
65
  * 否则退回 fileId;两者都没有扩展名时,再按 fileId 自带后缀 / Content-Type 补一个。
93
- * 补后缀是刚需:没有扩展名,Windows 上双击打不开、内联预览也认不出类型。
94
66
  */
95
67
  export function localNameFor(fileId, preferred, contentType = '') {
96
68
  let base = safeFileName(preferred || fileId);
@@ -102,7 +74,7 @@ export function localNameFor(fileId, preferred, contentType = '') {
102
74
  return base;
103
75
  }
104
76
 
105
- /** 同目录内不重名的落点(`名字 (2).ext`)。files 是 id → 台账记录。 */
77
+ /** 同目录内不重名的落点(`名字 (2).ext`)。files 是 id → 记录。 */
106
78
  function uniqueName(files, name, selfId) {
107
79
  const taken = new Set(
108
80
  Object.entries(files)
@@ -120,29 +92,71 @@ function uniqueName(files, name, selfId) {
120
92
  return candidate;
121
93
  }
122
94
 
95
+ function groupRows(groupId) {
96
+ const gid = normalizeGroupId(groupId);
97
+ return getDb().all(
98
+ `SELECT id, name, local_path, mime, size, meta
99
+ FROM attachments
100
+ WHERE kind = 'file' AND storage = 'cloud' AND group_id = :g AND deleted_at IS NULL
101
+ ORDER BY id`,
102
+ { g: gid === undefined ? 0 : Number(gid) }
103
+ );
104
+ }
105
+
106
+ function recordOf(row) {
107
+ let meta = {};
108
+ try {
109
+ meta = JSON.parse(String(row.meta || '{}')) || {};
110
+ } catch {
111
+ meta = {};
112
+ }
113
+ return {
114
+ name: String(row.name || ''),
115
+ local_path: String(row.local_path || ''),
116
+ size: Number(row.size) || 0,
117
+ contentType: String(row.mime || ''),
118
+ syncedAt: String(meta.syncedAt || ''),
119
+ };
120
+ }
121
+
122
+ function absOf(rec, dir) {
123
+ if (rec.local_path && existsSync(rec.local_path)) return rec.local_path;
124
+ return rec.name ? join(dir, rec.name) : '';
125
+ }
126
+
127
+ /** 只在**当前目录内**找已落盘副本:同步用这个判断「这个根下是否需要下载」。 */
128
+ function absInDir(rec, dir) {
129
+ const p = absOf(rec, dir);
130
+ if (!p) return '';
131
+ return dirname(resolve(p)) === resolve(dir) ? p : '';
132
+ }
133
+
123
134
  /**
124
- * 读台账 + 落盘文件,判断某个附件是否**已经在本地且内容未变**。
135
+ * 读 DB + 落盘文件,判断某个附件是否已经在本地且内容未变。
125
136
  * 返回绝对路径;没同步过(或本地文件被删了)返回 null。
126
137
  */
127
138
  export async function resolveLocal(groupId, fileId, overrideDir = '') {
139
+ const gid = normalizeGroupId(groupId);
128
140
  const dir = localDirFor(groupId, overrideDir);
129
- const man = await readManifest(dir);
130
- const rec = man.files[fileId];
131
- if (!rec || !rec.name) return null;
132
- const abs = join(dir, String(rec.name));
133
- return existsSync(abs) ? { path: abs, name: String(rec.name), size: Number(rec.size) || 0 } : null;
141
+ const row = getDb().get(
142
+ `SELECT id, name, local_path, mime, size, meta FROM attachments
143
+ WHERE id = :id AND kind = 'file' AND storage = 'cloud' AND group_id = :g AND deleted_at IS NULL`,
144
+ { id: String(fileId || ''), g: gid === undefined ? 0 : Number(gid) }
145
+ );
146
+ if (!row) return null;
147
+ const rec = recordOf(row);
148
+ const abs = absOf(rec, dir);
149
+ return abs && existsSync(abs) ? { path: abs, name: rec.name, size: rec.size } : null;
134
150
  }
135
151
 
136
- /** 该目录下已同步的全部条目(id → {path,name,size}),供 `todo attachments` 批量标注用。 */
152
+ /** 该目录下已同步的全部条目(id → {path,name,size}),供批量标注用。 */
137
153
  export async function localIndex(groupId, overrideDir = '') {
138
154
  const dir = localDirFor(groupId, overrideDir);
139
- const man = await readManifest(dir);
140
155
  const out = new Map();
141
- for (const [id, rec] of Object.entries(man.files)) {
142
- const abs = join(dir, String(rec?.name || ''));
143
- if (rec?.name && existsSync(abs)) {
144
- out.set(id, { path: abs, name: String(rec.name), size: Number(rec.size) || 0 });
145
- }
156
+ for (const row of groupRows(groupId)) {
157
+ const rec = recordOf(row);
158
+ const abs = absOf(rec, dir);
159
+ if (abs && existsSync(abs)) out.set(row.id, { path: abs, name: rec.name, size: rec.size });
146
160
  }
147
161
  return { dir, index: out };
148
162
  }
@@ -150,13 +164,12 @@ export async function localIndex(groupId, overrideDir = '') {
150
164
  /**
151
165
  * 同步附件到本地。
152
166
  *
153
- * - `ids` 为空 → 同步该 group 的**全部**附件(`file sync` 的默认语义)
167
+ * - `ids` 为空 → 同步该 group 的全部附件(`file sync` 的默认语义)
154
168
  * - `ids` 非空 → 只同步这些 id(读任务时按引用同步走这条)
155
169
  * - `names` → fileId 的人读文件名(来自任务里 markdown 的说明文字)
156
- * - `prune` → 删掉本地已不在后端的文件(**仅在 sync-all 时生效**:
157
- * 带了 ids 过滤还 prune,会把没列出来的附件一起删掉)
170
+ * - `prune` → 删掉本地已不在后端的文件(仅在 sync-all 时生效)
158
171
  *
159
- * 单个文件下载失败**不中断整体**:如实记进 failures 让调用方知道哪些没拿到。
172
+ * 单个文件下载失败不中断整体:如实记进 failures 让调用方知道哪些没拿到。
160
173
  */
161
174
  export async function syncAttachments({
162
175
  groupId,
@@ -167,8 +180,9 @@ export async function syncAttachments({
167
180
  dryRun = false,
168
181
  } = {}) {
169
182
  const dir = localDirFor(groupId, overrideDir);
170
- const man = await readManifest(dir);
171
- const files = { ...man.files };
183
+ const db = getDb();
184
+ const files = {};
185
+ for (const row of groupRows(groupId)) files[row.id] = recordOf(row);
172
186
 
173
187
  const remote = await listAllFiles({ groupId });
174
188
  const wanted = Array.isArray(ids) && ids.length ? new Set(ids.map(String)) : null;
@@ -188,13 +202,15 @@ export async function syncAttachments({
188
202
 
189
203
  const desired = localNameFor(id, names[id], meta.contentType);
190
204
  const prev = files[id];
191
- const prevAbs = prev?.name ? join(dir, String(prev.name)) : '';
205
+ // 换根(attachmentsDir / NX_KV_ATTACHMENTS)后旧绝对路径不算数:
206
+ // 必须在新目录里重新落一份,否则看起来像「没下载」。
207
+ const prevAbs = prev ? absInDir(prev, dir) : '';
192
208
  const sizeKnown = Number(prev?.size) > 0;
193
209
  const unchanged = prevAbs && existsSync(prevAbs) && sizeKnown && Number(prev.size) === Number(meta.size);
194
210
 
195
211
  if (unchanged) {
196
212
  skipped++;
197
- entries.push({ id, name: String(prev.name), path: prevAbs, size: Number(prev.size), contentType: meta.contentType, synced: true });
213
+ entries.push({ id, name: prev.name, path: prevAbs, size: Number(prev.size), contentType: meta.contentType, synced: true });
198
214
  continue;
199
215
  }
200
216
  if (dryRun) {
@@ -207,9 +223,8 @@ export async function syncAttachments({
207
223
  buf = await downloadFile(id);
208
224
  } catch (e) {
209
225
  failures.push({ id, error: String((e && e.message) || e) });
210
- // 本地已有旧版本就继续用它,避免「网络抖一下附件就消失」
211
226
  if (prevAbs && existsSync(prevAbs)) {
212
- entries.push({ id, name: String(prev.name), path: prevAbs, size: Number(prev.size), contentType: meta.contentType, synced: true, stale: true });
227
+ entries.push({ id, name: prev.name, path: prevAbs, size: Number(prev.size), contentType: meta.contentType, synced: true, stale: true });
213
228
  }
214
229
  continue;
215
230
  }
@@ -223,36 +238,64 @@ export async function syncAttachments({
223
238
  failures.push({ id, error: String((e && e.message) || e) });
224
239
  continue;
225
240
  }
226
- files[id] = { name, size: buf.length, contentType: meta.contentType, syncedAt: nowIso() };
241
+ files[id] = { name, local_path: abs, size: buf.length, contentType: meta.contentType, syncedAt: nowIso() };
242
+ upsertFileAttachment(db, {
243
+ id,
244
+ name,
245
+ localPath: abs,
246
+ mime: meta.contentType,
247
+ size: buf.length,
248
+ storage: 'cloud',
249
+ groupId: normalizeGroupId(groupId) || 0,
250
+ meta: { syncedAt: nowIso(), contentType: meta.contentType },
251
+ });
227
252
  downloaded++;
228
253
  entries.push({ id, name, path: abs, size: buf.length, contentType: meta.contentType, synced: true });
229
254
  }
230
255
 
231
- // prune:只在同步全部时生效(理由见函数头)
256
+ // prune:只在同步全部时生效(理由见函数头)。被任务/文档引用过的行不删,
257
+ // 只清本地缓存并保留元数据——否则 CASCADE 会把关系边一起删掉。
232
258
  const removed = [];
233
259
  if (prune && !wanted && !dryRun) {
260
+ const gid = normalizeGroupId(groupId);
234
261
  for (const id of Object.keys(files)) {
235
262
  if (remoteIds.has(id)) continue;
236
- const abs = join(dir, String(files[id]?.name || ''));
237
- try {
238
- if (existsSync(abs)) await fsp.unlink(abs);
239
- } catch {
240
- // 删不掉就留着(可能被占用);台账条目仍移除,下次同步不会误认它是最新的
263
+ const rec = files[id];
264
+ const abs = absOf(rec, dir);
265
+ if (abs) {
266
+ try {
267
+ if (existsSync(abs)) await fsp.unlink(abs);
268
+ } catch {
269
+ /* 删不掉就留着 */
270
+ }
271
+ }
272
+ removed.push(rec.name || id);
273
+ const linked = db.get(
274
+ `SELECT 1 AS x FROM task_attach WHERE attachment_id = :id
275
+ UNION ALL SELECT 1 FROM ref_attach WHERE attachment_id = :id LIMIT 1`,
276
+ { id }
277
+ );
278
+ if (linked) {
279
+ db.run(
280
+ `UPDATE attachments SET local_path = '', size = 0, meta = :meta, updated_at = :at
281
+ WHERE id = :id AND kind = 'file' AND storage = 'cloud' AND group_id = :g`,
282
+ {
283
+ id,
284
+ g: gid === undefined ? 0 : Number(gid),
285
+ meta: JSON.stringify({ syncedAt: rec.syncedAt, remoteDeleted: true }),
286
+ at: Date.now(),
287
+ }
288
+ );
289
+ } else {
290
+ db.run(
291
+ `DELETE FROM attachments
292
+ WHERE id = :id AND kind = 'file' AND storage = 'cloud' AND group_id = :g AND deleted_at IS NULL`,
293
+ { id, g: gid === undefined ? 0 : Number(gid) }
294
+ );
241
295
  }
242
- removed.push(files[id]?.name || id);
243
- delete files[id];
244
296
  }
245
297
  }
246
298
 
247
- if (!dryRun) {
248
- await writeManifest(dir, {
249
- groupId: normalizeGroupId(groupId) || 0,
250
- dir,
251
- updatedAt: nowIso(),
252
- files,
253
- });
254
- }
255
-
256
299
  return {
257
300
  dir,
258
301
  groupId: normalizeGroupId(groupId) || 0,
@@ -1,11 +1,34 @@
1
- // 本机配置:后端地址 + 登录态。
1
+ // 本机配置:凭据留文件(config.json),偏好进库(settings 表)。
2
2
  //
3
- // 与业务数据(KV 清单)分开存放:清单在服务端,这里只存「怎么连过去」。
4
- // 复用 store.js 的原子写语义,但结构独立——配置是单例,不是集合。
3
+ // ── 拆分(D4 裁决)─────────────────────────────────────────────────────
4
+ //
5
+ // 进库(settings 表,`app.*` 键,value 是 JSON 文本):
6
+ // autoSyncAttachments / attachmentsDir / gitRepoRoot / gitDevRoot
7
+ // —— 业务配置,与数据同生命周期(备份 / VACUUM INTO 跟着库走)。
8
+ // localtask 的 5 个键(lt.*)T03 已进库,见 localtask/repo/settings.js。
9
+ //
10
+ // 留文件(config.json,**精确 5 个字段**):
11
+ // baseUrl / token / email / userId / groupId
12
+ // —— 凭据与会话身份。**绝不进库**:库会被 `VACUUM INTO` 备份、被
13
+ // `db inspect` dump、被人拷走排障,凭据一旦进库就跟着这些通道扩散。
14
+ //
15
+ // `loadConfig()` / `saveConfig()` / `updateConfig()` 的签名与返回形状**完全不变**
16
+ // —— 内部拼「文件 5 项 + settings 表」再 normalize 一次返回,调用方零感知。
17
+ //
18
+ // 白名单纪律(#82 的教训):CREDENTIAL_KEYS / PREF_KEYS **显式枚举**每个字段。
19
+ // 不在白名单里的字段,两边都不写 —— 新增配置项必须同时在 normalize 与对应
20
+ // 白名单里登记,漏一处就是「设置了但下次启动丢掉」。
21
+ //
22
+ // settings 读取**不做长缓存**:单条 SELECT 是微秒级,缓存只会带来
23
+ // 「serve 改了设置、CLI 读到过期值」这类最难查的跨进程过期。
5
24
  import fsp from 'node:fs/promises';
6
25
  import { dirname, join } from 'node:path';
7
26
  import { homedir } from 'node:os';
8
27
  import { badInput } from './errors.js';
28
+ import { readSettingRaw, writeSettingRaw } from './db/settings.js';
29
+ import { tx } from './db/tx.js';
30
+ import { openStore } from './db/index.js';
31
+ import { nowMs } from './db/time.js';
9
32
 
10
33
  export const CONFIG_PATH = join(homedir(), '.nx-kv', 'config.json');
11
34
 
@@ -16,6 +39,17 @@ export function configPathFromEnv() {
16
39
 
17
40
  export const DEFAULT_BASE_URL = 'http://192.0.2.47:8988';
18
41
 
42
+ // ── 显式白名单(#82 的教训:不列出的字段两边都不写)────────────────────
43
+
44
+ /** 留在 config.json 的字段(凭据 + 会话身份)。config.json 的键集合精确等于它。 */
45
+ export const CREDENTIAL_KEYS = Object.freeze(['baseUrl', 'token', 'email', 'userId', 'groupId']);
46
+
47
+ /** 进 settings 表(`app.*` 前缀)的偏好字段。 */
48
+ export const PREF_KEYS = Object.freeze(['autoSyncAttachments', 'attachmentsDir', 'gitRepoRoot', 'gitDevRoot']);
49
+
50
+ /** settings 表里偏好字段的键名。 */
51
+ export const APP_SETTING_KEYS = Object.freeze(PREF_KEYS.map((k) => 'app.' + k));
52
+
19
53
  const EMPTY = () => ({
20
54
  baseUrl: process.env.NX_KV_BASE_URL || DEFAULT_BASE_URL,
21
55
  token: '',
@@ -39,6 +73,7 @@ const EMPTY = () => ({
39
73
  let cache = null;
40
74
  let cacheMtime = -1;
41
75
 
76
+ /** 全量归一(文件 5 项 + settings 偏好合并后跑一次,保证形状与类型稳定)。 */
42
77
  function normalize(data) {
43
78
  const base = EMPTY();
44
79
  if (!data || typeof data !== 'object') return base;
@@ -55,36 +90,71 @@ function normalize(data) {
55
90
  };
56
91
  }
57
92
 
93
+ /** 从 settings 表读偏好(每次现读 —— 不缓存,跨进程改设置立刻可见)。 */
94
+ function readPrefs() {
95
+ const db = openStore();
96
+ const prefs = {};
97
+ for (const key of APP_SETTING_KEYS) {
98
+ const v = readSettingRaw(db, key);
99
+ if (v !== undefined) prefs[key.slice('app.'.length)] = v;
100
+ }
101
+ return prefs;
102
+ }
103
+
104
+ /** 把偏好写进 settings 表(一个事务;只写白名单里的字段)。 */
105
+ function writePrefs(next) {
106
+ const at = nowMs();
107
+ tx(
108
+ (conn) => {
109
+ for (const k of PREF_KEYS) {
110
+ if (next[k] === undefined) continue;
111
+ writeSettingRaw(conn, 'app.' + k, next[k], at);
112
+ }
113
+ },
114
+ { db: openStore(), mode: 'IMMEDIATE' }
115
+ );
116
+ }
117
+
58
118
  export async function loadConfig(explicitPath) {
59
119
  const p = explicitPath || configPathFromEnv();
120
+ let filePart;
60
121
  try {
61
122
  const st = await fsp.stat(p);
62
- if (cache && cacheMtime === st.mtimeMs) return cache;
63
- cache = normalize(JSON.parse(await fsp.readFile(p, 'utf8')));
64
- cacheMtime = st.mtimeMs;
65
- return cache;
123
+ if (!(cache && cacheMtime === st.mtimeMs)) {
124
+ cache = normalize(JSON.parse(await fsp.readFile(p, 'utf8')));
125
+ cacheMtime = st.mtimeMs;
126
+ }
127
+ filePart = cache;
66
128
  } catch {
67
129
  // 不存在或损坏:返回默认结构(首次运行;也允许外部修好后自动恢复)
68
- cache = normalize(null);
130
+ filePart = normalize(null);
131
+ cache = filePart;
69
132
  cacheMtime = -1;
70
- return cache;
71
133
  }
134
+ // 偏好从 settings 表现读(迁移后文件里不再有它们),覆盖合并后归一
135
+ return normalize({ ...filePart, ...readPrefs() });
72
136
  }
73
137
 
74
138
  export async function saveConfig(next, explicitPath) {
139
+ const full = normalize(next);
140
+ // ① 文件:只写凭据白名单里的字段(**键集合精确等于 CREDENTIAL_KEYS** ——
141
+ // 偏好进了 settings,再写回文件会让「凭据文件」再次长出业务配置)。
142
+ const filePart = {};
143
+ for (const k of CREDENTIAL_KEYS) filePart[k] = full[k];
75
144
  const p = explicitPath || configPathFromEnv();
76
- const data = normalize(next);
77
145
  await fsp.mkdir(dirname(p), { recursive: true });
78
146
  const tmp = p + '.tmp';
79
- await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf8');
147
+ await fsp.writeFile(tmp, JSON.stringify(filePart, null, 2), 'utf8');
80
148
  await fsp.rename(tmp, p);
81
- cache = data;
149
+ // ② settings:偏好白名单(值不变就不写占位 —— loadConfig 侧缺键回落默认)
150
+ writePrefs(full);
151
+ cache = normalize({ ...filePart });
82
152
  try {
83
153
  cacheMtime = (await fsp.stat(p)).mtimeMs;
84
154
  } catch {
85
155
  cacheMtime = -1;
86
156
  }
87
- return data;
157
+ return full;
88
158
  }
89
159
 
90
160
  export async function updateConfig(patch) {