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
@@ -1,23 +1,28 @@
1
1
  // 文档模块的业务逻辑:CRUD + 外部写回。
2
2
  //
3
- // 「描述的权威是磁盘上的 .md 文件」——本模块只做这件事:CRUD、绑定、种子、知识聚合。
4
- // 面板编辑(DocPanel)与组详情渲染都从这里取数;`repo knowledge` 在 repos 模块
5
- // (它属于 repo.* 命令族),聚合逻辑在 knowledge.js。
3
+ // 「自有文档的正文权威在 DB」——v6 起正文只存 `ref_bodies`;mdfile 默认目录
4
+ // 只是 mdfile 默认附件目录,不再是文档来源(面板编辑与组详情都从这里取数)。
5
+ // `repo knowledge` 在 repos 模块(它属于 repo.* 命令族),聚合逻辑在 knowledge.js。
6
6
  //
7
7
  // ─── 读写口径(2026-11 任务 #88「简介文档优化」)───────────────────────
8
- // rel: 自有树(~/.nx-kv/docs/)——可读可写可删
8
+ // rel: 自有树(DB 里的逻辑 rel)——可读可写可删,不落盘
9
9
  // path: 外部(Obsidian vault / 任意登记目录)——**登记在册即可写**:
10
10
  // 读侧要求路径在绑定闭包内;写侧再校验一次(闭包 + .md + 非目录),
11
11
  // 等于「文档集里的每一篇都能就地改」,同时不把 PATCH 变成任意文件写入口。
12
12
  // 删除仍不给外部:删除是可恢复性最差的操作,让它回来源做。
13
+ // (外部路径不在 mdfile 默认目录下;后者只允许经 mdfile 附件访问。)
13
14
  import * as paths from './paths.js';
14
15
  import * as store from './store.js';
15
16
  import * as seed from './seed.js';
16
17
  import { reposBridge } from './repos-bridge.js';
17
- import { badInput, blocked } from '../../core/errors.js';
18
+ import { badInput, blocked, notFound } from '../../core/errors.js';
18
19
  import { getDb } from '../../core/db/index.js';
19
20
  import { tx } from '../../core/db/tx.js';
20
- import { ensureDocRef, syncRefAttachments } from '../../core/attachmentdb.js';
21
+ import { ensureDocRef, markRefBound, noBodyReason, putRefBinding, refDocById, syncRefAttachments, upsertRefBody } from '../../core/attachmentdb.js';
22
+ import { refIdFor } from '../../core/attachmentdb/ids.js';
23
+ import { randomUUID } from 'node:crypto';
24
+ import type { RelKind } from '../../core/attachmentdb.js';
25
+ import { syncRefIndex } from './ref-sync.js';
21
26
  import { docTitleFromMd } from '../../shared/doc-title.js';
22
27
  import fsp from 'node:fs/promises';
23
28
  import path from 'node:path';
@@ -35,10 +40,19 @@ async function safeRead(abs: string): Promise<string> {
35
40
  /** docs list 条目。 */
36
41
  export interface DocSummary {
37
42
  docId: string;
43
+ /** refs.id(v7:ref 的稳定地址) */
44
+ refId: string;
38
45
  rel: string;
46
+ /** 短描述(v7):列表主标签 */
47
+ desc: string;
39
48
  name: string;
40
49
  title: string;
41
50
  size: number;
51
+ /** v6:normal | legacy | external | empty(后三类不是正常文档) */
52
+ relKind: RelKind;
53
+ hasBody: boolean;
54
+ missing?: boolean;
55
+ reason?: string;
42
56
  }
43
57
 
44
58
  /** docs list 的出参。 */
@@ -52,16 +66,25 @@ export interface ListDocsResult {
52
66
  /** docs get 的出参(自有/外部/missing/目录四种形态共用)。 */
53
67
  export interface DocGetResult {
54
68
  docId: string;
69
+ /** refs.id(v7:ref 的稳定地址;面板行与模板取用指令都用它) */
70
+ refId?: string;
55
71
  rel?: string;
56
72
  path?: string;
57
73
  title?: string;
58
74
  summary?: string;
75
+ /** 短描述(v7) */
76
+ desc?: string;
77
+ /** 这篇 ref 的归属(ref_bindings;一个 ref 可挂多处) */
78
+ bindings?: Array<{ type: string; repoKey: string; groupKey: string | null; position: number }>;
59
79
  body?: string;
60
80
  missing?: boolean;
61
81
  writable?: boolean;
62
82
  dir?: boolean;
63
83
  files?: string[];
64
84
  external?: boolean;
85
+ /** v6:条目类别;没有正文时与 reason 一起返回 missing 语义 */
86
+ relKind?: RelKind;
87
+ reason?: string;
65
88
  }
66
89
 
67
90
  /** doc add / update 的入参(body-file 只给 CLI)。 */
@@ -70,13 +93,18 @@ export interface DocWriteCtx {
70
93
  rel?: unknown;
71
94
  body?: unknown;
72
95
  bodyFile?: unknown;
96
+ /** v7:短描述(可单独更新,不碰正文) */
97
+ desc?: unknown;
73
98
  }
74
99
 
75
100
  /** doc 写回的出参。 */
76
101
  export interface DocWriteResult {
77
102
  docId: string;
103
+ refId?: string;
78
104
  rel?: string;
79
105
  path?: string;
106
+ /** 短描述(v7) */
107
+ desc?: string;
80
108
  bytes: number;
81
109
  /** 外部绑定写回不产生摘要(summary 只来自自有树 writeBackSummary) */
82
110
  summary?: string | null;
@@ -88,15 +116,22 @@ export interface DocWriteResult {
88
116
  // 树索引(零副作用,不播种——agent/前端拿它当双链解析的数据源)
89
117
  export async function listDocs({ external }: { external?: boolean } = {}): Promise<ListDocsResult> {
90
118
  const docs: DocSummary[] = [];
91
- for (const f of await store.listOwnDocs()) {
119
+ // includeEmpty:历史空壳 / 外部镜像 / 无正文行也要出现在清单里,但必须显式标注,
120
+ // 不能让它们看起来像正常文档(v6 验收项)。
121
+ for (const f of await store.listOwnDocs({ includeEmpty: true })) {
92
122
  // #168:标题口径 = 正文**首行**的 `# 标题`(与文档页/附件清单同一口径)
93
- const title = docTitleFromMd(f.size <= 512 * 1024 ? await safeRead(f.abs) : '');
123
+ const title = f.hasBody ? docTitleFromMd(f.body ?? '') : '';
94
124
  docs.push({
95
125
  docId: paths.ownDocId(f.rel),
126
+ refId: f.id,
96
127
  rel: f.rel,
128
+ desc: f.desc,
97
129
  name: f.rel.replace(/\.md$/i, '').split('/').pop() ?? '',
98
130
  title,
99
131
  size: f.size,
132
+ relKind: f.relKind,
133
+ hasBody: f.hasBody,
134
+ ...(f.hasBody ? {} : { missing: true, reason: noBodyReason(f.relKind) }),
100
135
  });
101
136
  }
102
137
  const out: ListDocsResult = { docs, count: docs.length };
@@ -111,22 +146,93 @@ export async function listDocs({ external }: { external?: boolean } = {}): Promi
111
146
  return out;
112
147
  }
113
148
 
149
+ /** refId 形式的地址:`ref:<id>` 或裸 `ref_<16hex>`(ref 是 DB 实体,地址就是 id)。 */
150
+ const REF_ID_INPUT = /^(?:ref:)?(ref_[0-9a-f]{16})$/i;
151
+
152
+ interface RefIdInput {
153
+ refId: string;
154
+ rel: string;
155
+ externalPath: string;
156
+ desc: string;
157
+ }
158
+
159
+ /** 输入是不是 refId;是则按 refs.id 解析(不回退到路径猜测)。 */
160
+ function resolveRefIdInput(raw: unknown): RefIdInput | null {
161
+ const s = clean(raw);
162
+ const m = REF_ID_INPUT.exec(s);
163
+ if (!m) return null;
164
+ const row = refDocById(getDb(), m[1]);
165
+ if (!row) throw notFound('文档不存在: ' + m[1]);
166
+ // 外部镜像行:locator 是真实绝对路径,读取仍走闭包校验
167
+ const externalPath = row.origin === 'external' && /^([A-Za-z]:[\\/]|[\\/])/.test(row.locator) ? row.locator : '';
168
+ return { refId: row.id, rel: row.rel, externalPath, desc: row.desc };
169
+ }
170
+
171
+ /** 一个 ref 的归属清单(ref_bindings)。 */
172
+ function bindingsOfRef(refId: string): NonNullable<DocGetResult['bindings']> {
173
+ if (!clean(refId)) return [];
174
+ return getDb()
175
+ .all(
176
+ `SELECT type, repo_key AS repoKey, group_key AS groupKey, position
177
+ FROM ref_bindings WHERE ref_id = :id ORDER BY type, position`,
178
+ { id: refId }
179
+ )
180
+ .map((r: any) => ({
181
+ type: String(r.type),
182
+ repoKey: String(r.repoKey),
183
+ groupKey: r.groupKey == null ? null : String(r.groupKey),
184
+ position: Number(r.position) || 0,
185
+ }));
186
+ }
187
+
114
188
  // 读全文:自有(惰性播种)/ 外部(闭包内才放行);目录绑定返回文件清单
115
189
  export async function getDoc({ ref }: { ref?: unknown } = {}): Promise<DocGetResult> {
116
- if (!clean(ref)) throw badInput('请给文档标识:自有 rel:<路径>(或裸相对路径),外部 path:<绝对路径>');
117
- const parsed = paths.parseDocId(ref);
190
+ if (!clean(ref)) throw badInput('请给文档标识:ref:<refId> / rel:<路径> / path:<绝对路径>');
191
+ const hit = resolveRefIdInput(ref);
192
+ const parsed = hit
193
+ ? (hit.externalPath ? { kind: 'external' as const, path: hit.externalPath } : { kind: 'own' as const, rel: hit.rel })
194
+ : (paths.parseDocId(ref) as { kind: 'own'; rel: string } | { kind: 'external'; path: string });
195
+ const meta = hit ? { refId: hit.refId, desc: hit.desc, bindings: bindingsOfRef(hit.refId) } : {};
118
196
  if (parsed.kind === 'own') {
119
- let body: string | null = null;
120
- try {
121
- body = await store.readOwnDoc(parsed.rel);
122
- } catch {
123
- const seeded = await seed.ensureSeedForRel(parsed.rel);
124
- if (seeded === null) {
125
- return { docId: paths.ownDocId(parsed.rel), rel: parsed.rel, missing: true, writable: true, title: '', summary: '', body: '' };
126
- }
127
- body = seeded;
197
+ const state = await store.ownDocState(parsed.rel);
198
+ if (state.exists && state.hasBody) {
199
+ return {
200
+ ...outOwn(parsed.rel, state.body ?? '', state.relKind),
201
+ refId: state.id,
202
+ desc: state.desc,
203
+ bindings: bindingsOfRef(state.id),
204
+ };
128
205
  }
129
- return outOwn(parsed.rel, body);
206
+ // v6:有行但没有正文(历史空壳 / 外部镜像 / 正文缺失)→ 显式 missing + 原因,
207
+ // 不返回空文档成功态,也不把壳行播种成新文档。
208
+ if (state.exists) {
209
+ return {
210
+ docId: paths.ownDocId(parsed.rel),
211
+ refId: state.id,
212
+ rel: parsed.rel,
213
+ desc: state.desc,
214
+ bindings: bindingsOfRef(state.id),
215
+ missing: true,
216
+ writable: false,
217
+ title: '',
218
+ summary: '',
219
+ body: '',
220
+ relKind: state.relKind,
221
+ reason: state.reason,
222
+ };
223
+ }
224
+ const seeded = await seed.ensureSeedForRel(parsed.rel);
225
+ if (seeded === null) {
226
+ return {
227
+ docId: paths.ownDocId(parsed.rel), rel: parsed.rel, missing: true, writable: true,
228
+ title: '', summary: '', body: '', relKind: 'empty', reason: '文档不存在',
229
+ };
230
+ }
231
+ const after = await store.ownDocState(parsed.rel);
232
+ return {
233
+ ...outOwn(parsed.rel, seeded, 'normal'),
234
+ ...(after.exists ? { refId: after.id, desc: after.desc, bindings: bindingsOfRef(after.id) } : {}),
235
+ };
130
236
  }
131
237
  // 外部:先过绑定闭包,闭包外一律拒绝——doc.get 不能变成任意文件读入口
132
238
  const { loadStore } = await reposBridge();
@@ -141,13 +247,13 @@ export async function getDoc({ ref }: { ref?: unknown } = {}): Promise<DocGetRes
141
247
  /* 缺失:按 missing 返回 */
142
248
  }
143
249
  if (!st) {
144
- return { docId: paths.extDocId(abs), path: abs, missing: true, writable: true, title: '', summary: '', body: '' };
250
+ return { docId: paths.extDocId(abs), ...meta, path: abs, missing: true, writable: true, title: '', summary: '', body: '' };
145
251
  }
146
252
  if (st.isDirectory()) {
147
253
  const files = await store.listExternalDocs([{ path: abs, exists: true, isDir: true }], { maxDepth: 3, maxFiles: 200 });
148
- return { docId: paths.extDocId(abs), path: abs, dir: true, writable: false, files };
254
+ return { docId: paths.extDocId(abs), ...meta, path: abs, dir: true, writable: false, files };
149
255
  }
150
- return outExternal(abs, await safeRead(abs));
256
+ return { ...outExternal(abs, await safeRead(abs)), ...meta };
151
257
  }
152
258
 
153
259
  // ─── 增 / 改 / 删 ──────────────────────────────────────────────────────
@@ -165,9 +271,14 @@ async function bodyOf({ body, bodyFile }: DocWriteCtx, opts?: { transport?: stri
165
271
 
166
272
  export async function addDoc(ctx: DocWriteCtx, opts?: { transport?: string } | null): Promise<DocWriteResult> {
167
273
  const rel = await store.writeOwnDoc(ctx.rel as string, (await bodyOf(ctx, opts)) ?? '');
274
+ if (ctx.desc !== undefined) await store.setOwnDocDesc(rel, ctx.desc);
168
275
  const body = await store.readOwnDoc(rel);
169
276
  const summary = await seed.writeBackSummary(rel, body);
170
- return { docId: paths.ownDocId(rel), rel, bytes: Buffer.byteLength(body, 'utf8'), summary };
277
+ // 落盘即登记:新文件可能正好是某宿主的约定主篇(repo/<key>/index.md 等),
278
+ // 绑定索引跟着重建一次,别等下次双链索引才出现(#183)。
279
+ await syncRefIndex().catch(() => null);
280
+ const state = await store.ownDocState(rel);
281
+ return { docId: paths.ownDocId(rel), refId: state.id, rel, desc: state.desc, bytes: Buffer.byteLength(body, 'utf8'), summary };
171
282
  }
172
283
 
173
284
  // 外部文档写回(面板/CLI 均可):路径必须仍在**绑定闭包**内——闭包是唯一的授权来源,
@@ -204,28 +315,186 @@ async function writeExternalDoc(abs: string, body: string): Promise<DocWriteResu
204
315
  }
205
316
 
206
317
  export async function updateDoc(ctx: DocWriteCtx, opts?: { transport?: string } | null): Promise<DocWriteResult> {
207
- const parsed = paths.parseDocId(ctx.ref);
318
+ const hit = resolveRefIdInput(ctx.ref);
319
+ const parsed = hit
320
+ ? (hit.externalPath ? { kind: 'external' as const, path: hit.externalPath } : { kind: 'own' as const, rel: hit.rel })
321
+ : (paths.parseDocId(ctx.ref) as { kind: 'own'; rel: string } | { kind: 'external'; path: string });
208
322
  const body = await bodyOf(ctx, opts);
209
- if (body === null) throw badInput('请给 --body <正文>(多行用 --body-file <文件> 或 - 读管道)');
323
+ const desc = ctx.desc === undefined ? null : String(ctx.desc ?? '').trim();
324
+ if (body === null && desc === null) {
325
+ throw badInput('请给 --body <正文>(多行用 --body-file <文件> 或 - 读管道)或 --desc <描述>');
326
+ }
210
327
  // 外部绑定:登记在册 = 我的文档集,允许就地写回来源文件(闭包内校验)
211
- if (parsed.kind !== 'own') return writeExternalDoc(parsed.path, body);
328
+ if (parsed.kind !== 'own') {
329
+ const out = body === null
330
+ ? { docId: paths.extDocId(parsed.path), path: parsed.path, bytes: 0, external: true }
331
+ : await writeExternalDoc(parsed.path, body);
332
+ if (desc !== null && hit) await store.setOwnDocDesc(hit.rel, desc);
333
+ return { ...out, ...(hit ? { refId: hit.refId, desc: desc ?? undefined } : {}) };
334
+ }
335
+ if (body === null) {
336
+ // 只改描述:不读、不写正文
337
+ const saved = await store.setOwnDocDesc(parsed.rel, desc);
338
+ const state = await store.ownDocState(parsed.rel);
339
+ return { docId: paths.ownDocId(parsed.rel), refId: state.id, rel: parsed.rel, desc: saved, bytes: state.body ? Buffer.byteLength(state.body, 'utf8') : 0 };
340
+ }
212
341
  // 不存在即创建(面板保存语义:脏页签保存不该因为别人先建了而失败,也不该在这里静默分叉出第二份)
213
342
  const rel = await store.writeOwnDoc(parsed.rel, body);
214
343
  const saved = await store.readOwnDoc(rel);
215
344
  const summary = await seed.writeBackSummary(rel, saved);
216
- return { docId: paths.ownDocId(rel), rel, bytes: Buffer.byteLength(saved, 'utf8'), summary };
345
+ const state = await store.ownDocState(rel);
346
+ // desc 的优先级:显式并入参 > 已有的手写值(为空时才用摘要补,避免覆盖用户描述)
347
+ if (desc !== null) await store.setOwnDocDesc(rel, desc);
348
+ else if (!state.desc && summary) await store.setOwnDocDesc(rel, summary);
349
+ const finalState = await store.ownDocState(rel);
350
+ // 保存语义是「不存在即创建」——新出现的约定主篇要立刻进绑定索引(#183)
351
+ await syncRefIndex().catch(() => null);
352
+ return {
353
+ docId: paths.ownDocId(rel),
354
+ refId: finalState.id,
355
+ rel,
356
+ desc: finalState.desc,
357
+ bytes: Buffer.byteLength(saved, 'utf8'),
358
+ summary,
359
+ };
217
360
  }
218
361
 
219
362
  export async function removeDoc({ ref }: { ref?: unknown } = {}): Promise<{ docId: string; rel: string }> {
220
- const parsed = paths.parseDocId(ref);
363
+ const hit = resolveRefIdInput(ref);
364
+ const parsed = hit
365
+ ? (hit.externalPath ? { kind: 'external' as const, path: hit.externalPath } : { kind: 'own' as const, rel: hit.rel })
366
+ : (paths.parseDocId(ref) as { kind: 'own'; rel: string } | { kind: 'external'; path: string });
221
367
  if (parsed.kind !== 'own') throw blocked('外部绑定是只读引用,不能在这里删除');
222
368
  const rel = await store.removeOwnDoc(parsed.rel);
369
+ // 文件没了 → 约定主篇可能整体消失,绑定要跟着重算(#183)
370
+ await syncRefIndex().catch(() => null);
223
371
  return { docId: paths.ownDocId(rel), rel };
224
372
  }
225
373
 
374
+ // ─── 直接 ref(v7):desc + 归属,不涉及任何文件 / 路径 ────────────────
375
+
376
+ /** ref 的宿主类型(ref_bindings.type)。 */
377
+ export type RefOwnerType = 'repo' | 'group' | 'group_repo';
378
+
379
+ /** createRef 的入参。 */
380
+ export interface CreateRefInput {
381
+ desc?: unknown;
382
+ owner?: unknown;
383
+ /** 仓库 locator(id / key / 名称) */
384
+ repo?: unknown;
385
+ /** 组 locator(id / key / 名称) */
386
+ group?: unknown;
387
+ }
388
+
389
+ /** createRef 的出参。 */
390
+ export interface CreateRefResult {
391
+ refId: string;
392
+ docId: string;
393
+ desc: string;
394
+ bindings: NonNullable<DocGetResult['bindings']>;
395
+ }
396
+
397
+ /**
398
+ * 新建一个直接 ref:`refs` 行 + 空正文 + 一条归属绑定。
399
+ *
400
+ * 口径(v7 / 任务 #97):ref 是 DB 实体,没有路径 / 文件名 / 扩展名;
401
+ * 身份就是 `refs.id`,`rel = id` 只作唯一键,任何界面都不展示。
402
+ * 默认归属由调用方按「在哪儿点的新建」决定:单 repo / 组 / 组下的 repo。
403
+ */
404
+ export async function createRef({ desc, owner = 'repo', repo: repoLocator, group: groupLocator }: CreateRefInput = {}): Promise<CreateRefResult> {
405
+ const type = String(owner || 'repo') as RefOwnerType;
406
+ if (!['repo', 'group', 'group_repo'].includes(type)) {
407
+ throw badInput('归属类型只能是 repo / group / group_repo: ' + String(owner));
408
+ }
409
+ const { loadStore, deriveKey, boardKeyOf } = await reposBridge();
410
+ const s = await loadStore();
411
+ const board = groupLocator
412
+ ? s.boards.find((b: any) => b.id === clean(groupLocator) || boardKeyOf(b.name) === clean(groupLocator) || String(b.name).toLowerCase() === clean(groupLocator).toLowerCase())
413
+ : null;
414
+ if ((type === 'group' || type === 'group_repo') && !board) {
415
+ throw notFound('组不存在: ' + clean(groupLocator));
416
+ }
417
+ const repo = repoLocator
418
+ ? s.repos.find((r: any) => r.id === clean(repoLocator) || deriveKey(r) === clean(repoLocator) || String(r.name).toLowerCase() === clean(repoLocator).toLowerCase())
419
+ : null;
420
+ if ((type === 'repo' || type === 'group_repo') && !repo) {
421
+ throw notFound('仓库不存在: ' + clean(repoLocator));
422
+ }
423
+ const repoKey = type === 'group' ? String(boardKeyOf(board!.name)) : String(deriveKey(repo));
424
+ const groupKey = type === 'group_repo' ? String(boardKeyOf(board!.name)) : null;
425
+ const descText = clean(desc);
426
+ const id = refIdFor(randomUUID());
427
+ const at = Date.now();
428
+ const db = getDb();
429
+ tx(
430
+ (conn: any) => {
431
+ conn.run(
432
+ `INSERT INTO refs (id, type, rel, locator, origin, state, version, deleted_at, created_at, updated_at, "desc")
433
+ VALUES (:id, 'md', :rel, '', 'own', '', 0, NULL, :at, :at, :desc)`,
434
+ { id, rel: id, at, desc: descText }
435
+ );
436
+ // 空正文也落行:新建的是可编辑文档,不是「无正文」空壳。
437
+ upsertRefBody(conn, { refId: id, body: '', atMs: at });
438
+ const gk = groupKey == null ? null : groupKey;
439
+ const pos = type === 'group_repo'
440
+ ? 0
441
+ : Number(
442
+ conn.get(
443
+ `SELECT COALESCE(MAX(position), -1) + 1 AS p FROM ref_bindings
444
+ WHERE repo_key = :repo AND group_key IS NULL AND type = :type`,
445
+ { repo: repoKey, type }
446
+ )?.p ?? 0
447
+ );
448
+ putRefBinding(conn, { repoKey, groupKey: gk, refId: id, type, position: pos, atMs: at });
449
+ markRefBound(conn, id);
450
+ },
451
+ { db, mode: 'IMMEDIATE' }
452
+ );
453
+ return { refId: id, docId: 'ref:' + id, desc: descText, bindings: bindingsOfRef(id) };
454
+ }
455
+
456
+ /** unbindRef 的入参:按行精确解绑(直接 ref 专用)。 */
457
+ export interface UnbindRefInput {
458
+ ref?: unknown;
459
+ type?: unknown;
460
+ repo?: unknown;
461
+ group?: unknown;
462
+ }
463
+
464
+ /**
465
+ * 解绑一条**直接 ref** 的归属(不删 ref、不删正文)。
466
+ * 派生绑定(ext 推出的老文档)不在这里处理——摘除仍走宿主的文档集接口。
467
+ */
468
+ export async function unbindRef({ ref, type, repo, group }: UnbindRefInput = {}): Promise<{ refId: string; removed: number; orphan: boolean }> {
469
+ const hit = resolveRefIdInput(ref);
470
+ if (!hit) throw badInput('请给 refId(ref_…)');
471
+ const row = getDb().get('SELECT id, rel FROM refs WHERE id = :id AND deleted_at IS NULL', { id: hit.refId });
472
+ if (!row || String(row.rel) !== String(row.id)) throw blocked('只能解绑直接 ref: ' + hit.refId);
473
+ const t = String(type || '');
474
+ if (!['repo', 'group', 'group_repo'].includes(t)) throw badInput('归属类型只能是 repo / group / group_repo');
475
+ const repoKey = clean(repo);
476
+ if (!repoKey) throw badInput('缺少归属宿主(repo 或 group key)');
477
+ const db = getDb();
478
+ const removed = tx(
479
+ (conn: any) => {
480
+ const r = conn.run(
481
+ `DELETE FROM ref_bindings
482
+ WHERE ref_id = :ref AND type = :type AND repo_key = :repo
483
+ AND COALESCE(group_key, '') = COALESCE(:group, '')`,
484
+ { ref: hit.refId, type: t, repo: repoKey, group: clean(group) || null }
485
+ );
486
+ return Number(r.changes) || 0;
487
+ },
488
+ { db, mode: 'IMMEDIATE' }
489
+ );
490
+ const left = getDb().get('SELECT 1 AS x FROM ref_bindings WHERE ref_id = :id', { id: hit.refId });
491
+ if (!left) getDb().run("UPDATE refs SET state = 'orphan', updated_at = :at WHERE id = :id", { at: Date.now(), id: hit.refId });
492
+ return { refId: hit.refId, removed, orphan: !left };
493
+ }
494
+
226
495
  // ─── 出参整形 ──────────────────────────────────────────────────────────
227
496
 
228
- function outOwn(rel: string, body: string): DocGetResult {
497
+ function outOwn(rel: string, body: string, relKind: RelKind = 'normal'): DocGetResult {
229
498
  const { summaryFromMd } = seed;
230
499
  // #168:标题 = 正文**首行**的 `# 标题`(不是「任意位置的首个 # 行」——
231
500
  // 那样正文中间插一行 ## 就会改标题;也不是「首个非空行」——那会让正文
@@ -237,6 +506,7 @@ function outOwn(rel: string, body: string): DocGetResult {
237
506
  summary: summaryFromMd(body),
238
507
  body,
239
508
  writable: true,
509
+ relKind,
240
510
  };
241
511
  }
242
512