nx-kv 0.48.2 → 0.50.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 (309) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +103 -216
  3. package/assets/groups.json +1 -1
  4. package/assets/kv-get/SKILL.md +1 -1
  5. package/assets/kv-get/references/localget.md +2 -2
  6. package/assets/kv-get/references/timegoal-workflow.md +3 -3
  7. package/assets/kv-get/references/timegoal.md +1 -1
  8. package/assets/kv-get/references/wait-workflow.md +2 -3
  9. package/assets/kv-get/references/waitloop.md +3 -3
  10. package/assets/kv-repo/SKILL.md +1 -1
  11. package/assets/kv-submit/SKILL.md +3 -3
  12. package/assets/nx-kv/SKILL.md +111 -76
  13. package/assets/nx-kv/references/agent-workflow.md +58 -47
  14. package/assets/nx-kv/references/localtask-commands.md +179 -0
  15. package/package.json +3 -4
  16. package/src/core/attachmentdb/bodies.ts +193 -0
  17. package/src/core/attachmentdb/docs.ts +158 -33
  18. package/src/core/attachmentdb/ids.ts +27 -1
  19. package/src/core/attachmentdb/mdfile.ts +249 -0
  20. package/src/core/attachmentdb/query.ts +14 -1
  21. package/src/core/attachmentdb/resources.ts +28 -2
  22. package/src/core/attachmentdb.ts +27 -0
  23. package/src/core/config.ts +13 -133
  24. package/src/core/db/bootstrap.ts +5 -5
  25. package/src/core/db/import-json/refs.ts +27 -13
  26. package/src/core/db/migrations/index.ts +9 -0
  27. package/src/core/db/migrations/v2-data.ts +4 -4
  28. package/src/core/db/migrations/v5.sql +100 -0
  29. package/src/core/db/migrations/v6-data.ts +261 -0
  30. package/src/core/db/migrations/v6.sql +67 -0
  31. package/src/core/db/migrations/v7.sql +8 -0
  32. package/src/core/db/seed-templates.ts +3 -1
  33. package/src/core/db/version.ts +12 -1
  34. package/src/core/filekind.ts +95 -0
  35. package/src/core/instruction-template.ts +6 -4
  36. package/src/core/localatt.ts +3 -6
  37. package/src/core/paths.ts +11 -1
  38. package/src/index.ts +0 -2
  39. package/src/modules/docs/actions/_manifest.generated.ts +18 -0
  40. package/src/modules/docs/actions/doc-attach.ts +2 -1
  41. package/src/modules/docs/actions/doc-link-file.ts +28 -0
  42. package/src/modules/docs/actions/doc-mdfile.ts +28 -0
  43. package/src/modules/docs/actions/doc-mdfiles.ts +29 -0
  44. package/src/modules/docs/actions/doc-ref.ts +36 -0
  45. package/src/modules/docs/actions/doc-unbind.ts +34 -0
  46. package/src/modules/docs/actions/doc-update.ts +3 -2
  47. package/src/modules/docs/actions/docs-bind.ts +1 -1
  48. package/src/modules/docs/actions/docs-bindings.ts +108 -0
  49. package/src/modules/docs/actions/docs-notebind.ts +1 -1
  50. package/src/modules/docs/attach.ts +16 -3
  51. package/src/modules/docs/bound-docs.ts +74 -0
  52. package/src/modules/docs/docref.ts +18 -3
  53. package/src/modules/docs/knowledge-md.ts +51 -0
  54. package/src/modules/docs/knowledge.ts +112 -112
  55. package/src/modules/docs/links.ts +7 -1
  56. package/src/modules/docs/mdfile.ts +24 -0
  57. package/src/modules/docs/paths.ts +6 -9
  58. package/src/modules/docs/ref-sync.ts +166 -0
  59. package/src/modules/docs/refs.ts +16 -5
  60. package/src/modules/docs/render.ts +33 -15
  61. package/src/modules/docs/seed.ts +1 -1
  62. package/src/modules/docs/service.ts +300 -30
  63. package/src/modules/docs/store.ts +147 -74
  64. package/src/modules/file/actions/_manifest.generated.ts +0 -9
  65. package/src/modules/file/actions/file-content.ts +3 -4
  66. package/src/modules/file/actions/file-get.ts +2 -3
  67. package/src/modules/file/actions/file-upload.ts +1 -4
  68. package/src/modules/file/service.ts +52 -253
  69. package/src/modules/localtask/action-render.ts +5 -5
  70. package/src/modules/localtask/actions/_manifest.generated.ts +0 -6
  71. package/src/modules/localtask/actions/localtask-attach.ts +4 -2
  72. package/src/modules/localtask/actions/localtask-cancelMany.ts +1 -1
  73. package/src/modules/localtask/actions/localtask-closeMany.ts +4 -3
  74. package/src/modules/localtask/actions/localtask-get.ts +1 -1
  75. package/src/modules/localtask/repo/tasks.ts +12 -6
  76. package/src/modules/localtask/service.ts +0 -2
  77. package/src/modules/localtask/task-ops.ts +4 -4
  78. package/src/modules/localtask/task-remove.ts +33 -16
  79. package/src/modules/localtask/task-templates.ts +2 -3
  80. package/src/modules/localtask/task-view.ts +2 -2
  81. package/src/modules/repos/actions/_manifest.generated.ts +0 -3
  82. package/src/modules/repos/actions/repo-update.ts +2 -4
  83. package/src/modules/repos/cli/render.ts +0 -15
  84. package/src/modules/repos/service/bind-topics.ts +8 -18
  85. package/src/modules/repos/service.ts +1 -1
  86. package/src/modules/repos/transfer/export.ts +4 -1
  87. package/src/modules/setting/actions/setting-set.ts +0 -2
  88. package/src/modules/setting/service.ts +6 -25
  89. package/src/modules/system/actions/bootstrap.ts +2 -31
  90. package/src/modules/system/actions/health.ts +4 -31
  91. package/src/modules/system/routes.ts +1 -1
  92. package/src/modules/tasktool/attach-resource.ts +68 -42
  93. package/src/modules/tasktool/attach-template.ts +73 -54
  94. package/src/modules/tasktool/attach.ts +98 -71
  95. package/src/modules/tasktool/delivery-template.ts +14 -4
  96. package/src/modules/tasktool/doc-inline.ts +63 -29
  97. package/src/modules/tasktool/get.ts +1 -1
  98. package/src/modules/tasktool/groupctx.ts +19 -11
  99. package/src/modules/tasktool/plugins/waitgoal-config.ts +24 -55
  100. package/src/modules/tasktool/plugins/waitgoal.ts +0 -2
  101. package/src/modules/tasktool/preview.ts +2 -3
  102. package/src/modules/tasktool/wait.ts +6 -9
  103. package/src/runtime/cli.ts +3 -15
  104. package/src/runtime/container.ts +1 -5
  105. package/src/runtime/help.ts +1 -4
  106. package/src/runtime/registry.ts +0 -6
  107. package/src/shared/prompt-blocks.ts +37 -33
  108. package/src/shared/task-status.ts +3 -3
  109. package/src/web/frontend/App.tsx +3 -3
  110. package/src/web/frontend/api/cli-tree.json +115 -608
  111. package/src/web/frontend/api/client.generated.ts +88 -401
  112. package/src/web/frontend/components/Introduction/index.tsx +26 -14
  113. package/src/web/frontend/components/Introduction/rail.tsx +28 -3
  114. package/src/web/frontend/components/Introduction/style.css +3 -33
  115. package/src/web/frontend/components/Introduction/use-intro.ts +0 -80
  116. package/src/web/frontend/components/{cloud → attach}/upload.ts +7 -20
  117. package/src/web/frontend/components/bindings/bind-tags.tsx +183 -0
  118. package/src/web/frontend/components/doc/doc-head.tsx +29 -26
  119. package/src/web/frontend/components/icons.tsx +0 -1
  120. package/src/web/frontend/components/layout/crumbs.ts +0 -2
  121. package/src/web/frontend/components/md/ack-rail.tsx +10 -142
  122. package/src/web/frontend/components/md/attach-area.tsx +64 -9
  123. package/src/web/frontend/components/md/attach-common.ts +8 -3
  124. package/src/web/frontend/components/md/attach-modal.tsx +22 -17
  125. package/src/web/frontend/components/md/attach-picker.tsx +2 -2
  126. package/src/web/frontend/components/md/attachments.ts +2 -3
  127. package/src/web/frontend/components/popup/dismiss.ts +1 -1
  128. package/src/web/frontend/components/repos/get-loop-modal.tsx +20 -207
  129. package/src/web/frontend/components/sidebar/index.tsx +32 -6
  130. package/src/web/frontend/components/sidebar/model.ts +71 -0
  131. package/src/web/frontend/components/sidebar/task-children.tsx +41 -20
  132. package/src/web/frontend/components/status-tag/model.ts +1 -1
  133. package/src/web/frontend/components/task-panel/index.tsx +4 -1
  134. package/src/web/frontend/components/task-panel/task-row.tsx +2 -2
  135. package/src/web/frontend/components/tool-acts/modules.ts +0 -3
  136. package/src/web/frontend/components/use-rail-drag.ts +177 -0
  137. package/src/web/frontend/modules/board/ack-rail-pos.ts +17 -7
  138. package/src/web/frontend/modules/board/board-view.ts +2 -2
  139. package/src/web/frontend/modules/board/task-search.ts +81 -0
  140. package/src/web/frontend/modules/md/attach-mention.ts +6 -1
  141. package/src/web/frontend/modules/md/doc-bus.ts +22 -0
  142. package/src/web/frontend/modules/md/md-render.ts +9 -2
  143. package/src/web/frontend/modules/md/styles/chrome.css +25 -0
  144. package/src/web/frontend/modules/md/styles/docs.css +32 -21
  145. package/src/web/frontend/modules/md/styles/shell.css +1 -10
  146. package/src/web/frontend/page/dir/api.ts +7 -0
  147. package/src/web/frontend/page/dir/index.tsx +24 -58
  148. package/src/web/frontend/page/dir/landing.tsx +85 -72
  149. package/src/web/frontend/page/dir/task-actions.ts +17 -5
  150. package/src/web/frontend/page/dir/task-dock-panel.tsx +87 -2
  151. package/src/web/frontend/page/dir/task-dock.ts +21 -10
  152. package/src/web/frontend/page/dir/task-goal.ts +2 -2
  153. package/src/web/frontend/page/dir/task-status-bar.tsx +14 -1
  154. package/src/web/frontend/page/dir/task.tsx +5 -3
  155. package/src/web/frontend/page/doc/api.ts +71 -5
  156. package/src/web/frontend/page/doc/bindings.tsx +240 -0
  157. package/src/web/frontend/page/doc/doc-dock.tsx +159 -0
  158. package/src/web/frontend/page/doc/index.tsx +131 -212
  159. package/src/web/frontend/page/doc/use-wiki-nav.ts +101 -0
  160. package/src/web/frontend/page/group/index.tsx +61 -87
  161. package/src/web/frontend/page/overview/index.tsx +1 -2
  162. package/src/web/frontend/page/refs/api.ts +60 -8
  163. package/src/web/frontend/page/refs/index.tsx +177 -90
  164. package/src/web/frontend/page/refs/style.css +45 -2
  165. package/src/web/frontend/page/repos/doc-search-modal.tsx +7 -0
  166. package/src/web/frontend/page/repos/index.tsx +21 -60
  167. package/src/web/frontend/page/repos/repo-table.tsx +85 -77
  168. package/src/web/frontend/page/settings/index.tsx +3 -27
  169. package/src/web/frontend/page/settings/prompt-template-params.ts +18 -28
  170. package/src/web/frontend/panels.tsx +52 -6
  171. package/src/web/frontend/registry.ts +1 -2
  172. package/src/web/frontend/routes/index.ts +1 -2
  173. package/src/web/frontend/routes/static.ts +2 -3
  174. package/src/web/frontend/store.tsx +1 -8
  175. package/src/web/frontend/style.css +1 -0
  176. package/src/web/frontend/styles/base.css +0 -17
  177. package/src/web/frontend/styles/bindings.css +75 -0
  178. package/src/web/frontend/styles/buttons-cards.css +0 -72
  179. package/src/web/frontend/styles/repos-admin.css +7 -5
  180. package/src/web/frontend/styles-v2/dir.css +1 -9
  181. package/src/web/frontend/styles-v2/shell.css +0 -2
  182. package/src/web/frontend/styles-v2/sidebar.css +12 -0
  183. package/src/web/frontend/styles-v2/views.css +22 -102
  184. package/src/web/frontend/workspace/areas.ts +0 -2
  185. package/src/web/public/assets/Introduction-CohW6Xit.js +6 -0
  186. package/src/web/public/assets/Introduction-Iuxssa-b.css +1 -0
  187. package/src/web/public/assets/app-context-BgpTewyA.js +1 -0
  188. package/src/web/public/assets/{bar-B52NTf_v.js → bar-C2mfoqmj.js} +1 -1
  189. package/src/web/public/assets/{board-view-DABoVkaA.js → board-view-aAIEbSQi.js} +1 -1
  190. package/src/web/public/assets/button-xyR2UROd.js +1 -0
  191. package/src/web/public/assets/composer-launch-eTktHT_f.js +1 -0
  192. package/src/web/public/assets/{composer-panel-DpiU2h50.js → composer-panel-C0OOIXxz.js} +1 -1
  193. package/src/web/public/assets/dag-Gm4RcvEg.js +1 -0
  194. package/src/web/public/assets/dir-PjuMRbWo.js +3 -0
  195. package/src/web/public/assets/group-D94y_Lq6.js +1 -0
  196. package/src/web/public/assets/index-CBJKsJU3.css +1 -0
  197. package/src/web/public/assets/index-Crxdmsux.js +2 -0
  198. package/src/web/public/assets/md-history-CU_1I6ht.js +39 -0
  199. package/src/web/public/assets/{md-parse-b6GY5eBl.js → md-parse-CLyUaUto.js} +1 -1
  200. package/src/web/public/assets/{member-picker-B5I7KuOR.js → member-picker-XT12VRe6.js} +1 -1
  201. package/src/web/public/assets/model-CWJ8_2dN.js +2 -0
  202. package/src/web/public/assets/{overview-B3kHI66i.js → overview-BQm8BLCG.js} +1 -1
  203. package/src/web/public/assets/{progress-CdhFz0Lz.js → progress-CNam3Wuj.js} +2 -2
  204. package/src/web/public/assets/refs-C5idWnUj.css +1 -0
  205. package/src/web/public/assets/refs-ClETk1cj.js +2 -0
  206. package/src/web/public/assets/repos-BioGejZo.js +14 -0
  207. package/src/web/public/assets/route-crumb-Fc68LcQ4.js +1 -0
  208. package/src/web/public/assets/settings-BIzumXLD.js +8 -0
  209. package/src/web/public/assets/status-tag-CBFf_-ae.js +1 -0
  210. package/src/web/public/assets/task-CGmO3I2y.js +11 -0
  211. package/src/web/public/assets/task-row-DRBa11tf.js +1 -0
  212. package/src/web/public/assets/{task-status-DSrx0i66.js → task-status-BHF-y9Aq.js} +2 -1
  213. package/src/web/public/assets/{task-utils-_JAWRAz6.js → task-utils-DjODjVdc.js} +2 -2
  214. package/src/web/public/assets/{templates-CbRyW3PJ.js → templates-j8EzXHXf.js} +1 -1
  215. package/src/web/public/assets/ui-Y0aL-bGk.js +1 -0
  216. package/src/web/public/assets/use-rail-drag-DNfz4Gcx.js +1 -0
  217. package/src/web/public/assets/{workspace-4tw7trV7.js → workspace-D_G-B3TX.js} +4 -4
  218. package/src/web/public/index.html +9 -9
  219. package/assets/nx-kv/references/todo-commands.md +0 -269
  220. package/src/core/attachstore.ts +0 -360
  221. package/src/core/fileapi.ts +0 -267
  222. package/src/core/kvapi.ts +0 -237
  223. package/src/modules/auth/actions/_manifest.generated.ts +0 -26
  224. package/src/modules/auth/actions/auth-login.ts +0 -31
  225. package/src/modules/auth/actions/auth-logout.ts +0 -33
  226. package/src/modules/auth/actions/auth-me.ts +0 -33
  227. package/src/modules/auth/actions/auth-status.ts +0 -41
  228. package/src/modules/auth/index.ts +0 -24
  229. package/src/modules/auth/support.ts +0 -28
  230. package/src/modules/file/actions/file-list.ts +0 -31
  231. package/src/modules/file/actions/file-remove.ts +0 -31
  232. package/src/modules/file/actions/file-sync.ts +0 -33
  233. package/src/modules/localtask/actions/localtask-importRemote.ts +0 -51
  234. package/src/modules/localtask/actions/task-move.ts +0 -67
  235. package/src/modules/localtask/move-prims.ts +0 -170
  236. package/src/modules/localtask/move.ts +0 -174
  237. package/src/modules/localtask/remote-import.ts +0 -159
  238. package/src/modules/repos/actions/repo-ref-backfill.ts +0 -33
  239. package/src/modules/repos/ref-backfill.ts +0 -219
  240. package/src/modules/todo/actions/_manifest.generated.ts +0 -89
  241. package/src/modules/todo/actions/group-add.ts +0 -34
  242. package/src/modules/todo/actions/group-current.ts +0 -36
  243. package/src/modules/todo/actions/group-get.ts +0 -43
  244. package/src/modules/todo/actions/group-list.ts +0 -41
  245. package/src/modules/todo/actions/group-members.ts +0 -41
  246. package/src/modules/todo/actions/group-remove.ts +0 -44
  247. package/src/modules/todo/actions/group-update.ts +0 -37
  248. package/src/modules/todo/actions/group-use.ts +0 -43
  249. package/src/modules/todo/actions/prompt-get.ts +0 -31
  250. package/src/modules/todo/actions/prompt-remove.ts +0 -31
  251. package/src/modules/todo/actions/prompt-set.ts +0 -32
  252. package/src/modules/todo/actions/todo-add.ts +0 -34
  253. package/src/modules/todo/actions/todo-archive.ts +0 -33
  254. package/src/modules/todo/actions/todo-attach.ts +0 -37
  255. package/src/modules/todo/actions/todo-attachments.ts +0 -33
  256. package/src/modules/todo/actions/todo-done.ts +0 -33
  257. package/src/modules/todo/actions/todo-freeze.ts +0 -32
  258. package/src/modules/todo/actions/todo-get.ts +0 -33
  259. package/src/modules/todo/actions/todo-list.ts +0 -32
  260. package/src/modules/todo/actions/todo-remove.ts +0 -32
  261. package/src/modules/todo/actions/todo-unfreeze.ts +0 -34
  262. package/src/modules/todo/actions/todo-update.ts +0 -42
  263. package/src/modules/todo/actions/topic-add.ts +0 -31
  264. package/src/modules/todo/actions/topic-list.ts +0 -35
  265. package/src/modules/todo/actions/topic-remove.ts +0 -36
  266. package/src/modules/todo/attachments.ts +0 -194
  267. package/src/modules/todo/group.ts +0 -207
  268. package/src/modules/todo/index.ts +0 -26
  269. package/src/modules/todo/locate.ts +0 -103
  270. package/src/modules/todo/service.ts +0 -476
  271. package/src/modules/todo/store.ts +0 -176
  272. package/src/modules/todo/support.ts +0 -93
  273. package/src/web/frontend/components/Introduction/docs-modal.tsx +0 -338
  274. package/src/web/frontend/components/cloud/editor.tsx +0 -254
  275. package/src/web/frontend/components/cloud/group-popup.tsx +0 -198
  276. package/src/web/frontend/components/cloud/markdown.tsx +0 -60
  277. package/src/web/frontend/components/migrate/dialog.tsx +0 -120
  278. package/src/web/frontend/components/migrate/undo.tsx +0 -73
  279. package/src/web/frontend/components/migrate/use-move.ts +0 -137
  280. package/src/web/frontend/page/cloud/api.ts +0 -99
  281. package/src/web/frontend/page/cloud/index.tsx +0 -516
  282. package/src/web/frontend/page/dir/deleted-panel.tsx +0 -77
  283. package/src/web/public/assets/Introduction-BcPrmROW.css +0 -1
  284. package/src/web/public/assets/Introduction-Du_dycft.js +0 -6
  285. package/src/web/public/assets/app-context-BASCGAA-.js +0 -1
  286. package/src/web/public/assets/cloud-Droja_aT.js +0 -3
  287. package/src/web/public/assets/composer-launch-mK9Nr6mZ.js +0 -1
  288. package/src/web/public/assets/dag-Ca-wjIxQ.js +0 -1
  289. package/src/web/public/assets/deleted-panel-K9GgfR8t.js +0 -1
  290. package/src/web/public/assets/dir-DacRpcBt.js +0 -5
  291. package/src/web/public/assets/frontmatter-CLLxCmTv.js +0 -2
  292. package/src/web/public/assets/group-TPuU-QVc.js +0 -2
  293. package/src/web/public/assets/index-BkLkooKe.js +0 -2
  294. package/src/web/public/assets/index-DP3qBv1o.css +0 -1
  295. package/src/web/public/assets/md-history-0GBWw4qr.js +0 -39
  296. package/src/web/public/assets/model-Bn2fG6CC.js +0 -2
  297. package/src/web/public/assets/prompt-blocks-BovFd039.js +0 -8
  298. package/src/web/public/assets/refs-BDxfuH6R.js +0 -1
  299. package/src/web/public/assets/refs-CY4i7PoC.css +0 -1
  300. package/src/web/public/assets/repos-C8jRM7wS.js +0 -15
  301. package/src/web/public/assets/repos-ZPiaK93i.css +0 -1
  302. package/src/web/public/assets/route-crumb-QvahotvN.js +0 -1
  303. package/src/web/public/assets/settings-BBcdGLTc.js +0 -1
  304. package/src/web/public/assets/status-tag-BheHByek.js +0 -1
  305. package/src/web/public/assets/task-CUkQaLBZ.js +0 -11
  306. package/src/web/public/assets/tool-bar-BAmT-BI-.js +0 -1
  307. package/src/web/public/assets/upload-BcMhRsMn.js +0 -1
  308. /package/src/web/public/assets/{prompt-blocks-DA4lNJeC.css → button-DA4lNJeC.css} +0 -0
  309. /package/src/web/public/assets/{tool-bar-1h2zairf.css → use-rail-drag-1h2zairf.css} +0 -0
@@ -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,9 @@ 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 },
58
+ { from: 6, to: 7, file: 'v7.sql', title: 'refs 描述字段(desc)' },
53
59
  ];
54
60
 
55
61
  // 人读版本说明(docs/decisions 是决策的唯一权威位置,里面对应一份 date 化的 .md)
@@ -58,6 +64,9 @@ export const VERSION_NOTES = {
58
64
  2: 'docs/decisions/versions/2026-11-08-v2.md',
59
65
  3: 'docs/decisions/versions/2026-11-09-v3.md',
60
66
  4: 'docs/decisions/versions/2026-11-09-v4.md',
67
+ 5: 'docs/decisions/versions/2026-11-12-v5.md',
68
+ 6: 'docs/decisions/versions/2026-11-12-v6.md',
69
+ 7: 'docs/decisions/versions/2026-11-12-v7.md',
61
70
  };
62
71
 
63
72
  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;
@@ -0,0 +1,261 @@
1
+ // schema v5 → v6 的数据迁移(在 v6.sql 的同一个事务里执行)。
2
+ //
3
+ // 口径(2026-11-12 二轮确认,docs/decisions/2026-11-12-refs-body-in-db.md §11):
4
+ // 1. 存量 refs 归位:相对 locator → rel=locator(origin=import);
5
+ // 空 locator → rel=legacy/<id>;绝对路径 / URL → rel=external/<sha1(规范化)>;
6
+ // 2. 盘上 docs 树 31 篇正文 → ref_bodies,逐篇 sha256 回读比对(硬门禁);
7
+ // 3. 外部绝对路径且文件仍在 → 登记 attachments(kind='mdfile') + ref_attach(role='source');
8
+ // 文件不在 → 只留空壳;
9
+ // 4. 盘上无文件的 102 行保持空壳:不软删、不删行、body_bytes=0;
10
+ // 5. 存量 id 一律保留,不按新公式反推(方案 A)。
11
+ //
12
+ // 幂等:归位是 UPDATE、正文是 UPSERT;重复执行不产生新行。
13
+ // 失败:由 migrator 的 step 事务整体回滚,user_version 停在 5。
14
+ import { createHash } from 'node:crypto';
15
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
16
+ import type { Dirent } from 'node:fs';
17
+ import { basename, isAbsolute, join, resolve } from 'node:path';
18
+ import { refIdFor } from '../../attachmentdb/ids.js';
19
+ import { registerMdfile } from '../../attachmentdb/mdfile.js';
20
+ import type { DbApi } from '../driver.js';
21
+
22
+ /** 迁移上下文(bootstrap 传入,与 v2 同一份)。 */
23
+ export interface V6Context {
24
+ docsDir?: string;
25
+ atMs?: number;
26
+ }
27
+
28
+ /** step 006 的结果(落 meta.refs_v6,供迁移后核对与面板诊断)。 */
29
+ export interface RefsBodiesMigrationResult {
30
+ files: number;
31
+ bodies: number;
32
+ legacy: number;
33
+ external: number;
34
+ emptyBody: number;
35
+ relEmpty: number;
36
+ mdfiles: number;
37
+ sources: number;
38
+ warnings: string[];
39
+ }
40
+
41
+ const MD_RE = /\.(md|markdown)$/i;
42
+ const HTTP_RE = /^https?:\/\//i;
43
+
44
+ const sha1 = (s: unknown): string => createHash('sha1').update(String(s), 'utf8').digest('hex');
45
+ const sha256 = (buf: Buffer): string => createHash('sha256').update(buf).digest('hex');
46
+
47
+ /** 地址统一 POSIX(库里的 rel 永远是正斜杠)。 */
48
+ function toPosix(p: string): string {
49
+ return p.replace(/\\/g, '/');
50
+ }
51
+
52
+ /** 绝对路径规范化:解析 `.`/`..`,Windows 盘符小写(大小写不敏感)。 */
53
+ function normAbs(p: string): string {
54
+ let v = toPosix(resolve(p));
55
+ if (/^[A-Z]:/.test(v)) v = v.charAt(0).toLowerCase() + v.slice(1);
56
+ return v;
57
+ }
58
+
59
+ /** p 是否落在 root 内(Windows 大小写不敏感)。 */
60
+ function within(root: string, p: string): boolean {
61
+ if (!root) return false;
62
+ const norm = (v: string): string => toPosix(resolve(v)).replace(/\/+$/, '').toLowerCase();
63
+ const a = norm(root);
64
+ const b = norm(p);
65
+ return b === a || b.startsWith(a + '/');
66
+ }
67
+
68
+ /** docs 树里的 .md(POSIX 相对路径,排序保证可复现)。 */
69
+ function listMd(root: string): string[] {
70
+ const out: string[] = [];
71
+ if (!root || !existsSync(root)) return out;
72
+ const walk = (dir: string, prefix: string): void => {
73
+ let entries: Dirent[] = [];
74
+ try {
75
+ entries = readdirSync(dir, { withFileTypes: true });
76
+ } catch {
77
+ return;
78
+ }
79
+ for (const e of entries) {
80
+ const p = join(dir, e.name);
81
+ if (e.isDirectory()) walk(p, prefix ? `${prefix}/${e.name}` : e.name);
82
+ else if (MD_RE.test(e.name)) out.push(prefix ? `${prefix}/${e.name}` : e.name);
83
+ }
84
+ };
85
+ walk(root, '');
86
+ return out.map(toPosix).sort();
87
+ }
88
+
89
+ /**
90
+ * step 005 → 006 的 apply。`ctx` 由 bootstrap 传入:{ docsDir, atMs }。
91
+ * @throws 归位失败 / 正文回读 sha256 不符 / 计数不一致 → 整步回滚
92
+ */
93
+ export function migrateRefsBodies(conn: DbApi, { docsDir = '', atMs = Date.now() }: V6Context = {}): RefsBodiesMigrationResult {
94
+ const root = String(docsDir || '');
95
+ const warnings: string[] = [];
96
+ const relOwner = new Map<string, string>();
97
+
98
+ /** 给一条 ref 分配唯一 rel(重复时加序号后缀;绝不覆盖别人的 rel)。 */
99
+ const claim = (base: string, id: string): string => {
100
+ const owner = relOwner.get(base);
101
+ if (!owner || owner === id) {
102
+ relOwner.set(base, id);
103
+ return base;
104
+ }
105
+ for (let n = 2; n < 500; n++) {
106
+ const cand = `${base}-${n}`;
107
+ const cur = relOwner.get(cand);
108
+ if (!cur || cur === id) {
109
+ relOwner.set(cand, id);
110
+ return cand;
111
+ }
112
+ }
113
+ const cand = `${base}-${sha1(id).slice(0, 8)}`;
114
+ relOwner.set(cand, id);
115
+ return cand;
116
+ };
117
+
118
+ // ── 1. 存量 refs 归位 ────────────────────────────────────────────────
119
+ const rows: any[] = conn.all('SELECT id, locator FROM refs ORDER BY id');
120
+ for (const row of rows) {
121
+ const id = String(row.id);
122
+ const raw = String(row.locator ?? '').trim();
123
+ const loc = toPosix(raw);
124
+ let rel: string;
125
+ let origin: string;
126
+ let externalAbs = '';
127
+
128
+ if (!loc) {
129
+ rel = claim(`legacy/${id}`, id);
130
+ origin = 'import';
131
+ } else if (HTTP_RE.test(loc)) {
132
+ rel = claim(`external/${sha1(loc).slice(0, 16)}`, id);
133
+ origin = 'external';
134
+ } else if (isAbsolute(raw) || /^[A-Za-z]:[\\/]/.test(raw) || loc.startsWith('//')) {
135
+ const abs = normAbs(raw);
136
+ if (within(root, abs)) {
137
+ // 绝对路径落在文档树内:文件本身由下面的扫盘统一入库,这一行只留空壳,
138
+ // 避免同一文件出现两条正文。
139
+ rel = claim(`legacy/${id}`, id);
140
+ origin = 'import';
141
+ } else {
142
+ rel = claim(`external/${sha1(abs).slice(0, 16)}`, id);
143
+ origin = 'external';
144
+ externalAbs = abs;
145
+ }
146
+ } else {
147
+ rel = claim(loc, id);
148
+ origin = 'import';
149
+ }
150
+
151
+ conn.run('UPDATE refs SET rel = :rel, origin = :origin WHERE id = :id', { rel, origin, id });
152
+
153
+ if (!externalAbs) continue;
154
+ // 外部文件:仍在 → mdfile 指针 + source 边;不在 → 只留空壳
155
+ if (!MD_RE.test(externalAbs) || !existsSync(externalAbs)) {
156
+ warnings.push(`外部文件不在,只留空壳: ${id} -> ${externalAbs}`);
157
+ continue;
158
+ }
159
+ try {
160
+ const rec = registerMdfile(conn, {
161
+ path: externalAbs,
162
+ name: basename(externalAbs),
163
+ atMs,
164
+ });
165
+ conn.run(
166
+ `INSERT OR IGNORE INTO ref_attach (ref_id, attachment_id, role, position, note, created_at)
167
+ VALUES (:ref, :att, 'source', 0, '', :at)`,
168
+ { ref: id, att: rec.id, at: atMs }
169
+ );
170
+ } catch (e: any) {
171
+ // 登记冲突不阻断迁移:refs 行保留为空壳,原因进 meta 供人工核对。
172
+ warnings.push(`mdfile 登记失败(只留空壳): ${id} -> ${externalAbs}: ${e?.message || e}`);
173
+ }
174
+ }
175
+
176
+ // ── 2. 盘上正文入库 + 硬门禁 ─────────────────────────────────────────
177
+ // 口径(2026-11 收口):这些盘上文件入库后**磁盘那份保留、但不再被读取**——
178
+ // 它们不再是文档来源,只是历史残留(CSV 清单标注「已入库、盘上副本仅留档」)。
179
+ // 不要删它们(迁移不回滚用户文件),也不要再从这里读正文。
180
+ const files = listMd(root);
181
+ let bodies = 0;
182
+ for (const rel of files) {
183
+ const abs = join(root, ...rel.split('/'));
184
+ const buf = readFileSync(abs);
185
+ const body = buf.toString('utf8');
186
+ const hash = sha256(buf);
187
+ const id = relOwner.get(rel) || refIdFor(rel);
188
+
189
+ conn.run(
190
+ `INSERT INTO refs (id, type, rel, locator, origin, state, version, deleted_at, created_at, updated_at)
191
+ VALUES (:id, 'md', :rel, :rel, 'import', 'orphan', 0, NULL, :at, :at)
192
+ ON CONFLICT(id) DO UPDATE SET
193
+ rel = CASE WHEN refs.rel = '' THEN excluded.rel ELSE refs.rel END,
194
+ origin = CASE WHEN refs.origin = 'external' THEN refs.origin ELSE 'import' END`,
195
+ { id, rel, at: atMs }
196
+ );
197
+ relOwner.set(rel, id);
198
+
199
+ conn.run(
200
+ `INSERT INTO ref_bodies (ref_id, body, body_bytes, body_hash, updated_at)
201
+ VALUES (:id, :body, :n, :hash, :at)
202
+ ON CONFLICT(ref_id) DO UPDATE SET
203
+ body = excluded.body,
204
+ body_bytes = excluded.body_bytes,
205
+ body_hash = excluded.body_hash,
206
+ updated_at = excluded.updated_at`,
207
+ { id, body, n: buf.length, hash, at: atMs }
208
+ );
209
+
210
+ // 硬门禁:从库里回读正文,重算 sha256,与盘上文件逐篇比对。
211
+ const saved = conn.get('SELECT body FROM ref_bodies WHERE ref_id = :id', { id });
212
+ const reHash = sha256(Buffer.from(String(saved?.body ?? ''), 'utf8'));
213
+ if (!saved || reHash !== hash) {
214
+ throw new Error(
215
+ `v6 正文校验失败(整步回滚):${rel} 盘上 sha256=${hash} 库内=${reHash}`
216
+ );
217
+ }
218
+
219
+ conn.run('UPDATE refs SET rel = :rel, body_bytes = :n WHERE id = :id', {
220
+ rel,
221
+ n: buf.length,
222
+ id,
223
+ });
224
+ bodies += 1;
225
+ }
226
+
227
+ const count = (sql: string): number => Number(conn.get(sql)?.c || 0);
228
+
229
+ // ── 3. 计数校验(归位不许留空;正文数必须等于盘上文件数) ────────────
230
+ const relEmpty = count("SELECT count(*) AS c FROM refs WHERE rel = '' AND deleted_at IS NULL");
231
+ if (relEmpty > 0) {
232
+ throw new Error(`v6 归位失败(整步回滚):仍有 ${relEmpty} 行 rel 为空`);
233
+ }
234
+ if (bodies !== files.length) {
235
+ throw new Error(`v6 正文入库不完整(整步回滚):盘上 ${files.length} 篇,入库 ${bodies} 篇`);
236
+ }
237
+
238
+ const result: RefsBodiesMigrationResult = {
239
+ files: files.length,
240
+ bodies,
241
+ legacy: count("SELECT count(*) AS c FROM refs WHERE rel LIKE 'legacy/%'"),
242
+ external: count("SELECT count(*) AS c FROM refs WHERE origin = 'external'"),
243
+ emptyBody: count(
244
+ `SELECT count(*) AS c FROM refs r
245
+ LEFT JOIN ref_bodies b ON b.ref_id = r.id
246
+ WHERE r.deleted_at IS NULL AND b.ref_id IS NULL`
247
+ ),
248
+ relEmpty,
249
+ mdfiles: count("SELECT count(*) AS c FROM attachments WHERE kind = 'mdfile' AND deleted_at IS NULL"),
250
+ sources: count("SELECT count(*) AS c FROM ref_attach WHERE role = 'source'"),
251
+ warnings,
252
+ };
253
+
254
+ conn.run(
255
+ `INSERT INTO meta (key, value, updated_at) VALUES ('refs_v6', :v, :at)
256
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
257
+ { v: JSON.stringify(result), at: atMs }
258
+ );
259
+
260
+ return result;
261
+ }
@@ -0,0 +1,67 @@
1
+ -- schema v6:refs 从「文档索引」升级为「文档本体」
2
+ --
3
+ -- 设计口径(2026-11-12 二轮确认,docs/decisions/2026-11-12-refs-body-in-db.md §11):
4
+ -- · 正文进 ref_bodies(1:1 挂 refs.id),refs 只留身份与元数据;
5
+ -- · refs 新增 rel(逻辑名,唯一)/ origin / body_bytes;locator 冻结为历史取证列;
6
+ -- · ref_attach 的 role 增 'source':这条 ref 的正文来自某个 mdfile 附件;
7
+ -- · 存量 133 行 id 全部保留(方案 A:ref_<sha1(rel)> 只用于新行)。
8
+ --
9
+ -- refs 用 ALTER 加列、不重建:重建父表会在 DROP 时立刻触发子表
10
+ -- ref_bindings / ref_attach 的 ON DELETE CASCADE(v5 已实测)。
11
+ --
12
+ -- ref_attach 的 CHECK 必须重建表(SQLite 不能 ALTER CHECK)。它没有子表,
13
+ -- 但按同一口径先快照、重建后回填,避免 DROP 期间的外键动作留下空洞。
14
+ --
15
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
16
+ PRAGMA defer_foreign_keys = ON;
17
+
18
+ -- ── refs:身份 + 元数据(正文在 ref_bodies) ────────────────────────────
19
+ ALTER TABLE refs ADD COLUMN rel TEXT NOT NULL DEFAULT '';
20
+ ALTER TABLE refs ADD COLUMN origin TEXT NOT NULL DEFAULT 'own'; -- own | import | external
21
+ ALTER TABLE refs ADD COLUMN body_bytes INTEGER NOT NULL DEFAULT 0;
22
+
23
+ -- rel 是逻辑名,不是路径;空串表示尚未归位(迁移后活动行不再有)
24
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_refs_rel
25
+ ON refs (rel)
26
+ WHERE rel <> '' AND deleted_at IS NULL;
27
+
28
+ -- ── ref_bodies:正文唯一真相 ───────────────────────────────────────────
29
+ CREATE TABLE IF NOT EXISTS ref_bodies (
30
+ ref_id TEXT PRIMARY KEY REFERENCES refs(id) ON DELETE CASCADE,
31
+ body TEXT NOT NULL,
32
+ body_bytes INTEGER NOT NULL CHECK (body_bytes >= 0),
33
+ body_hash TEXT NOT NULL DEFAULT '', -- sha256(body),导入去重与漂移检测
34
+ updated_at INTEGER NOT NULL
35
+ );
36
+
37
+ -- ── ref_attach:role CHECK 增 'source'(关系表快照 → 重建 → 回填) ──────
38
+ CREATE TEMP TABLE _v6_ref_attach AS
39
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM ref_attach;
40
+
41
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
42
+ CREATE TABLE ref_attach_new (
43
+ ref_id TEXT NOT NULL REFERENCES refs(id) ON DELETE CASCADE,
44
+ attachment_id TEXT NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
45
+ role TEXT NOT NULL DEFAULT 'inline'
46
+ CHECK (role IN ('inline', 'attach', 'reference', 'source')),
47
+ position INTEGER NOT NULL DEFAULT 0,
48
+ note TEXT NOT NULL DEFAULT '',
49
+ created_at INTEGER NOT NULL,
50
+ PRIMARY KEY (ref_id, attachment_id)
51
+ );
52
+
53
+ INSERT INTO ref_attach_new (ref_id, attachment_id, role, position, note, created_at)
54
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM _v6_ref_attach;
55
+
56
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
57
+ -- 删除决策:ref_attach 的 role CHECK 需要扩 'source',SQLite 无法 ALTER CHECK,
58
+ -- 只能按快照重建;旧表在回填完成后立即删除,索引随后重建。
59
+ DROP TABLE ref_attach;
60
+ ALTER TABLE ref_attach_new RENAME TO ref_attach;
61
+
62
+ -- v2 的索引原样重建(DROP TABLE 时随表消失)
63
+ CREATE INDEX IF NOT EXISTS ix_ref_attach_att ON ref_attach (attachment_id);
64
+
65
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
66
+ -- 删除决策:TEMP 快照只服务本次重建,回填完成即删(随连接生命周期回收)。
67
+ DROP TABLE _v6_ref_attach;
@@ -0,0 +1,8 @@
1
+ -- schema v7:refs 增加描述字段(desc)
2
+ --
3
+ -- 口径(任务 #97):ref 是 DB 实体(id + desc + 正文 + 归属),不再是实体文件。
4
+ -- desc 是「快速定位」用的短描述,列表与提示词模板都以它为主标签;
5
+ -- 本轮不新增任何路径 / 文件名字段,也不改 ref_bodies / ref_attach。
6
+ --
7
+ -- desc 是 SQL 关键字,DDL 与查询一律加双引号。
8
+ ALTER TABLE refs ADD COLUMN "desc" TEXT NOT NULL DEFAULT '';
@@ -191,7 +191,9 @@ export const BUILTIN_TEMPLATES = Object.freeze([
191
191
  '{{task.text}}',
192
192
  '',
193
193
  '{{#if repo}}📁 项目:{{repo.name}}{{#if repo.desc}} —— {{repo.desc}}{{/if}}{{/if}}',
194
- '{{#each repo.docs}}\n 📄 {{this.path}}{{#if this.tag}} [{{this.tag}}]{{/if}}{{/each}}',
194
+ '{{#each repo.docs}}',
195
+ ' 📄 {{this.desc}}{{#if this.refId}}(nx-kv docs get --ref {{this.refId}}){{/if}}',
196
+ '{{/each}}',
195
197
  ].join('\n'),
196
198
  varsSchema: [],
197
199
  vars: {},
@@ -14,8 +14,19 @@
14
14
  *
15
15
  * v4(2026-11-09):参考仓库绑定从仓库级升到**组级**(group_refs);组的成员仓库
16
16
  * 共享组上的参考仓库,不做继承/覆盖。旧 ext_linked 绑定由 v4-data.js 搬运。
17
+ *
18
+ * v5(2026-11-12):attachments 重建,新增 kind='mdfile'(本地 md 文件指针)与
19
+ * storage='external';新增 abs_path / anchor_dir / missing_at / last_seen_at 四列
20
+ * 与路径部分唯一索引。纯 DDL 迁移,无数据搬运。
21
+ *
22
+ * v6(2026-11-12):refs 升级为「文档本体」——新增 rel(逻辑名,唯一)/ origin /
23
+ * body_bytes;正文进 ref_bodies(1:1,CASCADE);ref_attach 的 role 增 'source'
24
+ * (外部 md 文件同步来源)。盘上 docs 树正文一次性入库,逐篇 sha256 回读比对。
25
+ *
26
+ * v7(2026-11-12):refs 增加 desc(短描述)。ref 不再当实体文件,列表与提示词
27
+ * 模板以 desc 作为快速定位标签;不新增任何路径 / 文件名字段。
17
28
  */
18
- export const CURRENT_SCHEMA_VERSION = 4;
29
+ export const CURRENT_SCHEMA_VERSION = 7;
19
30
 
20
31
  /**
21
32
  * 运行时最低 Node 版本。