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,726 @@
1
+ // 统一资源表 attachments 的唯一读写实现(schema v2)。
2
+ //
3
+ // 这里只做「资源是什么 / 归谁所有」两件事,不做业务编排:
4
+ // · resources:file(本机或云端字节)、url(外部链接)、task(topic 内任务)、ref(文档);
5
+ // · relations:task_attach / ref_attach 的整组重写与孤儿查询;
6
+ // · 正文解析:`![名](fileId)` / `[名](fileId)`、`nxkv://task/<id>`、`nxkv://ref/<id>`、
7
+ // `[名](http(s)://…)` 都落库。用户可见的 markdown 写法不变。
8
+ //
9
+ // 为什么放在 core:localatt/attachstore(字节存储)与 docs/localtask 仓储(关系)
10
+ // 都要用它,放模块层会造成「核心存储依赖业务模块」的倒挂。
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, readFileSync, readdirSync, renameSync, unlinkSync } from 'node:fs';
13
+ import { isAbsolute, join, relative, resolve } from 'node:path';
14
+ // 不 import fileapi:它经 config → db/index → bootstrap → migrator 会绕回本模块。
15
+ // 这里只需要「按扩展名补一个够用的 MIME」,真实 MIME 由上传/同步路径写入。
16
+ const MIME_BY_EXT = {
17
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp',
18
+ gif: 'image/gif', svg: 'image/svg+xml', pdf: 'application/pdf',
19
+ md: 'text/markdown; charset=utf-8', txt: 'text/plain; charset=utf-8',
20
+ json: 'application/json; charset=utf-8', csv: 'text/csv; charset=utf-8',
21
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
22
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
23
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
24
+ };
25
+ function mimeFromName(name) {
26
+ const ext = String(name || '').split('.').pop().toLowerCase();
27
+ return MIME_BY_EXT[ext] || '';
28
+ }
29
+
30
+ /** 与 shared/attach.js 同一口径(core 不能反向 import shared)。 */
31
+ const FILE_ID_RE = /^[0-9a-fA-F]{16,}(\.[A-Za-z0-9]{1,8})?$/;
32
+ const MD_LINK_RE = /!?\[([^\]]*)\]\(\s*([^)\s]+)\s*\)/g;
33
+ const NXKV_TASK_RE = /^nxkv:\/\/task\/(\d+)$/i;
34
+ const NXKV_REF_RE = /^nxkv:\/\/ref\/([A-Za-z0-9_-]+)$/i;
35
+
36
+ const sha1 = (s) => createHash('sha1').update(String(s), 'utf8').digest('hex');
37
+
38
+ export function isFileId(value) {
39
+ return FILE_ID_RE.test(String(value ?? '').trim());
40
+ }
41
+
42
+ /** refs.locator → ref_id(与 import-json 的 refIdOf 同一公式;路径统一 POSIX)。 */
43
+ export function refIdFor(locator) {
44
+ return 'ref_' + sha1(String(locator ?? '').replace(/\\/g, '/')).slice(0, 16);
45
+ }
46
+
47
+ export function urlAttachmentId(url) {
48
+ return 'att_url_' + sha1(String(url || '').trim().toLowerCase()).slice(0, 16);
49
+ }
50
+
51
+ export function taskAttachmentId(topicKey, seq) {
52
+ return 'att_task_' + sha1(`${String(topicKey || '')}:${Number(seq) || 0}`).slice(0, 16);
53
+ }
54
+
55
+ export function refAttachmentId(refId) {
56
+ return 'att_ref_' + sha1(String(refId || '')).slice(0, 16);
57
+ }
58
+
59
+ function metaOf(row) {
60
+ try {
61
+ const v = JSON.parse(String((row && row.meta) || '{}'));
62
+ return v && typeof v === 'object' ? v : {};
63
+ } catch {
64
+ return {};
65
+ }
66
+ }
67
+
68
+ /**
69
+ * 正文 → 资源引用清单(顺序即 position)。只认:
70
+ * file:markdown 目标就是 fileId;
71
+ * task:nxkv://task/<全局 tasks.id>;
72
+ * ref:nxkv://ref/<ref_id>;
73
+ * url:markdown 目标是 http(s) 绝对地址。
74
+ * 其它链接(相对路径、锚点、普通 wiki 双链)不落资源表。
75
+ */
76
+ export function parseAttachmentRefs(text) {
77
+ const out = [];
78
+ const seen = new Set();
79
+ for (const m of String(text ?? '').matchAll(MD_LINK_RE)) {
80
+ const name = String(m[1] || '').trim();
81
+ const target = String(m[2] || '').trim();
82
+ const isImage = m[0].startsWith('![');
83
+ let ref = null;
84
+ if (isFileId(target)) {
85
+ ref = { kind: 'file', id: target, name: name || target, isImage };
86
+ } else {
87
+ const task = target.match(NXKV_TASK_RE);
88
+ const doc = target.match(NXKV_REF_RE);
89
+ if (task) ref = { kind: 'task', targetTaskId: Number(task[1]), name: name || `任务 ${task[1]}` };
90
+ else if (doc) ref = { kind: 'ref', targetRefId: doc[1], name: name || doc[1] };
91
+ else if (/^https?:\/\//i.test(target)) ref = { kind: 'url', url: target, name: name || target };
92
+ }
93
+ if (!ref) continue;
94
+ // 同一资源出现多次只保留第一条(关系表一资源一 role 一行,position 取首次出现)
95
+ const key = ref.id || (ref.kind === 'task' ? `task:${ref.targetTaskId}` : '')
96
+ || (ref.kind === 'ref' ? `ref:${ref.targetRefId}` : '')
97
+ || (ref.kind === 'url' ? `url:${ref.url.toLowerCase()}` : '');
98
+ if (seen.has(key)) continue;
99
+ seen.add(key);
100
+ ref.position = out.length;
101
+ ref.role = ref.kind === 'task' || ref.kind === 'ref' ? 'reference' : 'inline';
102
+ out.push(ref);
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /** 插入/更新一个本机或云端文件资源(id = fileId)。 */
108
+ export function upsertFileAttachment(conn, {
109
+ id,
110
+ name = '',
111
+ localPath = '',
112
+ mime = '',
113
+ size = 0,
114
+ hash = '',
115
+ storage = '',
116
+ groupId = 0,
117
+ meta = {},
118
+ atMs = Date.now(),
119
+ } = {}) {
120
+ const fid = String(id || '').trim();
121
+ if (!isFileId(fid)) throw new Error(`非法 fileId: ${fid}`);
122
+ const cur = conn.get('SELECT * FROM attachments WHERE id = :id', { id: fid });
123
+ const mergedMeta = { ...(cur ? metaOf(cur) : {}), ...(meta || {}) };
124
+ if (!cur) {
125
+ conn.run(
126
+ `INSERT INTO attachments
127
+ (id, kind, name, local_path, url, mime, size, hash, storage, group_id,
128
+ target_kind, target_key, target_seq, dedupe_key, meta, deleted_at, created_at, updated_at)
129
+ VALUES (:id, 'file', :name, :localPath, '', :mime, :size, :hash, :storage, :groupId,
130
+ '', '', NULL, '', :meta, NULL, :at, :at)`,
131
+ {
132
+ id: fid,
133
+ name: String(name || ''),
134
+ localPath: String(localPath || ''),
135
+ mime: String(mime || ''),
136
+ size: Math.max(0, Number(size) || 0),
137
+ hash: String(hash || ''),
138
+ storage: String(storage || ''),
139
+ groupId: Number(groupId) || 0,
140
+ meta: JSON.stringify(mergedMeta),
141
+ at: atMs,
142
+ }
143
+ );
144
+ return fid;
145
+ }
146
+ conn.run(
147
+ `UPDATE attachments SET
148
+ name = :name,
149
+ local_path = :localPath,
150
+ mime = :mime,
151
+ size = :size,
152
+ hash = :hash,
153
+ storage = :storage,
154
+ group_id = :groupId,
155
+ meta = :meta,
156
+ deleted_at = NULL,
157
+ updated_at = :at
158
+ WHERE id = :id`,
159
+ {
160
+ id: fid,
161
+ // 空值不覆盖已有真实值(正文先落占位、上传后补元数据的场景)
162
+ name: String(name || cur.name || ''),
163
+ localPath: String(localPath || cur.local_path || ''),
164
+ mime: String(mime || cur.mime || ''),
165
+ size: Math.max(0, Number(size) || Number(cur.size) || 0),
166
+ hash: String(hash || cur.hash || ''),
167
+ storage: String(storage || cur.storage || ''),
168
+ groupId: Number(groupId) || Number(cur.group_id) || 0,
169
+ meta: JSON.stringify(mergedMeta),
170
+ at: atMs,
171
+ }
172
+ );
173
+ return fid;
174
+ }
175
+
176
+ function upsertDeduped(conn, {
177
+ id, kind, name, dedupeKey, url = '', targetKind = '', targetKey = '', targetSeq = null,
178
+ meta = {}, atMs = Date.now(),
179
+ }) {
180
+ const row = conn.get(
181
+ 'SELECT * FROM attachments WHERE dedupe_key = :key AND deleted_at IS NULL',
182
+ { key: dedupeKey }
183
+ );
184
+ if (row) {
185
+ // 存量脏数据自愈:旧行把正文写进 name(多行/超长)时,后续 attach 用新值覆盖。
186
+ const dirtyName = String(row.name || '').includes('\n') || String(row.name || '').length > 200;
187
+ if (name && (!row.name || dirtyName)) {
188
+ conn.run('UPDATE attachments SET name = :name, updated_at = :at WHERE id = :id', {
189
+ id: row.id, name, at: atMs,
190
+ });
191
+ }
192
+ return row.id;
193
+ }
194
+ conn.run(
195
+ `INSERT INTO attachments
196
+ (id, kind, name, local_path, url, mime, size, hash, storage, group_id,
197
+ target_kind, target_key, target_seq, dedupe_key, meta, deleted_at, created_at, updated_at)
198
+ VALUES (:id, :kind, :name, '', :url, '', 0, '', '', 0,
199
+ :targetKind, :targetKey, :targetSeq, :dedupeKey, :meta, NULL, :at, :at)`,
200
+ {
201
+ id,
202
+ kind,
203
+ name: String(name || ''),
204
+ url: String(url || ''),
205
+ targetKind,
206
+ targetKey: String(targetKey || ''),
207
+ targetSeq,
208
+ dedupeKey,
209
+ meta: JSON.stringify(meta || {}),
210
+ at: atMs,
211
+ }
212
+ );
213
+ return id;
214
+ }
215
+
216
+ export function ensureUrlAttachment(conn, { url, name = '', atMs = Date.now() } = {}) {
217
+ const u = String(url || '').trim();
218
+ if (!/^https?:\/\//i.test(u)) return null;
219
+ return upsertDeduped(conn, {
220
+ id: urlAttachmentId(u),
221
+ kind: 'url',
222
+ name: name || u,
223
+ dedupeKey: 'url:' + u.toLowerCase(),
224
+ url: u,
225
+ atMs,
226
+ });
227
+ }
228
+
229
+ /**
230
+ * 去掉正文头部的 frontmatter(与 shared/frontmatter.js 的 stripFrontmatter 同口径)。
231
+ * core 是最底层,不能反向 import shared,所以这里保留一份最小实现。
232
+ */
233
+ const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
234
+ const FM_KV_RE = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/;
235
+ function stripFrontmatter(src) {
236
+ return String(src ?? '').replace(FM_RE, (block, inner) => {
237
+ const kv = String(inner || '').split(/\r?\n/).some((l) => FM_KV_RE.test(l));
238
+ return kv ? '' : block;
239
+ });
240
+ }
241
+
242
+ /** 任务标题 = 正文(去 frontmatter)首个非空行,去 # 前缀,截 80 字。 */
243
+ function taskTitleOf(body) {
244
+ const text = String(stripFrontmatter(String(body || ''))).trim();
245
+ const first = text.split(/\r?\n/).map((s) => s.trim()).find(Boolean) || '';
246
+ return first.replace(/^#+\s*/, '').trim().slice(0, 80);
247
+ }
248
+
249
+ /**
250
+ * task 型附件的展示名:只允许「#seq 标题」这种短标签,**绝不允许正文**。
251
+ * 调用方(CLI/面板)可能把整段正文当 name 传进来,这里统一兜底:
252
+ * - 单行且 ≤80 字 → 视为用户给的别名,去 #seq/# 前缀后保留;
253
+ * - 多行或超长 → 判定为正文,改用任务实时标题。
254
+ */
255
+ function taskAttachmentName(name, seq, title) {
256
+ const raw = String(name || '').trim();
257
+ const firstLine = raw.split(/\r?\n/)[0].trim();
258
+ const alias = firstLine.replace(/^#\s*\d+\s*/u, '').replace(/^#+\s*/u, '').trim();
259
+ const bodyLike = raw.includes('\n') || raw.length > 80 || !alias;
260
+ const label = bodyLike ? title || `任务 #${seq}` : alias.slice(0, 80);
261
+ return `#${seq} ${label}`.trim();
262
+ }
263
+
264
+ export function ensureTaskAttachment(conn, { taskId, atMs = Date.now(), name = '' } = {}) {
265
+ const row = conn.get(
266
+ `SELECT t.id AS taskId, t.seq, t.body, k.key AS topicKey
267
+ FROM tasks t JOIN topics k ON k.id = t.topic_id
268
+ WHERE t.id = :id`,
269
+ { id: Number(taskId) }
270
+ );
271
+ if (!row) return null;
272
+ const seq = Number(row.seq) || 0;
273
+ return upsertDeduped(conn, {
274
+ id: taskAttachmentId(row.topicKey, seq),
275
+ kind: 'task',
276
+ name: taskAttachmentName(name, seq, taskTitleOf(row.body)),
277
+ dedupeKey: `task:${row.topicKey}:${seq}`,
278
+ targetKind: 'task',
279
+ targetKey: String(row.topicKey),
280
+ targetSeq: seq,
281
+ meta: { taskId: Number(row.taskId), topicKey: String(row.topicKey), seq },
282
+ atMs,
283
+ });
284
+ }
285
+
286
+ export function ensureRefAttachment(conn, { refId, atMs = Date.now(), name = '' } = {}) {
287
+ const row = conn.get('SELECT id, locator FROM refs WHERE id = :id', { id: String(refId || '') });
288
+ if (!row) return null;
289
+ return upsertDeduped(conn, {
290
+ id: refAttachmentId(row.id),
291
+ kind: 'ref',
292
+ name: name || String(row.locator || row.id).split('/').pop(),
293
+ dedupeKey: `ref:${row.id}`,
294
+ targetKind: 'ref',
295
+ targetKey: String(row.id),
296
+ meta: { refId: String(row.id), locator: String(row.locator || '') },
297
+ atMs,
298
+ });
299
+ }
300
+
301
+ /** 一条正文引用 → 资源 id(无法解析到真实目标的返回 null)。 */
302
+ export function ensureAttachment(conn, ref, { atMs = Date.now() } = {}) {
303
+ if (!ref) return null;
304
+ if (ref.kind === 'file') {
305
+ return upsertFileAttachment(conn, {
306
+ id: ref.id,
307
+ name: ref.name,
308
+ mime: mimeFromName(ref.name),
309
+ storage: '',
310
+ meta: { isImage: !!ref.isImage, source: 'body' },
311
+ atMs,
312
+ });
313
+ }
314
+ if (ref.kind === 'url') return ensureUrlAttachment(conn, { url: ref.url, name: ref.name, atMs });
315
+ if (ref.kind === 'task') {
316
+ return ensureTaskAttachment(conn, { taskId: ref.targetTaskId, name: ref.name, atMs });
317
+ }
318
+ if (ref.kind === 'ref') return ensureRefAttachment(conn, { refId: ref.targetRefId, name: ref.name, atMs });
319
+ return null;
320
+ }
321
+
322
+ // ── 关系表写入(任务/文档共用一套语义) ────────────────────────────────
323
+ //
324
+ // role 是**边的语义**,不是资源的属性;同一资源对同一宿主只有一行(PK)。
325
+ // 冲突时的处置规则(2026-11-08 附件区改造):
326
+ // 已有 role 优先级 >= 新 role → 保留已有(正文同步不能把用户显式挂的东西降级);
327
+ // 否则升级(正文里出现的资源后来被显式挂载 → attach,删正文行也不会丢);
328
+ // 同 role 重复写只刷新 position(正文改了,顺序跟着改)。
329
+ // 优先级 attach > doc > reference > inline:越"显式"越不容易被正文覆盖。
330
+ const ROLE_PRIORITY = { inline: 0, reference: 1, doc: 2, attach: 3 };
331
+ const HOST_TABLE = {
332
+ task: { table: 'task_attach', col: 'task_id', roles: ['inline', 'attach', 'doc'] },
333
+ ref: { table: 'ref_attach', col: 'ref_id', roles: ['inline', 'attach', 'reference'] },
334
+ };
335
+
336
+ function hostOf(host) {
337
+ const h = HOST_TABLE[String(host || '')];
338
+ if (!h) throw new Error(`未知附件宿主: ${host}(应为 task 或 ref)`);
339
+ return h;
340
+ }
341
+
342
+ /**
343
+ * 写一条宿主 ↔ 资源的关系(upsert,带 role 优先级)。
344
+ * @returns {string} 实际落库的 role
345
+ */
346
+ export function linkAttachment(conn, {
347
+ host, hostId, attachmentId, role = 'attach', position, note = '', atMs = Date.now(),
348
+ } = {}) {
349
+ const h = hostOf(host);
350
+ const hostVal = host === 'task' ? Number(hostId) : String(hostId || '');
351
+ const att = String(attachmentId || '');
352
+ if (!att) throw new Error('linkAttachment 需要 attachmentId');
353
+ if (!h.roles.includes(role)) throw new Error(`非法 role: ${role}(${host} 只允许 ${h.roles.join('/')})`);
354
+ const idOk = host === 'task' ? Number.isFinite(hostVal) : !!hostVal;
355
+ if (!idOk) throw new Error(`linkAttachment 需要有效的 ${host} 宿主 id`);
356
+
357
+ const cur = conn.get(
358
+ `SELECT role, position FROM ${h.table} WHERE ${h.col} = :host AND attachment_id = :att`,
359
+ { host: hostVal, att }
360
+ );
361
+ if (cur) {
362
+ const curRank = ROLE_PRIORITY[cur.role] ?? 0;
363
+ const newRank = ROLE_PRIORITY[role] ?? 0;
364
+ if (curRank > newRank) return cur.role; // 显式边不被正文降级
365
+ if (curRank === newRank) {
366
+ const pos = position === undefined ? cur.position : position;
367
+ conn.run(
368
+ `UPDATE ${h.table} SET position = :pos WHERE ${h.col} = :host AND attachment_id = :att`,
369
+ { pos: Number(pos) || 0, host: hostVal, att }
370
+ );
371
+ return cur.role;
372
+ }
373
+ conn.run(
374
+ `UPDATE ${h.table} SET role = :role, position = :pos, note = :note
375
+ WHERE ${h.col} = :host AND attachment_id = :att`,
376
+ { role, pos: Number(position) || 0, note: String(note || ''), host: hostVal, att }
377
+ );
378
+ return role;
379
+ }
380
+ let pos = position;
381
+ if (pos === undefined) {
382
+ // 附件区(非 inline)默认追加到末尾;inline 的 position 由正文解析给出
383
+ const row = conn.get(
384
+ `SELECT COALESCE(MAX(position), -1) + 1 AS next FROM ${h.table}
385
+ WHERE ${h.col} = :host AND role <> 'inline'`,
386
+ { host: hostVal }
387
+ );
388
+ pos = Number((row && row.next) || 0);
389
+ }
390
+ conn.run(
391
+ `INSERT INTO ${h.table} (${h.col}, attachment_id, role, position, note, created_at)
392
+ VALUES (:host, :att, :role, :pos, :note, :at)`,
393
+ { host: hostVal, att, role, pos: Number(pos) || 0, note: String(note || ''), at: atMs }
394
+ );
395
+ return role;
396
+ }
397
+
398
+ /** 解除一条关系(只删边,不删资源字节)。返回是否真的删掉。 */
399
+ export function unlinkAttachment(conn, { host, hostId, attachmentId } = {}) {
400
+ const h = hostOf(host);
401
+ const hostVal = host === 'task' ? Number(hostId) : String(hostId || '');
402
+ const att = String(attachmentId || '');
403
+ const r = conn.run(
404
+ `DELETE FROM ${h.table} WHERE ${h.col} = :host AND attachment_id = :att`,
405
+ { host: hostVal, att }
406
+ );
407
+ return Number(r.changes) || 0;
408
+ }
409
+
410
+ /**
411
+ * 删除资源行(可选连字节一起删)。仍被任何任务/文档引用时拒绝——关系表是权威,
412
+ * 「解除关系」和「删资源」是两步,不能因为一次 detach --purge 误删别人在用的文件。
413
+ * @returns {{removed:boolean, reason?:string, attachment?:object}}
414
+ */
415
+ export function deleteAttachment(conn, id, { attachmentsRoot, purgeBytes = true } = {}) {
416
+ const row = getAttachment(conn, id);
417
+ if (!row) return { removed: false, reason: 'not-found' };
418
+ const still = conn.get(
419
+ `SELECT 1 AS x FROM task_attach WHERE attachment_id = :id
420
+ UNION ALL SELECT 1 FROM ref_attach WHERE attachment_id = :id LIMIT 1`,
421
+ { id: row.id }
422
+ );
423
+ if (still) return { removed: false, reason: 'in-use', attachment: row };
424
+ let bytesRemoved = false;
425
+ if (purgeBytes && row.kind === 'file' && row.localPath && within(attachmentsRoot, row.localPath)) {
426
+ try {
427
+ if (existsSync(row.localPath)) {
428
+ unlinkSync(row.localPath);
429
+ bytesRemoved = true;
430
+ }
431
+ } catch {
432
+ return { removed: false, reason: 'file-locked', attachment: row };
433
+ }
434
+ }
435
+ conn.run('DELETE FROM attachments WHERE id = :id', { id: row.id });
436
+ return { removed: true, bytesRemoved, attachment: row };
437
+ }
438
+
439
+ /** 任务正文里的资源整组重写(只动 inline 边,显式 attach/doc 保留)。 */
440
+ export function syncTaskAttachments(conn, { taskId, text, atMs = Date.now() } = {}) {
441
+ const id = Number(taskId);
442
+ if (!Number.isFinite(id)) return 0;
443
+ const refs = parseAttachmentRefs(text);
444
+ const ids = [];
445
+ for (const r of refs) {
446
+ const att = ensureAttachment(conn, r, { atMs });
447
+ if (att && !ids.includes(att)) ids.push(att);
448
+ }
449
+ conn.run("DELETE FROM task_attach WHERE task_id = :id AND role = 'inline'", { id });
450
+ ids.forEach((att, pos) => {
451
+ linkAttachment(conn, { host: 'task', hostId: id, attachmentId: att, role: 'inline', position: pos, atMs });
452
+ });
453
+ return ids.length;
454
+ }
455
+
456
+ /** 文档正文里的资源整组重写(inline + reference 边;显式 attach 保留)。 */
457
+ export function syncRefAttachments(conn, { refId, text, atMs = Date.now() } = {}) {
458
+ const id = String(refId || '');
459
+ if (!id) return 0;
460
+ const refs = parseAttachmentRefs(text);
461
+ const rows = [];
462
+ for (const r of refs) {
463
+ const att = ensureAttachment(conn, r, { atMs });
464
+ if (att && !rows.some((x) => x.id === att)) rows.push({ id: att, role: r.role });
465
+ }
466
+ conn.run("DELETE FROM ref_attach WHERE ref_id = :id AND role IN ('inline', 'reference')", { id });
467
+ rows.forEach((x, pos) => {
468
+ linkAttachment(conn, { host: 'ref', hostId: id, attachmentId: x.id, role: x.role, position: pos, atMs });
469
+ });
470
+ return rows.length;
471
+ }
472
+
473
+ /**
474
+ * 把一个「文档标识」解析成 refs.id:先按 id,再按 locator(原样 / 反斜杠归一),
475
+ * 都没有返回 null。CLI `--ref` 与面板选择器共用这一条,避免各自猜地址语法。
476
+ */
477
+ export function resolveRefId(conn, input) {
478
+ const raw = String(input || '').trim();
479
+ if (!raw) return null;
480
+ const byId = conn.get('SELECT id FROM refs WHERE id = :id AND deleted_at IS NULL', { id: raw });
481
+ if (byId) return byId.id;
482
+ const loc = raw.replace(/\\/g, '/');
483
+ const byLoc = conn.get(
484
+ 'SELECT id FROM refs WHERE locator = :loc AND deleted_at IS NULL', { loc }
485
+ );
486
+ if (byLoc) return byLoc.id;
487
+ const derived = refIdFor(loc);
488
+ const byDerived = conn.get('SELECT id FROM refs WHERE id = :id AND deleted_at IS NULL', { id: derived });
489
+ return byDerived ? byDerived.id : null;
490
+ }
491
+
492
+ /** 确保 refs 行存在(文档保存 / 索引重建共用;已有行不重置 state)。 */
493
+ export function ensureDocRef(conn, { locator, atMs = Date.now() } = {}) {
494
+ const loc = String(locator || '').trim().replace(/\\/g, '/');
495
+ if (!loc) return null;
496
+ const id = refIdFor(loc);
497
+ conn.run(
498
+ `INSERT INTO refs (id, type, locator, state, version, deleted_at, created_at, updated_at)
499
+ VALUES (:id, 'md', :locator, 'orphan', 0, NULL, :at, :at)
500
+ ON CONFLICT(id) DO UPDATE SET type = 'md', locator = excluded.locator, updated_at = excluded.updated_at`,
501
+ { id, locator: loc, at: atMs }
502
+ );
503
+ return id;
504
+ }
505
+
506
+ /** 文档删除:refs 行消失,ref_attach / ref_bindings 随之 CASCADE。 */
507
+ export function forgetDocRef(conn, locator) {
508
+ const loc = String(locator || '').trim().replace(/\\/g, '/');
509
+ if (!loc) return 0;
510
+ const r = conn.run('DELETE FROM refs WHERE id = :id', { id: refIdFor(loc) });
511
+ return Number(r.changes) || 0;
512
+ }
513
+
514
+ /** 全量重扫任务正文(迁移与导入后用;幂等)。 */
515
+ export function syncTaskAttachmentIndex(conn, { atMs = Date.now() } = {}) {
516
+ const rows = conn.all('SELECT id, body FROM tasks ORDER BY id');
517
+ let n = 0;
518
+ for (const row of rows) n += syncTaskAttachments(conn, { taskId: row.id, text: row.body, atMs });
519
+ return n;
520
+ }
521
+
522
+ /** 全量重扫 docs 自有树 + 外部 .md(迁移与索引重建用;幂等)。 */
523
+ export function syncDocAttachmentIndex(conn, { docsRoot, atMs = Date.now() } = {}) {
524
+ const root = String(docsRoot || '');
525
+ const files = [];
526
+ const walk = (dir) => {
527
+ let entries = [];
528
+ try {
529
+ entries = readdirSync(dir, { withFileTypes: true });
530
+ } catch {
531
+ return;
532
+ }
533
+ for (const e of entries) {
534
+ const abs = join(dir, e.name);
535
+ if (e.isDirectory()) walk(abs);
536
+ else if (e.isFile() && /\.md$/i.test(e.name)) files.push(abs);
537
+ }
538
+ };
539
+ if (root && existsSync(root)) walk(root);
540
+ let n = 0;
541
+ const covered = new Set();
542
+ for (const abs of files.sort()) {
543
+ const locator = relative(root, abs).replace(/\\/g, '/');
544
+ covered.add(resolve(abs).replace(/\\/g, '/').toLowerCase());
545
+ let text = '';
546
+ try {
547
+ text = readFileSync(abs, 'utf8');
548
+ } catch {
549
+ continue;
550
+ }
551
+ const refId = ensureDocRef(conn, { locator, atMs });
552
+ n += syncRefAttachments(conn, { refId, text, atMs });
553
+ }
554
+ // 外部 .md(refs.locator 是绝对路径):不在 docs 树里,但同样是文档库的一行。
555
+ // 迁移必须把它们的正文引用也落库,否则「存量文档的图片」只有正文 fileId 字符串。
556
+ for (const row of conn.all("SELECT id, locator FROM refs WHERE type = 'md'")) {
557
+ const loc = String(row.locator || '');
558
+ if (!isAbsolute(loc) || !existsSync(loc)) continue;
559
+ if (covered.has(resolve(loc).replace(/\\/g, '/').toLowerCase())) continue;
560
+ if (!/\.md$/i.test(loc)) continue;
561
+ let text = '';
562
+ try {
563
+ text = readFileSync(loc, 'utf8');
564
+ } catch {
565
+ continue;
566
+ }
567
+ n += syncRefAttachments(conn, { refId: row.id, text, atMs });
568
+ }
569
+ return n;
570
+ }
571
+
572
+ const ATT_SELECT = `SELECT id, kind, name, local_path, url, mime, size, hash, storage, group_id,
573
+ target_kind, target_key, target_seq, meta, deleted_at, created_at, updated_at
574
+ FROM attachments`;
575
+
576
+ function rowView(row) {
577
+ return {
578
+ id: row.id,
579
+ kind: row.kind,
580
+ name: row.name,
581
+ localPath: row.local_path,
582
+ url: row.url,
583
+ mime: row.mime,
584
+ size: Number(row.size) || 0,
585
+ hash: row.hash,
586
+ storage: row.storage,
587
+ groupId: Number(row.group_id) || 0,
588
+ targetKind: row.target_kind,
589
+ targetKey: row.target_key,
590
+ targetSeq: row.target_seq === null || row.target_seq === undefined ? null : Number(row.target_seq),
591
+ meta: metaOf(row),
592
+ deletedAt: row.deleted_at,
593
+ createdAt: Number(row.created_at) || 0,
594
+ updatedAt: Number(row.updated_at) || 0,
595
+ };
596
+ }
597
+
598
+ export function getAttachment(conn, id) {
599
+ const row = conn.get(`${ATT_SELECT} WHERE id = :id`, { id: String(id || '') });
600
+ return row ? rowView(row) : null;
601
+ }
602
+
603
+ export function listTaskAttachments(conn, taskId) {
604
+ return conn
605
+ .all(
606
+ `SELECT a.id, a.kind, a.name, a.local_path, a.url, a.mime, a.size, a.hash, a.storage,
607
+ a.group_id, a.target_kind, a.target_key, a.target_seq, a.meta,
608
+ a.deleted_at, a.created_at, a.updated_at, ta.role, ta.position, ta.note
609
+ FROM task_attach ta JOIN attachments a ON a.id = ta.attachment_id
610
+ WHERE ta.task_id = :id AND a.deleted_at IS NULL
611
+ ORDER BY ta.position, a.id`,
612
+ { id: Number(taskId) }
613
+ )
614
+ .map((r) => ({ ...rowView(r), role: r.role, position: Number(r.position) || 0, note: r.note }));
615
+ }
616
+
617
+ /** CLI 只有 topicKey + seq 时的查询入口。 */
618
+ export function listTaskAttachmentsBySeq(conn, { topicKey, seq }) {
619
+ const row = conn.get(
620
+ `SELECT t.id FROM tasks t JOIN topics k ON k.id = t.topic_id
621
+ WHERE k.key = :key AND t.seq = :seq`,
622
+ { key: String(topicKey || ''), seq: Number(seq) }
623
+ );
624
+ return row ? listTaskAttachments(conn, Number(row.id)) : [];
625
+ }
626
+
627
+ export function listRefAttachments(conn, refId) {
628
+ return conn
629
+ .all(
630
+ `SELECT a.id, a.kind, a.name, a.local_path, a.url, a.mime, a.size, a.hash, a.storage,
631
+ a.group_id, a.target_kind, a.target_key, a.target_seq, a.meta,
632
+ a.deleted_at, a.created_at, a.updated_at, ra.role, ra.position, ra.note
633
+ FROM ref_attach ra JOIN attachments a ON a.id = ra.attachment_id
634
+ WHERE ra.ref_id = :id AND a.deleted_at IS NULL
635
+ ORDER BY ra.position, a.id`,
636
+ { id: String(refId || '') }
637
+ )
638
+ .map((r) => ({ ...rowView(r), role: r.role, position: Number(r.position) || 0, note: r.note }));
639
+ }
640
+
641
+ /**
642
+ * 无主资源:没有任何 task_attach / ref_attach 边。
643
+ * 软删的任务/文档仍算「有主」(软删可恢复,不能在这里把字节删掉)。
644
+ */
645
+ export function listOrphans(conn) {
646
+ return conn
647
+ .all(
648
+ `${ATT_SELECT}
649
+ WHERE deleted_at IS NULL
650
+ AND NOT EXISTS (SELECT 1 FROM task_attach ta WHERE ta.attachment_id = attachments.id)
651
+ AND NOT EXISTS (SELECT 1 FROM ref_attach ra WHERE ra.attachment_id = attachments.id)
652
+ ORDER BY created_at, id`
653
+ )
654
+ .map(rowView);
655
+ }
656
+
657
+ function within(root, p) {
658
+ if (!root || !p) return false;
659
+ const a = resolve(root).replace(/\\/g, '/').toLowerCase();
660
+ const b = resolve(p).replace(/\\/g, '/').toLowerCase();
661
+ return b === a || b.startsWith(a.replace(/\/+$/, '') + '/');
662
+ }
663
+
664
+ export function pruneOrphans(conn, { attachmentsRoot, dryRun = false } = {}) {
665
+ const rows = listOrphans(conn);
666
+ const removed = [];
667
+ const skipped = [];
668
+ for (const row of rows) {
669
+ if (dryRun) {
670
+ removed.push(row);
671
+ continue;
672
+ }
673
+ const still = conn.get(
674
+ `SELECT 1 AS x FROM task_attach WHERE attachment_id = :id
675
+ UNION ALL SELECT 1 FROM ref_attach WHERE attachment_id = :id LIMIT 1`,
676
+ { id: row.id }
677
+ );
678
+ if (still) {
679
+ skipped.push(row);
680
+ continue;
681
+ }
682
+ if (row.kind === 'file' && row.localPath && within(attachmentsRoot, row.localPath)) {
683
+ try {
684
+ if (existsSync(row.localPath)) unlinkSync(row.localPath);
685
+ } catch {
686
+ /* 文件被占用:留到下次,先不删行(否则会变成无记录的残文件) */
687
+ skipped.push(row);
688
+ continue;
689
+ }
690
+ }
691
+ conn.run('DELETE FROM attachments WHERE id = :id AND deleted_at IS NULL', { id: row.id });
692
+ removed.push(row);
693
+ }
694
+ return { removed, skipped };
695
+ }
696
+
697
+ /** 迁移后归档旧 manifest(运行时不再写它,归档只是留证据)。 */
698
+ export function archiveAttachmentManifests(root, tag) {
699
+ const out = [];
700
+ if (!root || !existsSync(root)) return out;
701
+ const candidates = [];
702
+ const local = join(root, 'local', 'manifest.json');
703
+ if (existsSync(local)) candidates.push(local);
704
+ let entries = [];
705
+ try {
706
+ entries = readdirSync(root, { withFileTypes: true });
707
+ } catch {
708
+ entries = [];
709
+ }
710
+ for (const e of entries) {
711
+ if (!e.isDirectory() || e.name === 'local') continue;
712
+ const p = join(root, e.name, 'manifest.json');
713
+ if (existsSync(p)) candidates.push(p);
714
+ }
715
+ for (const from of candidates) {
716
+ const to = from.replace(/manifest\.json$/i, `manifest.migrated-${tag}.json`);
717
+ try {
718
+ if (existsSync(to)) continue;
719
+ renameSync(from, to);
720
+ out.push({ from, to });
721
+ } catch {
722
+ /* 归档失败不影响运行时(DB 已是唯一真相) */
723
+ }
724
+ }
725
+ return out;
726
+ }