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
@@ -0,0 +1,179 @@
1
+ # 命令手册:localtask(本机任务队列)
2
+
3
+ > 归属主文档 [[nx-kv]]。先读主文档的「最常用的六条」,这里补细节:
4
+ > 参数、返回结构、退出码、避坑。全部命令**纯本机、不需要登录**。
5
+
6
+ ## 通用约定
7
+
8
+ | 约定 | 内容 |
9
+ | --- | --- |
10
+ | `--json` | 单个 JSON 值到 stdout,无多余文本;适合 `JSON.parse` |
11
+ | 退出码 | `0` 成功;`1` 失败(参数错 / 不存在 / 冲突) |
12
+ | 主题定位 | 默认是**进程当前目录**;任意命令可带 `--cwd <目录>`;已有主题可直接 `--key <topicKey>` |
13
+ | 任务定位 | `--id <n>`(主题内唯一);跨主题引用写 `"<topicKey>:<id>"` |
14
+ | 数据落盘 | 本机 SQLite(`NX_KV_DB` 可覆盖;默认 `~/.nx-kv/nxkv.db`) |
15
+
16
+ `get` 是**领取**动词(改状态);查看一律用 `show`。要预览交付又不领取,用 `preview`。
17
+
18
+ ## 领取 / 等待 / 完成
19
+
20
+ ```bash
21
+ # 领活:有任务立即领走;没有立即 timeout(不阻塞)
22
+ nx-kv localtask get --json
23
+ # → { status:"ok", task:{ id, text, attachments? }, instruction:"…" }
24
+ # 或 { status:"timeout", ... }(exit 0,正常业务结果)
25
+
26
+ # 等人:阻塞等到下一条任务;本轮最后一步
27
+ nx-kv localtask wait --timeout 180 --json
28
+ # → 同上;超时返回 { status:"timeout", timeoutMs, ... }
29
+
30
+ # 只读查看单条
31
+ nx-kv localtask show --id <n> --json
32
+
33
+ # 完成回填(summary 必填;时间目标未到点会 blocked)
34
+ nx-kv localtask done --id <n> --summary "<完成总结>" --json
35
+
36
+ # 就地重开(同号回写;旧态压进 history)
37
+ nx-kv localtask reopen --id <n> --text "<新正文>" [--kind reopen|comment] --json
38
+ ```
39
+
40
+ `done` 被时间目标拒绝时返回(不是错误):
41
+
42
+ ```json
43
+ { "status": "blocked", "reason": "goal_not_reached", "remainingSec": 1830,
44
+ "hint": "时间未到,不能标记完成——请派出 sub agent 重新提出新的需求;到点后…再来标完成" }
45
+ ```
46
+
47
+ `wait` 的 timeout 返回形状是固定契约:`cwd` / `key` / `status` / `summary` / `timeoutMs`。
48
+
49
+ ## 投递 / 排队
50
+
51
+ ```bash
52
+ nx-kv localtask add "<Markdown 正文>" --json
53
+ nx-kv localtask add "<正文>" --cwd <目录> --json
54
+ nx-kv localtask add "<正文>" --global --json # 全局共享池
55
+ nx-kv localtask add "<正文>" --project <仓库> --board <组> --json
56
+ nx-kv localtask add "<正文>" --duration 2h --goal-prompt "先写测试" --json
57
+ nx-kv localtask add "<正文>" --block-by 12,13 --json # DAG:这些任务完成后才可领
58
+ nx-kv localtask add "<正文>" --gate --json # 闸门:本任务未完成,后面的 pending 不可领
59
+ ```
60
+
61
+ 投递到别的目录的完整「委托」流程见 `kv-submit` skill(它会把上下文与验收标准
62
+ 打包成自包含任务再 `localtask add`)。
63
+
64
+ ## 队列与主题管理
65
+
66
+ ```bash
67
+ nx-kv localtask list --json # 全部主题总览
68
+ nx-kv localtask update --id <n> --text "<新内容>" # 改正文(未领取时)
69
+ nx-kv localtask update --id <n> --duration 90m # 设/改任务级时间目标
70
+ nx-kv localtask update --id <n> --clear-goal # 清时间目标
71
+ nx-kv localtask reorder --id <n> --before-id <m> # 调序
72
+ nx-kv localtask remove --id <n> # 软删除
73
+ nx-kv localtask task restore --id <n> # 恢复软删除
74
+ nx-kv localtask clone --id <n> # 复制为新任务
75
+ nx-kv localtask chain --id <n> --json # 任务链(history + fork)
76
+ nx-kv localtask cancel --cwd <目录> # 取消该主题的等待(无等待则 no-op)
77
+ nx-kv localtask topic add --cwd <目录> # 建主题
78
+ nx-kv localtask topic remove --cwd <目录> --force # 删主题(有未领取任务默认拒绝)
79
+ nx-kv localtask topic remove-many --keys <k1,k2> --force
80
+ nx-kv localtask prune --days 30 --json # 清理旧终态任务
81
+ ```
82
+
83
+ ## 附件(全部本机)
84
+
85
+ ```bash
86
+ nx-kv file upload --path <本机文件> --json
87
+ # → { fileId, name, size, contentType, storage:"local", localPath, markdown:{image,file} }
88
+
89
+ nx-kv localtask attach --id <n> --path <本机文件> --json # 上传并嵌入正文
90
+ nx-kv localtask attach --id <n> --fileId <fileId> --json # 引用已有附件
91
+ nx-kv localtask attach --id <n> --fileId <id> --no-embed # 只挂附件区,不写正文
92
+ nx-kv localtask attach --id <n> --url <https://…> # 外链资源
93
+ nx-kv localtask attach --id <n> --ref <refId> [--inline] # 文档绑定(--inline 交付带全文)
94
+ nx-kv localtask attach --id <n> --mdfile <本机 .md 路径> # 本地 md 路径指针
95
+ nx-kv localtask attach-note --id <n> --attachment <id> --note "<说明>"
96
+ nx-kv localtask attachments --id <n> --json # 附件清单 + 本地绝对路径
97
+ nx-kv localtask detach --id <n> --attachment <id>
98
+ ```
99
+
100
+ 返回的附件条目形如:
101
+
102
+ ```json
103
+ { "id": "3f2a…9c", "kind": "image", "name": "设计稿.png",
104
+ "storage": "local", "synced": true,
105
+ "localPath": "C:\\Users\\me\\.nx-kv\\attachments\\local\\设计稿.png" }
106
+ ```
107
+
108
+ - `synced` = 本机仓命中;`localPath` 是真实在盘的绝对路径,agent 直接 `Read`。
109
+ - 未命中时没有 `localPath`,清单会写「本机附件仓没有这个文件」——不要猜路径。
110
+ - **没有 `file sync`、没有自动下载开关、没有云端图床**;上传即落盘。
111
+
112
+ 清理无主资源:
113
+
114
+ ```bash
115
+ nx-kv file orphans --json # 没有被任何任务/文档引用的上传
116
+ nx-kv file prune --dry-run # 先看
117
+ nx-kv file prune # 回收(DB 行 + 附件根内的字节)
118
+ ```
119
+
120
+ ## 时间目标
121
+
122
+ ```bash
123
+ nx-kv timegoal set --cwd <目录> --duration 4h --prompt "<根指令>" # 目录级预算
124
+ nx-kv timegoal show --cwd <目录> --json
125
+ nx-kv timegoal check --task task:<topicKey>:<taskId> --summary "<本轮现状>" --json
126
+ nx-kv timegoal clear --cwd <目录>
127
+ nx-kv timegoal list --json
128
+ nx-kv timegoal log --cwd <目录> --json
129
+ ```
130
+
131
+ - 任务级目标(`localtask add --duration`)**领取即计时**,交付里带 `check` 指令;
132
+ - 每轮推进先 `check`(原文回显提示词,防长对话漂移);
133
+ - `done` 在目标未到点时返回 `blocked`;按 hint 派 sub agent 重提需求;
134
+ - 目录级目标是「这个目录整体跑多久」,不影响单条任务的 done。
135
+
136
+ ## 预览与诊断
137
+
138
+ ```bash
139
+ nx-kv localtask preview --id <n> --json # 预览领取交付(不领取、不写库、不起计时)
140
+ nx-kv localtask events --json # 队列事件(面板实时刷新同源)
141
+ nx-kv localtask presence --json # 哪些主题有 agent 在等
142
+ nx-kv localtask timegoal-log --json # 本主题的时间目标日志
143
+ nx-kv localtask config --timeout 180 # 等待超时与交付模板(目录级设置)
144
+ ```
145
+
146
+ ## 文档库(refs)
147
+
148
+ ```bash
149
+ nx-kv docs list --json
150
+ nx-kv docs get --ref <refId> --json # 取正文(也认 rel:<相对路径>)
151
+ nx-kv docs bindings --repo <key> --json # 仓库绑了哪些文档
152
+ nx-kv docs ref add <path-or-…> --desc "<一行简介>" # 建直接 ref(无本地路径)
153
+ nx-kv docs ref unbind --ref <refId> # 解绑(不删文档)
154
+ ```
155
+
156
+ ref 是**库内文档 + 归属**,不是附件、没有本地路径;读取一律 `docs get --ref`。
157
+
158
+ ## 错误与退出码
159
+
160
+ | 情况 | 退出码 / code | 处理 |
161
+ | --- | --- | --- |
162
+ | 参数缺失 / 非法 | 1 · `INVALID_INPUT` | 看报错「用法:」;`--json` 时读 `code` |
163
+ | 任务 / 主题不存在 | 1 · `NOT_FOUND` | `localtask list` 确认主题与 id |
164
+ | 状态冲突(已被领取 / 已完成) | 1 · `CONFLICT` | 语义是「已经是你要的」,跳过即可 |
165
+ | 时间目标未到点 | 0 · `{status:"blocked"}` | 不硬标完成;按 hint 派 sub agent 重提需求 |
166
+ | wait 超时 | 0 · `{status:"timeout"}` | 正常业务结果,按「暂时没活」收尾 |
167
+
168
+ ## 避坑
169
+
170
+ | 坑 | 后果 | 正确做法 |
171
+ | --- | --- | --- |
172
+ | 用 `get` 当查看 | 改状态、起计时 | 查看用 `show` / `preview` |
173
+ | 连续 attach 用正文定位 | 正文被改写,定位漂移 | 一律 `--id` |
174
+ | 忘了 `--cwd` | 在别的目录建/领了队列 | 先 `localtask list` 确认主题 |
175
+ | 把 timeout 当失败 | 反复重跑,空转 | timeout 是业务结果(exit 0) |
176
+ | 并发 `get` + `wait` | 同一队列抢任务 | 同一目录同一时刻只挂一个 wait |
177
+ | 提前 `done` 带时间目标的任务 | blocked,白跑 | 到点 `check.reached` 后再 done |
178
+ | 附件按 URL 猜 | 本机没有该地址 | 用 `localPath`;未命中就问提交方 |
179
+ | 软删除后以为没了 | 任务仍在历史 | `task restore` 可恢复;彻底清理用 `prune` |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.48.2",
4
- "description": "nx-kv — KV 清单管理中枢(远程)+ 本机本地任务队列(localtask):serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
3
+ "version": "0.50.0",
4
+ "description": "nx-kv — 本机任务队列(localtask)+ 文档库 + 仓库登记:serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "nx-kv": "bin/kv.mjs"
@@ -43,8 +43,7 @@
43
43
  "keywords": [
44
44
  "cli",
45
45
  "web-panel",
46
- "kv",
47
- "todo",
46
+ "task-queue",
48
47
  "agent-tools",
49
48
  "skills"
50
49
  ],
@@ -0,0 +1,193 @@
1
+ // ref 正文(ref_bodies)的读写与条目分类。
2
+ //
3
+ // v6 起 `refs` 是文档身份 + 元数据,正文唯一真相在 `ref_bodies`(1:1,CASCADE)。
4
+ // 本模块只做三件事:
5
+ // 1. 正文 CRUD(upsert / get);
6
+ // 2. rel ↔ id 的解析(rel 是逻辑名,id 是外键目标);
7
+ // 3. 条目分类:normal / legacy / external / empty —— 让调用方能区分
8
+ // 「正常文档」与「历史空壳 / 外部文件镜像 / 无正文」。
9
+ //
10
+ // 分类口径(docs/decisions/2026-11-12-refs-body-in-db.md §11.1):
11
+ // legacy/<id> 迁移时无 locator 的历史行,只有身份、没有正文;
12
+ // external/<hash> 外部绝对路径 / URL 的镜像行,正文在库外,不进 ref_bodies;
13
+ // empty 其它没有正文的活动行(如盘上文件已删的历史条目);
14
+ // normal 有正文、且不是上面两类命名空间。
15
+ import { createHash } from 'node:crypto';
16
+
17
+ /** 一条 ref 条目的读路径类别。 */
18
+ export type RelKind = 'normal' | 'legacy' | 'external' | 'empty';
19
+
20
+ /** 一条正文记录。 */
21
+ export interface RefBodyRow {
22
+ ref_id: string;
23
+ body: string;
24
+ body_bytes: number;
25
+ body_hash: string;
26
+ updated_at: number;
27
+ }
28
+
29
+ /** 列表用的一条 ref 条目(带正文是否存在)。 */
30
+ export interface RefDocRow {
31
+ id: string;
32
+ rel: string;
33
+ origin: string;
34
+ /** 短描述(v7):列表 / 提示词模板的快速定位标签 */
35
+ desc: string;
36
+ bodyBytes: number;
37
+ hasBody: boolean;
38
+ relKind: RelKind;
39
+ }
40
+
41
+ const sha256 = (s: string): string => createHash('sha256').update(s, 'utf8').digest('hex');
42
+
43
+ /** rel + 是否有正文 → 读路径类别。 */
44
+ export function relKindOf(rel: unknown, hasBody: boolean): RelKind {
45
+ const r = String(rel || '');
46
+ if (r.startsWith('legacy/')) return 'legacy';
47
+ if (r.startsWith('external/')) return 'external';
48
+ return hasBody ? 'normal' : 'empty';
49
+ }
50
+
51
+ /** 无正文条目的原因(给人读;docs get / 交付清单共用)。 */
52
+ export function noBodyReason(kind: RelKind): string {
53
+ if (kind === 'legacy') return '历史索引条目:只有身份与旧地址,没有正文';
54
+ if (kind === 'external') return '外部文件镜像:正文在库外,未入库';
55
+ if (kind === 'empty') return '条目存在但正文缺失(文件已删除或从未入库)';
56
+ return '';
57
+ }
58
+
59
+ /** rel 是否属于「不允许当正常文档展示」的命名空间。 */
60
+ export function isShellRel(rel: unknown): boolean {
61
+ const r = String(rel || '');
62
+ return r.startsWith('legacy/') || r.startsWith('external/');
63
+ }
64
+
65
+ /** 按 refs.id 取正文。 */
66
+ export function getRefBody(conn: any, refId: unknown): RefBodyRow | null {
67
+ const row = conn.get(
68
+ 'SELECT ref_id, body, body_bytes, body_hash, updated_at FROM ref_bodies WHERE ref_id = :id',
69
+ { id: String(refId || '') }
70
+ );
71
+ return row ? (row as RefBodyRow) : null;
72
+ }
73
+
74
+ /** 写正文(UPSERT),返回字节数与 sha256。body_bytes 一律按 UTF-8 计。 */
75
+ export function upsertRefBody(
76
+ conn: any,
77
+ { refId, body, atMs = Date.now() }: { refId: string; body: unknown; atMs?: number }
78
+ ): { bytes: number; hash: string } {
79
+ const text = String(body ?? '');
80
+ const bytes = Buffer.byteLength(text, 'utf8');
81
+ const hash = sha256(text);
82
+ conn.run(
83
+ `INSERT INTO ref_bodies (ref_id, body, body_bytes, body_hash, updated_at)
84
+ VALUES (:id, :body, :n, :hash, :at)
85
+ ON CONFLICT(ref_id) DO UPDATE SET
86
+ body = excluded.body,
87
+ body_bytes = excluded.body_bytes,
88
+ body_hash = excluded.body_hash,
89
+ updated_at = excluded.updated_at`,
90
+ { id: refId, body: text, n: bytes, hash, at: atMs }
91
+ );
92
+ return { bytes, hash };
93
+ }
94
+
95
+ /** 按 rel 找活动行的 id(rel 是逻辑名,唯一)。 */
96
+ export function refIdByRel(conn: any, rel: unknown): string | null {
97
+ const r = String(rel || '').trim();
98
+ if (!r) return null;
99
+ const row = conn.get(
100
+ 'SELECT id FROM refs WHERE rel = :rel AND deleted_at IS NULL',
101
+ { rel: r }
102
+ );
103
+ return row ? String(row.id) : null;
104
+ }
105
+
106
+ /**
107
+ * 列出 ref 条目。
108
+ * @param includeEmpty=false 只给「有正文且非 legacy/external」的正常文档
109
+ * (默认口径,供导出/双链/知识聚合使用);
110
+ * true 连历史空壳、外部镜像、无正文行一起给(`docs list` 用,需显式标注)。
111
+ */
112
+ export function listRefDocs(conn: any, { includeEmpty = false }: { includeEmpty?: boolean } = {}): RefDocRow[] {
113
+ const rows: any[] = conn.all(
114
+ `SELECT r.id, r.rel, r.origin, r."desc", r.body_bytes,
115
+ CASE WHEN b.ref_id IS NULL THEN 0 ELSE 1 END AS has_body
116
+ FROM refs r
117
+ LEFT JOIN ref_bodies b ON b.ref_id = r.id
118
+ WHERE r.deleted_at IS NULL AND r.rel <> ''
119
+ ORDER BY r.rel`
120
+ );
121
+ const out: RefDocRow[] = [];
122
+ for (const row of rows) {
123
+ const rel = String(row.rel || '');
124
+ const hasBody = Number(row.has_body) === 1;
125
+ const relKind = relKindOf(rel, hasBody);
126
+ if (!includeEmpty && (!hasBody || relKind !== 'normal')) continue;
127
+ out.push({
128
+ id: String(row.id),
129
+ rel,
130
+ origin: String(row.origin || ''),
131
+ desc: String(row.desc || ''),
132
+ bodyBytes: Number(row.body_bytes) || 0,
133
+ hasBody,
134
+ relKind,
135
+ });
136
+ }
137
+ return out;
138
+ }
139
+
140
+ /** 按 rel 取条目状态(含正文);不存在返回 null。 */
141
+ export function refDocByRel(conn: any, rel: unknown): (RefDocRow & { body: string | null }) | null {
142
+ const r = String(rel || '').trim();
143
+ if (!r) return null;
144
+ const row = conn.get(
145
+ `SELECT r.id, r.rel, r.origin, r."desc", r.body_bytes,
146
+ CASE WHEN b.ref_id IS NULL THEN 0 ELSE 1 END AS has_body,
147
+ b.body
148
+ FROM refs r
149
+ LEFT JOIN ref_bodies b ON b.ref_id = r.id
150
+ WHERE r.rel = :rel AND r.deleted_at IS NULL`,
151
+ { rel: r }
152
+ );
153
+ if (!row) return null;
154
+ const hasBody = Number(row.has_body) === 1;
155
+ return {
156
+ id: String(row.id),
157
+ rel: String(row.rel),
158
+ origin: String(row.origin || ''),
159
+ desc: String(row.desc || ''),
160
+ bodyBytes: Number(row.body_bytes) || 0,
161
+ hasBody,
162
+ relKind: relKindOf(row.rel, hasBody),
163
+ body: hasBody ? String(row.body ?? '') : null,
164
+ };
165
+ }
166
+
167
+ /** 按 refs.id 取条目(docs get 的 refId 寻址 / 归属查询共用)。 */
168
+ export function refDocById(conn: any, id: unknown): (RefDocRow & { body: string | null; locator: string }) | null {
169
+ const r = String(id || '').trim();
170
+ if (!r) return null;
171
+ const row = conn.get(
172
+ `SELECT r.id, r.rel, r.locator, r.origin, r."desc", r.body_bytes,
173
+ CASE WHEN b.ref_id IS NULL THEN 0 ELSE 1 END AS has_body,
174
+ b.body
175
+ FROM refs r
176
+ LEFT JOIN ref_bodies b ON b.ref_id = r.id
177
+ WHERE r.id = :id AND r.deleted_at IS NULL`,
178
+ { id: r }
179
+ );
180
+ if (!row) return null;
181
+ const hasBody = Number(row.has_body) === 1;
182
+ return {
183
+ id: String(row.id),
184
+ rel: String(row.rel),
185
+ locator: String(row.locator || ''),
186
+ origin: String(row.origin || ''),
187
+ desc: String(row.desc || ''),
188
+ bodyBytes: Number(row.body_bytes) || 0,
189
+ hasBody,
190
+ relKind: relKindOf(row.rel, hasBody),
191
+ body: hasBody ? String(row.body ?? '') : null,
192
+ };
193
+ }
@@ -1,35 +1,42 @@
1
1
  // 文档索引:refs 行的解析/建/删,与任务、文档两块正文的整库重扫(迁移与索引用;幂等)。
2
2
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
3
  import type { Dirent } from 'node:fs';
4
+ import { createHash } from 'node:crypto';
4
5
  import { isAbsolute, join, relative, resolve } from 'node:path';
5
6
  import { refIdFor } from './ids.js';
7
+ import { refIdByRel } from './bodies.js';
6
8
  import { syncRefAttachments, syncTaskAttachments } from './relations.js';
7
9
 
8
10
  /**
9
- * 把一个「文档标识」解析成 refs.id:先按 id,再按 locator(原样 / 反斜杠归一),
10
- * 都没有返回 null。CLI `--ref` 与面板选择器共用这一条,避免各自猜地址语法。
11
+ * 把一个「文档标识」解析成 refs.id:先按 id,再按 rel(v6 起的逻辑名),
12
+ * 再按 locator(历史入口 / 外部绝对路径),都没有返回 null。
13
+ * CLI `--ref` 与面板选择器共用这一条,避免各自猜地址语法。
11
14
  *
12
- * **docId 前缀也认**(#165 二轮:面板选择器给的是 `rel:` / `path:` 形式,
13
- * 而 refs.locator 存的是裸相对路径 / 绝对路径——不剥前缀就永远匹配不上,
14
- * 面板「给任务挂文档」直接失败)。故额外按「剥前缀后的 locator」再查一次。
15
+ * **docId 前缀也认**(#165 二轮:面板选择器给的是 `rel:` / `path:` 形式)。
15
16
  */
16
17
  export function resolveRefId(conn: any, input?: string): string | null {
17
18
  const raw = String(input || '').trim();
18
19
  if (!raw) return null;
19
20
  const byId = conn.get('SELECT id FROM refs WHERE id = :id AND deleted_at IS NULL', { id: raw });
20
21
  if (byId) return byId.id;
22
+
21
23
  const loc = raw.replace(/\\/g, '/');
22
- const byLoc = conn.get(
23
- 'SELECT id FROM refs WHERE locator = :loc AND deleted_at IS NULL', { loc }
24
- );
25
- if (byLoc) return byLoc.id;
26
- // docId 形态(rel:xxx / path:xxx)→ 剥前缀按 locator 再查
27
24
  const stripped = /^rel:|^path:/i.test(loc) ? loc.replace(/^rel:|^path:/i, '') : '';
28
- if (stripped) {
29
- const byStripped = conn.get(
30
- 'SELECT id FROM refs WHERE locator = :loc AND deleted_at IS NULL', { loc: stripped }
25
+ const candidates = [loc, stripped].filter(Boolean);
26
+
27
+ // v6 之前(迁移链早期步骤)refs 还没有 rel 列,只能走历史 locator 入口
28
+ if (hasRelColumn(conn)) {
29
+ for (const cand of candidates) {
30
+ const id = refIdByRel(conn, cand);
31
+ if (id) return id;
32
+ }
33
+ }
34
+ // 历史入口:locator(v4 及以前的行;外部绝对路径仍靠它命中)
35
+ for (const cand of candidates) {
36
+ const byLoc = conn.get(
37
+ 'SELECT id FROM refs WHERE locator = :loc AND deleted_at IS NULL', { loc: cand }
31
38
  );
32
- if (byStripped) return byStripped.id;
39
+ if (byLoc) return byLoc.id;
33
40
  }
34
41
  const derived = refIdFor(loc);
35
42
  const byDerived = conn.get('SELECT id FROM refs WHERE id = :id AND deleted_at IS NULL', { id: derived });
@@ -37,29 +44,142 @@ export function resolveRefId(conn: any, input?: string): string | null {
37
44
  }
38
45
 
39
46
  export interface EnsureDocRefInput {
47
+ /** v6 起的逻辑名(首选) */
48
+ rel?: string;
49
+ /** 历史入口 / 外部绝对路径(兼容既有调用方) */
40
50
  locator?: string;
41
51
  atMs?: number;
42
52
  }
43
53
 
44
- /** 确保 refs 行存在(文档保存 / 索引重建共用;已有行不重置 state)。 */
45
- export function ensureDocRef(conn: any, { locator, atMs = Date.now() }: EnsureDocRefInput = {}): string | null {
46
- const loc = String(locator || '').trim().replace(/\\/g, '/');
47
- if (!loc) return null;
48
- const id = refIdFor(loc);
54
+ const sha1 = (s: unknown): string => createHash('sha1').update(String(s), 'utf8').digest('hex');
55
+
56
+ /**
57
+ * refs 是否已有 v6 的 rel 列。
58
+ * 迁移链会从旧结构逐级升级:v2-data 也会调 ensureDocRef,那时 rel 还不存在,
59
+ * 不能无条件查询它(否则 1→2 直接失败)。列存在性用 pragma_table_info 判断。
60
+ */
61
+ function hasRelColumn(conn: any): boolean {
62
+ return !!conn.get("SELECT name FROM pragma_table_info('refs') WHERE name = 'rel'");
63
+ }
64
+
65
+ /** 外部绝对路径 / URL 的逻辑 rel(v6 迁移同一口径)。 */
66
+ function externalRelOf(input: string): string {
67
+ let seed = isAbsolute(input) ? resolve(input).replace(/\\/g, '/') : input;
68
+ if (/^[A-Z]:/.test(seed)) seed = seed.charAt(0).toLowerCase() + seed.slice(1);
69
+ return 'external/' + sha1(seed).slice(0, 16);
70
+ }
71
+
72
+ /**
73
+ * 确保 refs 行存在(文档保存 / 索引重建共用;已有行不重置 state)。
74
+ * 先按 rel / locator 命中既有行——v6 迁移保留的 id 绝不被新公式改写。
75
+ */
76
+ export function ensureDocRef(conn: any, { rel, locator, atMs = Date.now() }: EnsureDocRefInput = {}): string | null {
77
+ const input = String(rel ?? locator ?? '').trim().replace(/\\/g, '/');
78
+ if (!input) return null;
79
+ const hasRel = hasRelColumn(conn);
80
+ if (hasRel) {
81
+ const byRel = refIdByRel(conn, input);
82
+ if (byRel) return byRel;
83
+ }
84
+ // 绝对路径 / URL:先按 locator 命中(外部镜像行的 id 与 rel 都不是新公式)
85
+ const byLoc = conn.get(
86
+ 'SELECT id FROM refs WHERE locator = :loc AND deleted_at IS NULL', { loc: input }
87
+ );
88
+ if (byLoc) return String(byLoc.id);
89
+
90
+ // v6 之前:保持历史形态(不动 locator 之外的语义)
91
+ if (!hasRel) {
92
+ const oldId = refIdFor(input);
93
+ conn.run(
94
+ `INSERT INTO refs (id, type, locator, state, version, deleted_at, created_at, updated_at)
95
+ VALUES (:id, 'md', :locator, 'orphan', 0, NULL, :at, :at)
96
+ ON CONFLICT(id) DO UPDATE SET type = 'md', locator = excluded.locator, updated_at = excluded.updated_at`,
97
+ { id: oldId, locator: input, at: atMs }
98
+ );
99
+ return oldId;
100
+ }
101
+
102
+ const external = /^https?:\/\//i.test(input)
103
+ || isAbsolute(input) || /^[A-Za-z]:[\\/]/.test(input) || input.startsWith('//');
104
+ const targetRel = external ? externalRelOf(input) : input;
105
+ const id = refIdFor(external ? input : targetRel);
49
106
  conn.run(
50
- `INSERT INTO refs (id, type, locator, state, version, deleted_at, created_at, updated_at)
51
- VALUES (:id, 'md', :locator, 'orphan', 0, NULL, :at, :at)
52
- ON CONFLICT(id) DO UPDATE SET type = 'md', locator = excluded.locator, updated_at = excluded.updated_at`,
53
- { id, locator: loc, at: atMs }
107
+ `INSERT INTO refs (id, type, rel, locator, origin, state, version, deleted_at, created_at, updated_at)
108
+ VALUES (:id, 'md', :rel, :locator, :origin, 'orphan', 0, NULL, :at, :at)
109
+ ON CONFLICT(id) DO NOTHING`,
110
+ { id, rel: targetRel, locator: input, origin: external ? 'external' : 'own', at: atMs }
54
111
  );
55
112
  return id;
56
113
  }
57
114
 
58
- /** 文档删除:refs 行消失,ref_attach / ref_bindings 随之 CASCADE。 */
59
- export function forgetDocRef(conn: any, locator?: string): number {
60
- const loc = String(locator || '').trim().replace(/\\/g, '/');
61
- if (!loc) return 0;
62
- const r = conn.run('DELETE FROM refs WHERE id = :id', { id: refIdFor(loc) });
115
+ /** 文档删除:refs 行消失,ref_bodies / ref_attach / ref_bindings 随之 CASCADE。 */
116
+ export function forgetDocRef(conn: any, input?: string): number {
117
+ const id = resolveRefId(conn, input);
118
+ if (!id) return 0;
119
+ const r = conn.run('DELETE FROM refs WHERE id = :id', { id });
120
+ return Number(r.changes) || 0;
121
+ }
122
+
123
+ // ─── 宿主绑定(ref_bindings)──────────────────────────────────────────
124
+ //
125
+ // ref_bindings 一行 = 「某个宿主(仓库 / 组 / 组内某仓库)的文档列表里的一项」。
126
+ // 表在 v3 迁移时建好,但长期只有 bind-topics 与导入器在写——docs 域改 ext
127
+ // (r.doc / docLinks / b.repoDocs)时不同步,于是库里全是 orphan、面板上却
128
+ // 显示「已绑定」(#183 实锤:4 篇已挂文档,ref_bindings 零行)。这四个
129
+ // 原语给 docs 域的整表重建用,写入方只允许 docs/ref-sync。
130
+
131
+ export interface RefBindingRow {
132
+ repoKey?: string;
133
+ groupKey?: string | null;
134
+ refId?: string;
135
+ type?: string;
136
+ position?: number;
137
+ note?: string;
138
+ atMs?: number;
139
+ }
140
+
141
+ /** 绑一条(幂等:唯一键冲突时保留原行)。 */
142
+ export function putRefBinding(conn: any, { repoKey, groupKey = null, refId, type = 'repo', position = 0, note = '', atMs = Date.now() }: RefBindingRow = {}): void {
143
+ conn.run(
144
+ `INSERT OR IGNORE INTO ref_bindings (repo_key, group_key, ref_id, type, position, note, created_at)
145
+ VALUES (:repo, :group, :ref, :type, :pos, :note, :at)`,
146
+ {
147
+ repo: String(repoKey || ''),
148
+ group: groupKey == null ? null : String(groupKey),
149
+ ref: String(refId || ''),
150
+ type: String(type || 'repo'),
151
+ pos: Number(position) || 0,
152
+ note: String(note || ''),
153
+ at: atMs,
154
+ }
155
+ );
156
+ }
157
+
158
+ /**
159
+ * 清空「派生绑定」(v7):只清 rel ≠ id 的 ref 的绑定。
160
+ *
161
+ * rel = id 的行是 v7 新建的直接 ref(ref 是 DB 实体,没有路径):
162
+ * 它的归属由用户直接写入 ref_bindings,不来自 ext,整表重建时不能抹掉。
163
+ */
164
+ export function clearRefBindings(conn: any): void {
165
+ conn.run('DELETE FROM ref_bindings WHERE ref_id NOT IN (SELECT id FROM refs WHERE rel = id)');
166
+ }
167
+
168
+ /** 绑定命中的 ref → state 清空(不再是孤儿)。 */
169
+ export function markRefBound(conn: any, refId?: string): void {
170
+ const id = String(refId || '');
171
+ if (!id) return;
172
+ conn.run("UPDATE refs SET state = '', updated_at = :at WHERE id = :id", { id, at: Date.now() });
173
+ }
174
+
175
+ /** 没有任何绑定的 ref → 回到 orphan(重建收尾,防止摘绑定后状态残留)。 */
176
+ export function markUnboundRefsOrphan(conn: any): number {
177
+ const r = conn.run(
178
+ `UPDATE refs SET state = 'orphan', updated_at = :at
179
+ WHERE deleted_at IS NULL AND state <> 'orphan'
180
+ AND id NOT IN (SELECT ref_id FROM ref_bindings)`,
181
+ { at: Date.now() }
182
+ );
63
183
  return Number(r.changes) || 0;
64
184
  }
65
185
 
@@ -71,11 +191,16 @@ export function syncTaskAttachmentIndex(conn: any, { atMs = Date.now() }: { atMs
71
191
  return n;
72
192
  }
73
193
 
74
- /** 全量重扫 docs 自有树 + 外部 .md(迁移与索引重建用;幂等)。 */
75
- export function syncDocAttachmentIndex(conn: any, { docsRoot, atMs = Date.now() }: {
76
- docsRoot?: string; atMs?: number;
194
+ /**
195
+ * 全量重扫 docs 自有树 + 外部 .md(**仅迁移 / 索引重建用**;幂等)。
196
+ *
197
+ * 这是 attachment 层的例外读盘:v2 迁移时正文还没进库,必须从旧文档目录取一次。
198
+ * 业务读路径不得调用它——自有文档正文的唯一真相是 `ref_bodies`。
199
+ */
200
+ export function syncDocAttachmentIndex(conn: any, { docsDir, atMs = Date.now() }: {
201
+ docsDir?: string; atMs?: number;
77
202
  } = {}): number {
78
- const root = String(docsRoot || '');
203
+ const root = String(docsDir || '');
79
204
  const files: string[] = [];
80
205
  const walk = (dir: string): void => {
81
206
  let entries: Dirent[] = [];
@@ -105,7 +230,7 @@ export function syncDocAttachmentIndex(conn: any, { docsRoot, atMs = Date.now()
105
230
  const refId = ensureDocRef(conn, { locator, atMs });
106
231
  n += syncRefAttachments(conn, { refId, text, atMs });
107
232
  }
108
- // 外部 .md(refs.locator 是绝对路径):不在 docs 树里,但同样是文档库的一行。
233
+ // 外部 .md(refs.locator 是绝对路径):不在 docs 目录里,但同样是文档库的一行。
109
234
  // 迁移必须把它们的正文引用也落库,否则「存量文档的图片」只有正文 fileId 字符串。
110
235
  for (const row of conn.all("SELECT id, locator FROM refs WHERE type = 'md'")) {
111
236
  const loc = String(row.locator || '');