nx-kv 0.48.1 → 0.49.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 (289) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/package.json +1 -1
  3. package/src/core/attachmentdb/bodies.ts +161 -0
  4. package/src/core/attachmentdb/docs.ts +95 -33
  5. package/src/core/attachmentdb/ids.ts +27 -1
  6. package/src/core/attachmentdb/mdfile.ts +249 -0
  7. package/src/core/attachmentdb/query.ts +14 -1
  8. package/src/core/attachmentdb/resources.ts +23 -0
  9. package/src/core/attachmentdb.ts +22 -0
  10. package/src/core/db/bootstrap.ts +5 -5
  11. package/src/core/db/import-json/refs.ts +27 -13
  12. package/src/core/db/migrations/index.ts +7 -0
  13. package/src/core/db/migrations/v2-data.ts +4 -4
  14. package/src/core/db/migrations/v5.sql +100 -0
  15. package/src/core/db/migrations/v6-data.ts +261 -0
  16. package/src/core/db/migrations/v6.sql +67 -0
  17. package/src/core/db/version.ts +9 -1
  18. package/src/core/paths.ts +10 -0
  19. package/src/modules/auth/actions/auth-login.ts +11 -4
  20. package/src/modules/auth/actions/auth-logout.ts +9 -4
  21. package/src/modules/auth/actions/auth-me.ts +9 -4
  22. package/src/modules/auth/actions/auth-status.ts +9 -4
  23. package/src/modules/bundled/actions/bundled-get.ts +12 -4
  24. package/src/modules/bundled/actions/bundled-groups.ts +9 -4
  25. package/src/modules/bundled/actions/bundled-install.ts +13 -4
  26. package/src/modules/bundled/actions/bundled-list.ts +9 -4
  27. package/src/modules/db/actions/db-backup.ts +10 -4
  28. package/src/modules/db/actions/db-migrate.ts +10 -4
  29. package/src/modules/db/actions/db-status.ts +9 -4
  30. package/src/modules/db/actions/db-verify.ts +9 -4
  31. package/src/modules/docs/actions/_manifest.generated.ts +9 -0
  32. package/src/modules/docs/actions/doc-add.ts +12 -4
  33. package/src/modules/docs/actions/doc-attach-note.ts +11 -4
  34. package/src/modules/docs/actions/doc-attach.ts +20 -5
  35. package/src/modules/docs/actions/doc-attachments.ts +9 -4
  36. package/src/modules/docs/actions/doc-detach.ts +11 -4
  37. package/src/modules/docs/actions/doc-get.ts +9 -4
  38. package/src/modules/docs/actions/doc-link-file.ts +28 -0
  39. package/src/modules/docs/actions/doc-list.ts +9 -4
  40. package/src/modules/docs/actions/doc-mdfile.ts +28 -0
  41. package/src/modules/docs/actions/doc-mdfiles.ts +29 -0
  42. package/src/modules/docs/actions/doc-remove.ts +9 -4
  43. package/src/modules/docs/actions/doc-update.ts +12 -4
  44. package/src/modules/docs/actions/docs-bind.ts +13 -4
  45. package/src/modules/docs/actions/docs-index.ts +9 -4
  46. package/src/modules/docs/actions/docs-link.ts +14 -4
  47. package/src/modules/docs/actions/docs-notebind.ts +13 -4
  48. package/src/modules/docs/actions/docs-seed.ts +9 -4
  49. package/src/modules/docs/attach.ts +14 -1
  50. package/src/modules/docs/docref.ts +13 -1
  51. package/src/modules/docs/knowledge.ts +17 -19
  52. package/src/modules/docs/mdfile.ts +24 -0
  53. package/src/modules/docs/paths.ts +6 -9
  54. package/src/modules/docs/render.ts +24 -4
  55. package/src/modules/docs/seed.ts +1 -1
  56. package/src/modules/docs/service.ts +48 -18
  57. package/src/modules/docs/store.ts +120 -74
  58. package/src/modules/file/actions/file-content.ts +10 -4
  59. package/src/modules/file/actions/file-get.ts +10 -4
  60. package/src/modules/file/actions/file-list.ts +11 -4
  61. package/src/modules/file/actions/file-orphans.ts +9 -4
  62. package/src/modules/file/actions/file-prune.ts +10 -4
  63. package/src/modules/file/actions/file-remove.ts +10 -4
  64. package/src/modules/file/actions/file-sync.ts +13 -4
  65. package/src/modules/file/actions/file-upload.ts +15 -4
  66. package/src/modules/localtask/action-render.ts +2 -2
  67. package/src/modules/localtask/actions/localtask-add.ts +24 -4
  68. package/src/modules/localtask/actions/localtask-attach-note.ts +13 -4
  69. package/src/modules/localtask/actions/localtask-attach.ts +26 -6
  70. package/src/modules/localtask/actions/localtask-attachments.ts +11 -4
  71. package/src/modules/localtask/actions/localtask-cancel.ts +10 -4
  72. package/src/modules/localtask/actions/localtask-cancelMany.ts +11 -4
  73. package/src/modules/localtask/actions/localtask-chain.ts +11 -4
  74. package/src/modules/localtask/actions/localtask-claim.ts +12 -4
  75. package/src/modules/localtask/actions/localtask-clone.ts +11 -4
  76. package/src/modules/localtask/actions/localtask-closeMany.ts +13 -4
  77. package/src/modules/localtask/actions/localtask-config.ts +19 -4
  78. package/src/modules/localtask/actions/localtask-detach.ts +13 -4
  79. package/src/modules/localtask/actions/localtask-done.ts +12 -4
  80. package/src/modules/localtask/actions/localtask-events.ts +12 -4
  81. package/src/modules/localtask/actions/localtask-fork.ts +11 -4
  82. package/src/modules/localtask/actions/localtask-get.ts +11 -4
  83. package/src/modules/localtask/actions/localtask-importRemote.ts +13 -4
  84. package/src/modules/localtask/actions/localtask-list.ts +9 -4
  85. package/src/modules/localtask/actions/localtask-presence.ts +9 -4
  86. package/src/modules/localtask/actions/localtask-preview.ts +13 -4
  87. package/src/modules/localtask/actions/localtask-prune.ts +10 -4
  88. package/src/modules/localtask/actions/localtask-remove.ts +12 -4
  89. package/src/modules/localtask/actions/localtask-removeMany.ts +12 -4
  90. package/src/modules/localtask/actions/localtask-reopen.ts +17 -4
  91. package/src/modules/localtask/actions/localtask-reorder.ts +15 -4
  92. package/src/modules/localtask/actions/localtask-task-restore.ts +11 -4
  93. package/src/modules/localtask/actions/localtask-timegoalLog.ts +11 -4
  94. package/src/modules/localtask/actions/localtask-topic-add.ts +10 -4
  95. package/src/modules/localtask/actions/localtask-topic-remove.ts +11 -4
  96. package/src/modules/localtask/actions/localtask-topic-removeMany.ts +12 -4
  97. package/src/modules/localtask/actions/localtask-update.ts +22 -4
  98. package/src/modules/localtask/actions/localtask-wait.ts +13 -4
  99. package/src/modules/localtask/actions/task-move.ts +21 -4
  100. package/src/modules/repos/actions/board-add.ts +10 -4
  101. package/src/modules/repos/actions/board-assign.ts +12 -4
  102. package/src/modules/repos/actions/board-export.ts +9 -4
  103. package/src/modules/repos/actions/board-get.ts +9 -4
  104. package/src/modules/repos/actions/board-import.ts +9 -4
  105. package/src/modules/repos/actions/board-list.ts +9 -4
  106. package/src/modules/repos/actions/board-note.ts +11 -4
  107. package/src/modules/repos/actions/board-prefix.ts +10 -4
  108. package/src/modules/repos/actions/board-prune.ts +11 -4
  109. package/src/modules/repos/actions/board-rekey.ts +11 -4
  110. package/src/modules/repos/actions/board-remove.ts +9 -4
  111. package/src/modules/repos/actions/board-update.ts +11 -4
  112. package/src/modules/repos/actions/repo-add.ts +17 -4
  113. package/src/modules/repos/actions/repo-bind-topics.ts +10 -4
  114. package/src/modules/repos/actions/repo-bind.ts +12 -4
  115. package/src/modules/repos/actions/repo-clone.ts +14 -4
  116. package/src/modules/repos/actions/repo-detect.ts +9 -4
  117. package/src/modules/repos/actions/repo-doc-add.ts +15 -4
  118. package/src/modules/repos/actions/repo-doc-list.ts +9 -4
  119. package/src/modules/repos/actions/repo-doc-remove.ts +10 -4
  120. package/src/modules/repos/actions/repo-export.ts +12 -4
  121. package/src/modules/repos/actions/repo-get.ts +9 -4
  122. package/src/modules/repos/actions/repo-import-diff.ts +10 -4
  123. package/src/modules/repos/actions/repo-import.ts +14 -4
  124. package/src/modules/repos/actions/repo-key-migrate.ts +9 -4
  125. package/src/modules/repos/actions/repo-key-refresh.ts +11 -4
  126. package/src/modules/repos/actions/repo-key-set.ts +11 -4
  127. package/src/modules/repos/actions/repo-knowledge.ts +10 -4
  128. package/src/modules/repos/actions/repo-list.ts +9 -4
  129. package/src/modules/repos/actions/repo-open.ts +9 -4
  130. package/src/modules/repos/actions/repo-ref-add.ts +13 -4
  131. package/src/modules/repos/actions/repo-ref-backfill.ts +10 -4
  132. package/src/modules/repos/actions/repo-ref-check.ts +9 -4
  133. package/src/modules/repos/actions/repo-ref-clone.ts +16 -4
  134. package/src/modules/repos/actions/repo-ref-note.ts +12 -4
  135. package/src/modules/repos/actions/repo-ref-of.ts +9 -4
  136. package/src/modules/repos/actions/repo-ref-sync.ts +10 -4
  137. package/src/modules/repos/actions/repo-remote-check.ts +10 -4
  138. package/src/modules/repos/actions/repo-remote-list.ts +9 -4
  139. package/src/modules/repos/actions/repo-remote-pick.ts +10 -4
  140. package/src/modules/repos/actions/repo-remote.ts +11 -4
  141. package/src/modules/repos/actions/repo-remove.ts +9 -4
  142. package/src/modules/repos/actions/repo-scan.ts +11 -4
  143. package/src/modules/repos/actions/repo-update.ts +21 -4
  144. package/src/modules/repos/service/bind-topics.ts +8 -18
  145. package/src/modules/repos/service.ts +1 -1
  146. package/src/modules/repos/transfer/export.ts +4 -1
  147. package/src/modules/setting/actions/setting-get.ts +9 -4
  148. package/src/modules/setting/actions/setting-set.ts +12 -4
  149. package/src/modules/system/actions/bootstrap.ts +7 -4
  150. package/src/modules/system/actions/health.ts +6 -3
  151. package/src/modules/system/actions/routes.ts +11 -3
  152. package/src/modules/system/routes.ts +1 -1
  153. package/src/modules/tasktool/actions/timegoal-check.ts +11 -4
  154. package/src/modules/tasktool/actions/timegoal-clear.ts +9 -4
  155. package/src/modules/tasktool/actions/timegoal-list.ts +9 -4
  156. package/src/modules/tasktool/actions/timegoal-log.ts +9 -4
  157. package/src/modules/tasktool/actions/timegoal-prune.ts +9 -4
  158. package/src/modules/tasktool/actions/timegoal-set.ts +11 -4
  159. package/src/modules/tasktool/actions/timegoal-show.ts +10 -4
  160. package/src/modules/tasktool/actions/timegoal-update.ts +11 -4
  161. package/src/modules/tasktool/attach-resource.ts +37 -5
  162. package/src/modules/tasktool/attach-template.ts +45 -4
  163. package/src/modules/tasktool/attach.ts +47 -3
  164. package/src/modules/tasktool/doc-inline.ts +54 -29
  165. package/src/modules/templates/actions/templates-add.ts +17 -4
  166. package/src/modules/templates/actions/templates-default.ts +13 -4
  167. package/src/modules/templates/actions/templates-list.ts +11 -4
  168. package/src/modules/templates/actions/templates-remove.ts +9 -4
  169. package/src/modules/templates/actions/templates-update.ts +15 -4
  170. package/src/modules/todo/actions/group-add.ts +10 -4
  171. package/src/modules/todo/actions/group-current.ts +9 -4
  172. package/src/modules/todo/actions/group-get.ts +9 -4
  173. package/src/modules/todo/actions/group-list.ts +9 -4
  174. package/src/modules/todo/actions/group-members.ts +9 -4
  175. package/src/modules/todo/actions/group-remove.ts +9 -4
  176. package/src/modules/todo/actions/group-update.ts +11 -4
  177. package/src/modules/todo/actions/group-use.ts +9 -4
  178. package/src/modules/todo/actions/prompt-get.ts +10 -4
  179. package/src/modules/todo/actions/prompt-remove.ts +10 -4
  180. package/src/modules/todo/actions/prompt-set.ts +11 -4
  181. package/src/modules/todo/actions/todo-add.ts +11 -4
  182. package/src/modules/todo/actions/todo-archive.ts +10 -4
  183. package/src/modules/todo/actions/todo-attach.ts +17 -4
  184. package/src/modules/todo/actions/todo-attachments.ts +12 -4
  185. package/src/modules/todo/actions/todo-done.ts +13 -4
  186. package/src/modules/todo/actions/todo-freeze.ts +12 -4
  187. package/src/modules/todo/actions/todo-get.ts +12 -4
  188. package/src/modules/todo/actions/todo-list.ts +11 -4
  189. package/src/modules/todo/actions/todo-remove.ts +12 -4
  190. package/src/modules/todo/actions/todo-unfreeze.ts +12 -4
  191. package/src/modules/todo/actions/todo-update.ts +15 -4
  192. package/src/modules/todo/actions/topic-add.ts +10 -4
  193. package/src/modules/todo/actions/topic-list.ts +9 -4
  194. package/src/modules/todo/actions/topic-remove.ts +10 -4
  195. package/src/runtime/action-decorator.ts +2 -2
  196. package/src/runtime/codegen.ts +26 -41
  197. package/src/runtime/registry.ts +2 -2
  198. package/src/shared/prompt-blocks.ts +6 -1
  199. package/src/web/frontend/api/cli-tree.json +47 -2
  200. package/src/web/frontend/api/client.generated.ts +424 -536
  201. package/src/web/frontend/components/md/attach-area.tsx +58 -3
  202. package/src/web/frontend/components/md/attach-common.ts +2 -2
  203. package/src/web/frontend/modules/md/attach-mention.ts +6 -1
  204. package/src/web/frontend/modules/md/styles/chrome.css +25 -0
  205. package/src/web/frontend/page/cloud/api.ts +99 -0
  206. package/src/web/frontend/page/cloud/index.tsx +13 -32
  207. package/src/web/frontend/page/dag/api.ts +20 -0
  208. package/src/web/frontend/page/dag/index.tsx +2 -5
  209. package/src/web/frontend/page/dir/api.ts +140 -0
  210. package/src/web/frontend/page/dir/index.tsx +37 -57
  211. package/src/web/frontend/page/dir/task-actions.ts +39 -59
  212. package/src/web/frontend/page/dir/task-chain.ts +2 -2
  213. package/src/web/frontend/page/dir/task-dock-panel.tsx +87 -2
  214. package/src/web/frontend/page/dir/task-feedback.ts +19 -23
  215. package/src/web/frontend/page/dir/task-goal.ts +3 -3
  216. package/src/web/frontend/page/dir/task-status-bar.tsx +14 -1
  217. package/src/web/frontend/page/dir/task.tsx +5 -3
  218. package/src/web/frontend/page/doc/api.ts +82 -0
  219. package/src/web/frontend/page/doc/index.tsx +45 -47
  220. package/src/web/frontend/page/group/api.ts +24 -0
  221. package/src/web/frontend/page/group/index.tsx +7 -16
  222. package/src/web/frontend/page/overview/api.ts +16 -0
  223. package/src/web/frontend/page/overview/index.tsx +2 -2
  224. package/src/web/frontend/page/progress/api.ts +20 -0
  225. package/src/web/frontend/page/progress/index.tsx +3 -6
  226. package/src/web/frontend/page/refs/api.ts +14 -0
  227. package/src/web/frontend/page/refs/index.tsx +2 -4
  228. package/src/web/frontend/page/repos/api.ts +197 -0
  229. package/src/web/frontend/page/repos/bind-modals.tsx +4 -7
  230. package/src/web/frontend/page/repos/board-admin.tsx +6 -6
  231. package/src/web/frontend/page/repos/doc-search-modal.tsx +11 -4
  232. package/src/web/frontend/page/repos/index.tsx +10 -14
  233. package/src/web/frontend/page/repos/pending-section.tsx +7 -13
  234. package/src/web/frontend/page/repos/ref-panel.tsx +9 -14
  235. package/src/web/frontend/page/repos/remote-modal.tsx +4 -28
  236. package/src/web/frontend/page/repos/repo-form-modal.tsx +4 -4
  237. package/src/web/frontend/page/settings/api.ts +29 -0
  238. package/src/web/frontend/page/settings/index.tsx +3 -3
  239. package/src/web/frontend/page/settings/prompt-templates-section.tsx +4 -4
  240. package/src/web/frontend/page/settings/sidebar-section.tsx +2 -2
  241. package/src/web/public/assets/Introduction-BDS09bo3.js +6 -0
  242. package/src/web/public/assets/{bar-B9WWmCpt.js → bar-DBtVMtRi.js} +1 -1
  243. package/src/web/public/assets/cloud-0AcS7Mtd.js +3 -0
  244. package/src/web/public/assets/{composer-panel-ByezS8Xv.js → composer-panel-D624x9uT.js} +1 -1
  245. package/src/web/public/assets/dag-Ca-wjIxQ.js +1 -0
  246. package/src/web/public/assets/{deleted-panel-BcbtctNF.js → deleted-panel-BeyVhrAI.js} +1 -1
  247. package/src/web/public/assets/dir-CYGqeYZU.js +5 -0
  248. package/src/web/public/assets/group-B5cZqWIt.js +2 -0
  249. package/src/web/public/assets/{index-D8MvtVAm.js → index-BLEuH6mL.js} +2 -2
  250. package/src/web/public/assets/{index-DP3qBv1o.css → index-ChWwzUrF.css} +1 -1
  251. package/src/web/public/assets/{md-history-BqZvzWiD.js → md-history-Bpyib4z4.js} +3 -3
  252. package/src/web/public/assets/overview-DrsWuDVi.js +1 -0
  253. package/src/web/public/assets/progress-CdhFz0Lz.js +3 -0
  254. package/src/web/public/assets/{prompt-blocks-BovFd039.js → prompt-blocks-CO8msDuJ.js} +1 -1
  255. package/src/web/public/assets/refs-DMVuOOK9.js +1 -0
  256. package/src/web/public/assets/repos-C5OwK72H.js +15 -0
  257. package/src/web/public/assets/{route-crumb-CWVu80du.js → route-crumb-6q3rIB-_.js} +1 -1
  258. package/src/web/public/assets/settings-BH_l1Yek.js +1 -0
  259. package/src/web/public/assets/{status-tag-DRl9E2Os.js → status-tag-BD6cdnyb.js} +1 -1
  260. package/src/web/public/assets/task-B7AjuMiC.js +11 -0
  261. package/src/web/public/assets/task-utils-BNFx9yag.js +12 -0
  262. package/src/web/public/assets/{templates-Df__0k-F.js → templates-G7kHB-xI.js} +1 -1
  263. package/src/web/public/assets/tool-bar-DIXBM0wv.js +1 -0
  264. package/src/web/public/index.html +2 -2
  265. package/src/modules/auth/schemas.ts +0 -27
  266. package/src/modules/bundled/schemas.ts +0 -32
  267. package/src/modules/db/schemas.ts +0 -27
  268. package/src/modules/docs/schemas.ts +0 -107
  269. package/src/modules/file/schemas.ts +0 -61
  270. package/src/modules/localtask/schemas.ts +0 -310
  271. package/src/modules/repos/schemas.ts +0 -310
  272. package/src/modules/setting/schemas.ts +0 -18
  273. package/src/modules/system/schemas.ts +0 -30
  274. package/src/modules/tasktool/schemas.ts +0 -52
  275. package/src/modules/templates/schemas.ts +0 -50
  276. package/src/modules/todo/schemas.ts +0 -177
  277. package/src/web/public/assets/Introduction-aQCeCLrV.js +0 -6
  278. package/src/web/public/assets/cloud-C4b8SU7C.js +0 -3
  279. package/src/web/public/assets/dag-jvrjx4i7.js +0 -1
  280. package/src/web/public/assets/dir-B82XBb1J.js +0 -5
  281. package/src/web/public/assets/group-BPUOO_QM.js +0 -2
  282. package/src/web/public/assets/overview-DMihuyzh.js +0 -1
  283. package/src/web/public/assets/progress-D-rMgz3w.js +0 -3
  284. package/src/web/public/assets/refs-D21jmrn6.js +0 -1
  285. package/src/web/public/assets/repos-B94tMDGs.js +0 -15
  286. package/src/web/public/assets/settings-DgTt4JG5.js +0 -1
  287. package/src/web/public/assets/task-B2x5GoV3.js +0 -11
  288. package/src/web/public/assets/task-utils-By8gLpHY.js +0 -12
  289. package/src/web/public/assets/tool-bar-Cv7f6p4v.js +0 -1
@@ -0,0 +1,249 @@
1
+ // mdfile(本地 md 文件指针)的登记、读取与校验。
2
+ //
3
+ // 语义(docs/decisions/2026-11-12-refs-body-in-db.md §5 / O7 + 2026-11 收口):
4
+ // · 字节留在用户磁盘原地:storage='external',库里只存 abs_path + hash;
5
+ // · 登记时算 sha256 指纹;读取时现读并核对指纹,不一致只报 stale,**不自动改库**;
6
+ // · 文件不存在只标 missing_at,不软删、不删行、不碰外部文件;
7
+ // · 相对链接锚点 = 登记时文件所在目录(anchor_dir),不是任何「文档根」;
8
+ // · `NX_KV_DOCS_DIR` 只是 mdfile 的默认附件目录,不承载文档正文——
9
+ // mdfile 是**唯一**允许直接读该目录(以及任意外部 md)的入口。
10
+ //
11
+ // 本模块只碰 attachments 一张表与文件系统,不做业务编排(宿主编排在各模块里)。
12
+ import { createHash } from 'node:crypto';
13
+ import { existsSync, readFileSync, statSync } from 'node:fs';
14
+ import { basename, dirname } from 'node:path';
15
+ import { mdfileAttachmentId, normalizeMdfilePath } from './ids.js';
16
+ import { badInput, conflict } from '../errors.js';
17
+
18
+ const MD_EXT_RE = /\.(md|markdown)$/i;
19
+
20
+ /** 外部 md 必须走文本对面,MIME 固定(不靠扩展名猜,也不影响渲染分支)。 */
21
+ export const MDFILE_MIME = 'text/markdown; charset=utf-8';
22
+
23
+ function sha256(buf: Buffer): string {
24
+ return createHash('sha256').update(buf).digest('hex');
25
+ }
26
+
27
+ export interface MdfileRecord {
28
+ id: string;
29
+ name: string;
30
+ absPath: string;
31
+ anchorDir: string;
32
+ size: number;
33
+ hash: string;
34
+ missingAt: number | null;
35
+ lastSeenAt: number | null;
36
+ }
37
+
38
+ export interface RegisterMdfileInput {
39
+ /** 文件路径(相对路径按当前工作目录解析) */
40
+ path?: unknown;
41
+ /** 显示名(默认取文件名) */
42
+ name?: unknown;
43
+ atMs?: number;
44
+ }
45
+
46
+ /**
47
+ * 登记一个本地 md 文件(幂等:同一路径重登记只刷新指纹与时间)。
48
+ * 默认目录(NX_KV_DOCS_DIR)只约束「放哪」,不限制登记:
49
+ * 该目录下的文件同样只能经 attach 访问,所以登记一律放行。
50
+ * @throws 路径非法 / 非 .md / 文件不存在
51
+ */
52
+ export function registerMdfile(conn: any, {
53
+ path, name = '', atMs = Date.now(),
54
+ }: RegisterMdfileInput = {}): MdfileRecord {
55
+ const absPath = normalizeMdfilePath(path);
56
+ if (!absPath) throw badInput('mdfile 需要文件路径');
57
+ if (!MD_EXT_RE.test(absPath)) {
58
+ throw badInput(`mdfile 只接受 .md / .markdown 文件: ${absPath}`);
59
+ }
60
+ if (!existsSync(absPath)) throw badInput(`文件不存在: ${absPath}`);
61
+ const st = statSync(absPath);
62
+ if (!st.isFile()) throw badInput(`不是普通文件: ${absPath}`);
63
+
64
+ const buf = readFileSync(absPath);
65
+ const hash = sha256(buf);
66
+ const size = buf.length;
67
+ const anchorDir = dirname(absPath);
68
+ let id = mdfileAttachmentId(absPath);
69
+ const displayName = String(name || '').trim() || basename(absPath);
70
+
71
+ const cur = conn.get('SELECT id, kind FROM attachments WHERE id = :id', { id });
72
+ if (cur && cur.kind !== 'mdfile') {
73
+ throw conflict(`附件 id 冲突:${id} 已被 kind=${cur.kind} 占用,无法登记为 mdfile`);
74
+ }
75
+
76
+ const upsert = (targetId: string): void => conn.run(
77
+ `INSERT INTO attachments
78
+ (id, kind, name, local_path, url, mime, size, hash, storage, group_id,
79
+ target_kind, target_key, target_seq, dedupe_key, meta,
80
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at)
81
+ VALUES (:id, 'mdfile', :name, '', '', :mime, :size, :hash, 'external', 0,
82
+ '', '', NULL, '', '{}',
83
+ :absPath, :anchorDir, NULL, :at, NULL, :at, :at)
84
+ ON CONFLICT(id) DO UPDATE SET
85
+ name = excluded.name,
86
+ mime = excluded.mime,
87
+ size = excluded.size,
88
+ hash = excluded.hash,
89
+ storage = 'external',
90
+ abs_path = excluded.abs_path,
91
+ anchor_dir = excluded.anchor_dir,
92
+ missing_at = NULL,
93
+ last_seen_at = excluded.last_seen_at,
94
+ deleted_at = NULL,
95
+ updated_at = excluded.updated_at`,
96
+ {
97
+ id: targetId,
98
+ name: displayName,
99
+ mime: MDFILE_MIME,
100
+ size,
101
+ hash,
102
+ absPath,
103
+ anchorDir,
104
+ at: atMs,
105
+ }
106
+ );
107
+
108
+ try {
109
+ upsert(id);
110
+ } catch (e) {
111
+ // Windows:同一文件用不同大小写登记 → 不同 id 撞 ux_attachments_mdfile_path;
112
+ // 回落到已登记行,避免出现两条同文件记录。
113
+ const other = conn.get(
114
+ "SELECT id FROM attachments WHERE kind = 'mdfile' AND deleted_at IS NULL AND abs_path = :absPath COLLATE NOCASE",
115
+ { absPath }
116
+ );
117
+ if (!other) throw e;
118
+ id = String(other.id);
119
+ upsert(id);
120
+ }
121
+
122
+ const saved = conn.get('SELECT id, name, abs_path, anchor_dir FROM attachments WHERE id = :id', { id });
123
+ return {
124
+ id,
125
+ name: String(saved?.name || displayName),
126
+ absPath: String(saved?.abs_path || absPath),
127
+ anchorDir: String(saved?.anchor_dir || anchorDir),
128
+ size,
129
+ hash,
130
+ missingAt: null,
131
+ lastSeenAt: atMs,
132
+ };
133
+ }
134
+
135
+ export interface ReadMdfileResult {
136
+ id: string;
137
+ name: string;
138
+ absPath: string;
139
+ anchorDir: string;
140
+ body: string;
141
+ size: number;
142
+ /** 现读指纹(文件缺失时为空) */
143
+ hash: string;
144
+ /** 文件内容与登记时的指纹不一致(不自动改库) */
145
+ stale: boolean;
146
+ /** 文件当前不存在(已标 missing_at) */
147
+ missing: boolean;
148
+ missingAt: number | null;
149
+ }
150
+
151
+ /**
152
+ * 读一个 mdfile 的正文并做读时校验。
153
+ * - 文件不存在:标 `missing_at`,返回空正文 + `missing: true`(不软删行);
154
+ * - 指纹不一致:返回正文 + `stale: true`(不自动改库);
155
+ * - 正常:刷新 `last_seen_at` 并清掉 `missing_at`。
156
+ * @returns null = 没有这条 mdfile(或已软删)
157
+ */
158
+ export function readMdfile(conn: any, id: unknown, { atMs = Date.now() }: { atMs?: number } = {}): ReadMdfileResult | null {
159
+ const row = conn.get(
160
+ "SELECT * FROM attachments WHERE id = :id AND kind = 'mdfile' AND deleted_at IS NULL",
161
+ { id: String(id || '') }
162
+ );
163
+ if (!row) return null;
164
+
165
+ const absPath = String(row.abs_path || '');
166
+ const name = String(row.name || '') || (absPath ? basename(absPath) : String(row.id));
167
+ const anchorDir = String(row.anchor_dir || '') || (absPath ? dirname(absPath) : '');
168
+ const recorded = String(row.hash || '');
169
+
170
+ if (!absPath || !existsSync(absPath)) {
171
+ conn.run('UPDATE attachments SET missing_at = :at WHERE id = :id', { at: atMs, id: row.id });
172
+ return {
173
+ id: String(row.id), name, absPath, anchorDir, body: '',
174
+ size: Number(row.size) || 0, hash: '', stale: false, missing: true, missingAt: atMs,
175
+ };
176
+ }
177
+
178
+ const buf = readFileSync(absPath);
179
+ const hash = sha256(buf);
180
+ const stale = !!recorded && recorded !== hash;
181
+ // 文件存在就清 missing_at:stale 只表达指纹漂移,两种状态互不排斥。
182
+ conn.run('UPDATE attachments SET last_seen_at = :at, missing_at = NULL WHERE id = :id', {
183
+ at: atMs,
184
+ id: row.id,
185
+ });
186
+ return {
187
+ id: String(row.id),
188
+ name,
189
+ absPath,
190
+ anchorDir,
191
+ body: buf.toString('utf8'),
192
+ size: buf.length,
193
+ hash,
194
+ stale,
195
+ missing: false,
196
+ missingAt: null,
197
+ };
198
+ }
199
+
200
+ export interface MdfileRow extends MdfileRecord {
201
+ /** 台账上的失效时间(不代表此刻一定不存在;以 readMdfile 为准) */
202
+ missing: boolean;
203
+ }
204
+
205
+ /** 按绝对路径找已登记的 mdfile(Windows 大小写不敏感);没有则 null。 */
206
+ export function findMdfileByPath(conn: any, absPath: unknown): MdfileRecord | null {
207
+ const abs = normalizeMdfilePath(absPath);
208
+ if (!abs) return null;
209
+ const row = conn.get(
210
+ `SELECT id, name, abs_path, anchor_dir, size, hash, missing_at, last_seen_at
211
+ FROM attachments
212
+ WHERE kind = 'mdfile' AND deleted_at IS NULL AND abs_path = :abs COLLATE NOCASE`,
213
+ { abs }
214
+ );
215
+ if (!row) return null;
216
+ return {
217
+ id: String(row.id),
218
+ name: String(row.name || ''),
219
+ absPath: String(row.abs_path || ''),
220
+ anchorDir: String(row.anchor_dir || ''),
221
+ size: Number(row.size) || 0,
222
+ hash: String(row.hash || ''),
223
+ missingAt: row.missing_at === null || row.missing_at === undefined ? null : Number(row.missing_at),
224
+ lastSeenAt: row.last_seen_at === null || row.last_seen_at === undefined ? null : Number(row.last_seen_at),
225
+ };
226
+ }
227
+
228
+ /** 列出全部已登记的 mdfile(含已失标的,供巡检)。 */
229
+ export function listMdfiles(conn: any, { missingOnly = false }: { missingOnly?: boolean } = {}): MdfileRow[] {
230
+ const rows: any[] = conn.all(
231
+ `SELECT id, name, abs_path, anchor_dir, size, hash, missing_at, last_seen_at
232
+ FROM attachments
233
+ WHERE kind = 'mdfile' AND deleted_at IS NULL
234
+ ORDER BY updated_at DESC, id`
235
+ );
236
+ return rows
237
+ .map((r: any): MdfileRow => ({
238
+ id: String(r.id),
239
+ name: String(r.name || ''),
240
+ absPath: String(r.abs_path || ''),
241
+ anchorDir: String(r.anchor_dir || ''),
242
+ size: Number(r.size) || 0,
243
+ hash: String(r.hash || ''),
244
+ missingAt: r.missing_at === null || r.missing_at === undefined ? null : Number(r.missing_at),
245
+ lastSeenAt: r.last_seen_at === null || r.last_seen_at === undefined ? null : Number(r.last_seen_at),
246
+ missing: r.missing_at !== null && r.missing_at !== undefined,
247
+ }))
248
+ .filter((r) => !missingOnly || r.missing);
249
+ }
@@ -5,7 +5,9 @@ import { join, resolve } from 'node:path';
5
5
  import { metaOf } from './ids.js';
6
6
 
7
7
  const ATT_SELECT = `SELECT id, kind, name, local_path, url, mime, size, hash, storage, group_id,
8
- target_kind, target_key, target_seq, meta, deleted_at, created_at, updated_at
8
+ target_kind, target_key, target_seq, meta,
9
+ abs_path, anchor_dir, missing_at, last_seen_at,
10
+ deleted_at, created_at, updated_at
9
11
  FROM attachments`;
10
12
 
11
13
  export interface AttachmentView {
@@ -24,6 +26,11 @@ export interface AttachmentView {
24
26
  /** 行值可能为 NULL(SQLite),消费方各自 Number() 归一,故这里不做窄化。 */
25
27
  targetSeq: any;
26
28
  meta: Record<string, unknown>;
29
+ /** mdfile 专用:规范化绝对路径 / 相对链接锚点(其它 kind 为空) */
30
+ absPath: string;
31
+ anchorDir: string;
32
+ missingAt: number | null;
33
+ lastSeenAt: number | null;
27
34
  deletedAt: string | null;
28
35
  createdAt: number;
29
36
  updatedAt: number;
@@ -51,6 +58,10 @@ function rowView(row: any): AttachmentView {
51
58
  targetKey: row.target_key,
52
59
  targetSeq: row.target_seq === null || row.target_seq === undefined ? null : Number(row.target_seq),
53
60
  meta: metaOf(row),
61
+ absPath: String(row.abs_path || ''),
62
+ anchorDir: String(row.anchor_dir || ''),
63
+ missingAt: row.missing_at === null || row.missing_at === undefined ? null : Number(row.missing_at),
64
+ lastSeenAt: row.last_seen_at === null || row.last_seen_at === undefined ? null : Number(row.last_seen_at),
54
65
  deletedAt: row.deleted_at,
55
66
  createdAt: Number(row.created_at) || 0,
56
67
  updatedAt: Number(row.updated_at) || 0,
@@ -67,6 +78,7 @@ export function listTaskAttachments(conn: any, taskId?: string | number): Linked
67
78
  .all(
68
79
  `SELECT a.id, a.kind, a.name, a.local_path, a.url, a.mime, a.size, a.hash, a.storage,
69
80
  a.group_id, a.target_kind, a.target_key, a.target_seq, a.meta,
81
+ a.abs_path, a.anchor_dir, a.missing_at, a.last_seen_at,
70
82
  a.deleted_at, a.created_at, a.updated_at, ta.role, ta.position, ta.note
71
83
  FROM task_attach ta JOIN attachments a ON a.id = ta.attachment_id
72
84
  WHERE ta.task_id = :id AND a.deleted_at IS NULL
@@ -93,6 +105,7 @@ export function listRefAttachments(conn: any, refId?: string | number): LinkedAt
93
105
  .all(
94
106
  `SELECT a.id, a.kind, a.name, a.local_path, a.url, a.mime, a.size, a.hash, a.storage,
95
107
  a.group_id, a.target_kind, a.target_key, a.target_seq, a.meta,
108
+ a.abs_path, a.anchor_dir, a.missing_at, a.last_seen_at,
96
109
  a.deleted_at, a.created_at, a.updated_at, ra.role, ra.position, ra.note
97
110
  FROM ref_attach ra JOIN attachments a ON a.id = ra.attachment_id
98
111
  WHERE ra.ref_id = :id AND a.deleted_at IS NULL
@@ -236,6 +236,28 @@ export function ensureRefAttachment(conn: any, { refId, atMs = Date.now(), name
236
236
  });
237
237
  }
238
238
 
239
+ /**
240
+ * mdfile 是「已登记的外部文件指针」:正文引用只能命中已有行,**不能凭 id 造行**
241
+ * (没有路径就无从读取)。未登记时返回 null,由调用方报「先 docs attach --mdfile」。
242
+ */
243
+ export function ensureMdfileAttachment(conn: any, { id, name = '', atMs = Date.now() }: {
244
+ id?: string | null; name?: string; atMs?: number;
245
+ } = {}): string | null {
246
+ const attId = String(id || '').trim();
247
+ if (!attId) return null;
248
+ const row = conn.get(
249
+ "SELECT id, name FROM attachments WHERE id = :id AND kind = 'mdfile' AND deleted_at IS NULL",
250
+ { id: attId }
251
+ );
252
+ if (!row) return null;
253
+ if (name && !row.name) {
254
+ conn.run('UPDATE attachments SET name = :name, updated_at = :at WHERE id = :id', {
255
+ id: attId, name: String(name), at: atMs,
256
+ });
257
+ }
258
+ return attId;
259
+ }
260
+
239
261
  /** 一条正文引用 → 资源 id(无法解析到真实目标的返回 null)。 */
240
262
  export function ensureAttachment(conn: any, ref: AttachmentRef | null | undefined, { atMs = Date.now() }: {
241
263
  atMs?: number;
@@ -256,5 +278,6 @@ export function ensureAttachment(conn: any, ref: AttachmentRef | null | undefine
256
278
  return ensureTaskAttachment(conn, { taskId: ref.targetTaskId, name: ref.name, atMs });
257
279
  }
258
280
  if (ref.kind === 'ref') return ensureRefAttachment(conn, { refId: ref.targetRefId, name: ref.name, atMs });
281
+ if (ref.kind === 'mdfile') return ensureMdfileAttachment(conn, { id: ref.targetMdfileId, name: ref.name, atMs });
259
282
  return null;
260
283
  }
@@ -15,6 +15,8 @@
15
15
  // 本文件只是对外入口:公共 API 全部 re-export,import 路径不变。
16
16
  export {
17
17
  isFileId,
18
+ mdfileAttachmentId,
19
+ normalizeMdfilePath,
18
20
  parseAttachmentRefs,
19
21
  refAttachmentId,
20
22
  refIdFor,
@@ -23,11 +25,20 @@ export {
23
25
  } from './attachmentdb/ids.js';
24
26
  export {
25
27
  ensureAttachment,
28
+ ensureMdfileAttachment,
26
29
  ensureRefAttachment,
27
30
  ensureTaskAttachment,
28
31
  ensureUrlAttachment,
29
32
  upsertFileAttachment,
30
33
  } from './attachmentdb/resources.js';
34
+ export {
35
+ MDFILE_MIME,
36
+ listMdfiles,
37
+ findMdfileByPath,
38
+ readMdfile,
39
+ registerMdfile,
40
+ } from './attachmentdb/mdfile.js';
41
+ export type { MdfileRecord, MdfileRow, ReadMdfileResult } from './attachmentdb/mdfile.js';
31
42
  export {
32
43
  linkAttachment,
33
44
  syncRefAttachments,
@@ -35,6 +46,17 @@ export {
35
46
  unlinkAttachment,
36
47
  updateAttachmentNote,
37
48
  } from './attachmentdb/relations.js';
49
+ export {
50
+ getRefBody,
51
+ isShellRel,
52
+ listRefDocs,
53
+ noBodyReason,
54
+ refDocByRel,
55
+ refIdByRel,
56
+ relKindOf,
57
+ upsertRefBody,
58
+ } from './attachmentdb/bodies.js';
59
+ export type { RefBodyRow, RefDocRow, RelKind } from './attachmentdb/bodies.js';
38
60
  export {
39
61
  ensureDocRef,
40
62
  forgetDocRef,
@@ -25,7 +25,7 @@
25
25
  // **绝不自动建表** —— 那会把别人的库就地改成我们的结构。
26
26
  import { existsSync, rmSync, unlinkSync, writeFileSync, renameSync, readFileSync } from 'node:fs';
27
27
  import { join } from 'node:path';
28
- import { attachmentsRootFromEnv, dbPathFromEnv, backupsDirFromEnv, defaultStoreTarget } from '../paths.js';
28
+ import { attachmentsRootFromEnv, dbPathFromEnv, backupsDirFromEnv, defaultStoreTarget, mdfileDirFromEnv } from '../paths.js';
29
29
  import {
30
30
  archiveAttachmentManifests,
31
31
  syncDocAttachmentIndex,
@@ -185,10 +185,10 @@ export function bootstrap(
185
185
  ): BootstrapResult {
186
186
  const before = inspectStore(db);
187
187
  const legacy = scanLegacy(appDir);
188
- // 迁移上下文:002 的 apply 需要把 manifest.json / docs 树 / 任务正文一起迁走。
188
+ // 迁移上下文:002 的 apply 需要把 manifest.json / docs 旧目录 / 任务正文一起迁走。
189
189
  const migrationContext = {
190
190
  attachmentsRoot: attachmentsRootFromEnv(),
191
- docsRoot: process.env.NX_KV_DOCS_DIR || join(appDir, 'docs'),
191
+ docsDir: mdfileDirFromEnv(appDir),
192
192
  atMs,
193
193
  };
194
194
  const result: BootstrapResult = {
@@ -231,7 +231,7 @@ export function bootstrap(
231
231
  // 导入之后立刻把正文引用/文档资源落关系表(002 的 apply 在导入之前跑,
232
232
  // 这里补一次,保证「导入的历史任务」也不是只有正文里的 fileId 字符串)。
233
233
  syncTaskAttachmentIndex(conn, { atMs });
234
- syncDocAttachmentIndex(conn, { docsRoot: migrationContext.docsRoot, atMs });
234
+ syncDocAttachmentIndex(conn, { docsDir: migrationContext.docsDir, atMs });
235
235
  // 内置模板 seed 放在导入**之后**:legacy templates.json 里用户改过的
236
236
  // builtin 行先落库,seed 的 INSERT OR IGNORE 就不会用出厂文本盖掉它。
237
237
  seedBuiltinTemplates(conn, atMs);
@@ -300,7 +300,7 @@ export function bootstrap(
300
300
  const out = importLegacy(conn, { appDir, atMs });
301
301
  // 导入的数据在本事务里落资源关系;失败则整段回滚,不会留下半套关系。
302
302
  syncTaskAttachmentIndex(conn, { atMs });
303
- syncDocAttachmentIndex(conn, { docsRoot: migrationContext.docsRoot, atMs });
303
+ syncDocAttachmentIndex(conn, { docsDir: migrationContext.docsDir, atMs });
304
304
  return out;
305
305
  },
306
306
  { db, mode: 'IMMEDIATE', rollback: dryRun }
@@ -3,7 +3,8 @@
3
3
  // 2. `docs/` 树扫描(未被任何 DocRef 指到的 → state='orphan')
4
4
  // `ref_relations` 本轮留空。
5
5
  import { existsSync, readdirSync } from 'node:fs';
6
- import { join, sep } from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ import { isAbsolute, join, resolve, sep } from 'node:path';
7
8
  import { groupKeyOf } from '../../keys.js';
8
9
  import { refIdOf } from './data.js';
9
10
  import type { ImportReport } from './data.js';
@@ -23,10 +24,17 @@ function toPosix(rel: string): string {
23
24
  return rel.split(sep).join('/');
24
25
  }
25
26
 
26
- /** 递归收集 docs 树里的 .md(返回 POSIX 相对路径)。 */
27
- export function listDocFiles(docsRoot: string): string[] {
27
+ /** 外部绝对路径 / URL → v6 的逻辑 rel(与 v6-data 同一口径)。 */
28
+ function externalRel(locator: string): string {
29
+ let seed = isAbsolute(locator) ? toPosix(resolve(locator)) : locator;
30
+ if (/^[A-Z]:/.test(seed)) seed = seed.charAt(0).toLowerCase() + seed.slice(1);
31
+ return 'external/' + createHash('sha1').update(seed, 'utf8').digest('hex').slice(0, 16);
32
+ }
33
+
34
+ /** 递归收集旧文档目录里的 .md(返回 POSIX 相对路径)。**仅 legacy JSON 导入用。** */
35
+ export function listDocFiles(docsDir: string): string[] {
28
36
  const out: string[] = [];
29
- if (!docsRoot || !existsSync(docsRoot)) return out;
37
+ if (!docsDir || !existsSync(docsDir)) return out;
30
38
  const walk = (dir: string, prefix: string): void => {
31
39
  let entries: Dirent[] = [];
32
40
  try {
@@ -40,7 +48,7 @@ export function listDocFiles(docsRoot: string): string[] {
40
48
  else if (/\.md$/i.test(e.name)) out.push(prefix ? `${prefix}/${e.name}` : e.name);
41
49
  }
42
50
  };
43
- walk(docsRoot, '');
51
+ walk(docsDir, '');
44
52
  return out.map(toPosix).sort();
45
53
  }
46
54
 
@@ -53,18 +61,18 @@ export function listDocFiles(docsRoot: string): string[] {
53
61
  export function importRefs(
54
62
  db: DbApi,
55
63
  reposData: any,
56
- docsRoot: string,
64
+ docsDir: string,
57
65
  atMs: number,
58
66
  report: ImportReport
59
67
  ): void {
60
- const files = listDocFiles(docsRoot);
68
+ const files = listDocFiles(docsDir);
61
69
  const fileSet = new Set(files);
62
70
  for (const locator of files) {
63
71
  const r = db.run(
64
- `INSERT INTO refs (id, type, locator, state, version, deleted_at, created_at, updated_at)
65
- VALUES (:id, 'md', :locator, 'orphan', 0, NULL, :at, :at)
72
+ `INSERT INTO refs (id, type, rel, locator, state, version, deleted_at, created_at, updated_at)
73
+ VALUES (:id, 'md', :rel, :locator, 'orphan', 0, NULL, :at, :at)
66
74
  ON CONFLICT(id) DO NOTHING`,
67
- { id: refIdOf(locator), locator, at: atMs }
75
+ { id: refIdOf(locator), rel: locator, locator, at: atMs }
68
76
  );
69
77
  if (Number(r.changes) > 0) report.imported.refs += 1;
70
78
  }
@@ -152,10 +160,16 @@ export function importRefs(
152
160
  if (d.extPath) {
153
161
  // 外部路径(Obsidian 等):只在库里留地址,字节在库外
154
162
  db.run(
155
- `INSERT INTO refs (id, type, locator, state, version, deleted_at, created_at, updated_at)
156
- VALUES (:id, :type, :locator, '', 0, NULL, :at, :at)
163
+ `INSERT INTO refs (id, type, rel, locator, origin, state, version, deleted_at, created_at, updated_at)
164
+ VALUES (:id, :type, :rel, :locator, 'external', '', 0, NULL, :at, :at)
157
165
  ON CONFLICT(id) DO NOTHING`,
158
- { id: refIdOf(d.locator), type: d.type, locator: d.locator, at: atMs }
166
+ {
167
+ id: refIdOf(d.locator),
168
+ type: d.type,
169
+ rel: externalRel(d.locator),
170
+ locator: d.locator,
171
+ at: atMs,
172
+ }
159
173
  );
160
174
  report.imported.refs += 1;
161
175
  } else if (!fileSet.has(d.locator)) {
@@ -5,6 +5,8 @@
5
5
  // v2.sql = 1 → 2 的跃迁脚本(建 attachments/task_attach/ref_attach、删两张空表)
6
6
  // v3.sql = 2 → 3 的跃迁脚本(templates 加 scope/origin_topic)
7
7
  // v4.sql = 3 → 4 的跃迁脚本(建 group_refs:参考仓库绑定升到组级)
8
+ // v5.sql = 4 → 5 的跃迁脚本(重建 attachments:新增 mdfile / external / 路径列)
9
+ // v6.sql = 5 → 6 的跃迁脚本(refs.rel/origin/body_bytes + ref_bodies + ref_attach 增 source)
8
10
  // index.js= 边映射表 + 路径规划(本文件)
9
11
  //
10
12
  // 规则(与 docs/decisions/versions 下的版本说明同一口径):
@@ -14,6 +16,7 @@
14
16
  import { readFileSync } from 'node:fs';
15
17
  import { migrateAttachments } from './v2-data.js';
16
18
  import { migrateGroupRefs } from './v4-data.js';
19
+ import { migrateRefsBodies } from './v6-data.js';
17
20
  import { CURRENT_SCHEMA_VERSION } from '../version.js';
18
21
  import type { DbApi } from '../driver.js';
19
22
 
@@ -50,6 +53,8 @@ export const DIRECT_EDGES: MigrationStep[] = [
50
53
  { from: 1, to: 2, file: 'v2.sql', title: '附件/资源统一模型', apply: migrateAttachments },
51
54
  { from: 2, to: 3, file: 'v3.sql', title: '模板可见域(scope/origin_topic)' },
52
55
  { from: 3, to: 4, file: 'v4.sql', title: '参考仓库绑定升到组级(group_refs)', apply: migrateGroupRefs },
56
+ { from: 4, to: 5, file: 'v5.sql', title: '附件新增 mdfile(本地 md 指针)' },
57
+ { from: 5, to: 6, file: 'v6.sql', title: 'refs 正文入库(rel / ref_bodies / source)', apply: migrateRefsBodies },
53
58
  ];
54
59
 
55
60
  // 人读版本说明(docs/decisions 是决策的唯一权威位置,里面对应一份 date 化的 .md)
@@ -58,6 +63,8 @@ export const VERSION_NOTES = {
58
63
  2: 'docs/decisions/versions/2026-11-08-v2.md',
59
64
  3: 'docs/decisions/versions/2026-11-09-v3.md',
60
65
  4: 'docs/decisions/versions/2026-11-09-v4.md',
66
+ 5: 'docs/decisions/versions/2026-11-12-v5.md',
67
+ 6: 'docs/decisions/versions/2026-11-12-v6.md',
61
68
  };
62
69
 
63
70
  const keyOf = (from: number, to: number): string => `${from}->${to}`;
@@ -23,7 +23,7 @@ import type { DbApi } from '../driver.js';
23
23
  /** 迁移上下文(bootstrap 传入)。 */
24
24
  export interface V2Context {
25
25
  attachmentsRoot?: string;
26
- docsRoot?: string;
26
+ docsDir?: string;
27
27
  atMs?: number;
28
28
  }
29
29
 
@@ -162,16 +162,16 @@ function normalizeRefs(conn: DbApi, atMs: number): void {
162
162
  }
163
163
 
164
164
  /**
165
- * step 002 的 apply。`ctx` 由 bootstrap 传入:{ attachmentsRoot, docsRoot, atMs }。
165
+ * step 002 的 apply。`ctx` 由 bootstrap 传入:{ attachmentsRoot, docsDir, atMs }。
166
166
  */
167
167
  export function migrateAttachments(
168
168
  conn: DbApi,
169
- { attachmentsRoot, docsRoot, atMs = Date.now() }: V2Context = {}
169
+ { attachmentsRoot, docsDir, atMs = Date.now() }: V2Context = {}
170
170
  ): AttachmentsMigrationResult {
171
171
  const overrideDir = String(readSettingRaw(conn, 'app.attachmentsDir') || '');
172
172
  const manifestCount = migrateManifests(conn, { attachmentsRoot, overrideDir, atMs });
173
173
  normalizeRefs(conn, atMs);
174
174
  const taskEdges = syncTaskAttachmentIndex(conn, { atMs });
175
- const docEdges = syncDocAttachmentIndex(conn, { docsRoot, atMs });
175
+ const docEdges = syncDocAttachmentIndex(conn, { docsDir, atMs });
176
176
  return { manifestCount, taskEdges, docEdges };
177
177
  }
@@ -0,0 +1,100 @@
1
+ -- schema v5:附件新增 kind='mdfile'(本地 md 文件指针)与 storage='external'
2
+ --
3
+ -- 设计口径(2026-11-12,docs/decisions/2026-11-12-refs-body-in-db.md §2.4 / §5):
4
+ -- · mdfile 是**独立资源类型**,不是 kind='file' + MIME 判定:
5
+ -- 字节留在用户磁盘原地(storage='external'),库里只存路径指针 + 内容指纹;
6
+ -- web 端按 kind 分支走 md 渲染,不走通用文件的下载/预览路径。
7
+ -- · 身份沿用 att_<kind>_<hash16> 家族:id = att_mdfile_<sha1(规范化绝对路径)>。
8
+ -- · 新增列只服务 mdfile,其它 kind 一律留空/0(无默认值以外的语义)。
9
+ --
10
+ -- SQLite 不能 ALTER 既有的 CHECK 约束 → 只能 12-step 重建 attachments。
11
+ --
12
+ -- **DROP TABLE 会级联删子表**(实测,不是理论风险):外键启用时 DROP TABLE 会做
13
+ -- 一次隐式 DELETE,并立刻触发子表的 ON DELETE CASCADE;`defer_foreign_keys`
14
+ -- 只推迟约束**校验**,不推迟级联**动作**。所以关系表必须先快照、重建后回填,
15
+ -- 否则 task_attach / ref_attach 会被静默清空(且 foreign_key_check 仍为干净)。
16
+ -- 回填用显式列名,不依赖列序。
17
+ --
18
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
19
+ PRAGMA defer_foreign_keys = ON;
20
+
21
+ -- 关系表快照(TEMP,随连接生命周期;迁移结束立即 DROP)
22
+ CREATE TEMP TABLE _v5_task_attach AS
23
+ SELECT task_id, attachment_id, role, position, note, created_at FROM task_attach;
24
+ CREATE TEMP TABLE _v5_ref_attach AS
25
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM ref_attach;
26
+
27
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
28
+ CREATE TABLE attachments_new (
29
+ id TEXT PRIMARY KEY,
30
+ kind TEXT NOT NULL CHECK (kind IN ('file', 'url', 'task', 'ref', 'mdfile')),
31
+ name TEXT NOT NULL DEFAULT '',
32
+ -- 本机/云端文件本轮实际可读的绝对路径;云端缓存未下载时为空。
33
+ -- mdfile 不用这一列(见 abs_path),保持为空。
34
+ local_path TEXT NOT NULL DEFAULT '',
35
+ url TEXT NOT NULL DEFAULT '',
36
+ mime TEXT NOT NULL DEFAULT '',
37
+ size INTEGER NOT NULL DEFAULT 0 CHECK (size >= 0),
38
+ hash TEXT NOT NULL DEFAULT '',
39
+ -- file 的存储位置:local=本机附件仓,cloud=云端镜像缓存;
40
+ -- mdfile 固定 external(字节不在库里)。
41
+ storage TEXT NOT NULL DEFAULT '' CHECK (storage IN ('', 'local', 'cloud', 'external')),
42
+ group_id INTEGER NOT NULL DEFAULT 0,
43
+ -- 内部资源的定位信息(kind=task/ref 时有值;file/url/mdfile 为空)
44
+ target_kind TEXT NOT NULL DEFAULT '' CHECK (target_kind IN ('', 'task', 'ref')),
45
+ target_key TEXT NOT NULL DEFAULT '',
46
+ target_seq INTEGER,
47
+ dedupe_key TEXT NOT NULL DEFAULT '',
48
+ meta TEXT NOT NULL DEFAULT '{}'
49
+ CHECK (json_valid(meta) AND json_type(meta) = 'object'),
50
+ -- mdfile 专用(其它 kind 留空/0)
51
+ abs_path TEXT NOT NULL DEFAULT '', -- 规范化后的绝对路径(唯一性基础)
52
+ anchor_dir TEXT NOT NULL DEFAULT '', -- 相对链接锚点 = 登记时文件所在目录
53
+ missing_at INTEGER, -- 上次确认文件不存在的时间(不软删)
54
+ last_seen_at INTEGER, -- 上次读到时文件仍在(且 hash 未变)的时间
55
+ deleted_at INTEGER,
56
+ created_at INTEGER NOT NULL,
57
+ updated_at INTEGER NOT NULL
58
+ );
59
+
60
+ INSERT INTO attachments_new (
61
+ id, kind, name, local_path, url, mime, size, hash, storage,
62
+ group_id, target_kind, target_key, target_seq, dedupe_key, meta,
63
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at
64
+ )
65
+ SELECT id, kind, name, local_path, url, mime, size, hash, storage,
66
+ group_id, target_kind, target_key, target_seq, dedupe_key, meta,
67
+ '', '', NULL, NULL, deleted_at, created_at, updated_at
68
+ FROM attachments;
69
+
70
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
71
+ DROP TABLE attachments;
72
+
73
+ ALTER TABLE attachments_new RENAME TO attachments;
74
+
75
+ -- v2 的 3 个索引原样重建(DROP TABLE 时随表消失)
76
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_dedupe
77
+ ON attachments (dedupe_key)
78
+ WHERE dedupe_key <> '' AND deleted_at IS NULL;
79
+ CREATE INDEX IF NOT EXISTS ix_attachments_kind
80
+ ON attachments (kind, deleted_at);
81
+ CREATE INDEX IF NOT EXISTS ix_attachments_target
82
+ ON attachments (target_kind, target_key, target_seq);
83
+ CREATE INDEX IF NOT EXISTS ix_attachments_group
84
+ ON attachments (storage, group_id, deleted_at);
85
+
86
+ -- mdfile 路径唯一:同一外部文件只登记一行(软删后允许重新登记)
87
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_mdfile_path
88
+ ON attachments (abs_path COLLATE NOCASE)
89
+ WHERE kind = 'mdfile' AND deleted_at IS NULL;
90
+
91
+ -- 回填关系表(DROP 时已被 CASCADE 删掉,此处按快照逐行恢复;显式列名)
92
+ INSERT INTO task_attach (task_id, attachment_id, role, position, note, created_at)
93
+ SELECT task_id, attachment_id, role, position, note, created_at FROM _v5_task_attach;
94
+ INSERT INTO ref_attach (ref_id, attachment_id, role, position, note, created_at)
95
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM _v5_ref_attach;
96
+
97
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
98
+ DROP TABLE _v5_task_attach;
99
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
100
+ DROP TABLE _v5_ref_attach;