nx-kv 0.41.0 → 0.41.1

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 (204) hide show
  1. package/CHANGELOG.md +29 -6
  2. package/README.md +1 -0
  3. package/package.json +2 -2
  4. package/src/core/attachmentdb/docs.js +104 -0
  5. package/src/core/attachmentdb/ids.js +96 -0
  6. package/src/core/attachmentdb/query.js +189 -0
  7. package/src/core/attachmentdb/relations.js +153 -0
  8. package/src/core/attachmentdb/resources.js +225 -0
  9. package/src/core/attachmentdb.js +42 -715
  10. package/src/core/db/import-json/data.js +140 -0
  11. package/src/core/db/import-json/extras.js +69 -0
  12. package/src/core/db/import-json/links.js +147 -0
  13. package/src/core/db/import-json/refs.js +183 -0
  14. package/src/core/db/import-json/repos.js +180 -0
  15. package/src/core/db/import-json/scan.js +35 -0
  16. package/src/core/db/import-json/tasks.js +317 -0
  17. package/src/core/db/import-json.js +31 -1061
  18. package/src/modules/docs/attach.js +181 -0
  19. package/src/modules/docs/index.js +20 -448
  20. package/src/modules/docs/knowledge.js +7 -2
  21. package/src/modules/docs/render.js +84 -0
  22. package/src/modules/docs/service.js +200 -0
  23. package/src/modules/localtask/action-attach.js +88 -0
  24. package/src/modules/localtask/action-flags.js +6 -0
  25. package/src/modules/localtask/action-lifecycle.js +190 -0
  26. package/src/modules/localtask/action-maintenance.js +130 -0
  27. package/src/modules/localtask/action-move.js +58 -0
  28. package/src/modules/localtask/action-query.js +46 -0
  29. package/src/modules/localtask/action-remove.js +116 -0
  30. package/src/modules/localtask/action-render.js +200 -0
  31. package/src/modules/localtask/action-submit.js +186 -0
  32. package/src/modules/localtask/action-topics.js +46 -0
  33. package/src/modules/localtask/action-waiting.js +95 -0
  34. package/src/modules/localtask/index.js +29 -1104
  35. package/src/modules/repos/boards/core.js +255 -0
  36. package/src/modules/repos/boards/docs.js +53 -0
  37. package/src/modules/repos/boards/members.js +228 -0
  38. package/src/modules/repos/boards/transfer.js +159 -0
  39. package/src/modules/repos/boards.js +25 -661
  40. package/src/modules/repos/cli/board-actions.js +177 -0
  41. package/src/modules/repos/cli/ref-actions.js +157 -0
  42. package/src/modules/repos/cli/remote-actions.js +141 -0
  43. package/src/modules/repos/cli/render.js +168 -0
  44. package/src/modules/repos/cli/repo-actions.js +199 -0
  45. package/src/modules/repos/cli/transfer-actions.js +105 -0
  46. package/src/modules/repos/index.js +18 -920
  47. package/src/modules/repos/service/bind-topics.js +97 -0
  48. package/src/modules/repos/service/context.js +189 -0
  49. package/src/modules/repos/service/crud.js +345 -0
  50. package/src/modules/repos/service/identity.js +188 -0
  51. package/src/modules/repos/service/store.js +274 -0
  52. package/src/modules/repos/service.js +41 -1061
  53. package/src/modules/repos/transfer/diff.js +126 -0
  54. package/src/modules/repos/transfer/export.js +223 -0
  55. package/src/modules/repos/transfer/import.js +377 -0
  56. package/src/modules/repos/transfer/layout.js +135 -0
  57. package/src/modules/repos/transfer/render.js +72 -0
  58. package/src/modules/repos/transfer.js +11 -922
  59. package/src/modules/tasktool/attach-resource.js +293 -0
  60. package/src/modules/tasktool/attach-template.js +266 -0
  61. package/src/modules/tasktool/attach.js +70 -558
  62. package/src/modules/tasktool/delivery-template.js +2 -1
  63. package/src/modules/tasktool/doc-inline.js +84 -0
  64. package/src/modules/tasktool/groupctx.js +3 -1
  65. package/src/modules/tasktool/plugins/timegoal-core-store.js +151 -0
  66. package/src/modules/tasktool/plugins/timegoal-cwd-store.js +441 -0
  67. package/src/modules/tasktool/plugins/timegoal-store.js +16 -842
  68. package/src/modules/tasktool/plugins/timegoal-task-store.js +289 -0
  69. package/src/modules/tasktool/wait.js +3 -1
  70. package/src/modules/todo/attachments.js +149 -0
  71. package/src/modules/todo/locate.js +82 -0
  72. package/src/modules/todo/service.js +42 -382
  73. package/src/modules/todo/store.js +158 -0
  74. package/src/shared/prompt-blocks.js +13 -4
  75. package/src/web/frontend/components/md/find-bar.jsx +38 -0
  76. package/src/web/frontend/components/md/live-block.jsx +129 -0
  77. package/src/web/frontend/components/md/md-panes-helpers.js +92 -0
  78. package/src/web/frontend/components/md/md-panes-keys.js +193 -0
  79. package/src/web/frontend/components/md/md-panes-root.jsx +158 -0
  80. package/src/web/frontend/components/md/md-panes.jsx +124 -1342
  81. package/src/web/frontend/components/md/slash-menu.jsx +83 -0
  82. package/src/web/frontend/components/md/status-bar.jsx +46 -0
  83. package/src/web/frontend/components/md/use-live-preview.js +279 -0
  84. package/src/web/frontend/components/md/use-slash-menu.js +80 -0
  85. package/src/web/frontend/components/md/use-source-editor.js +297 -0
  86. package/src/web/frontend/modules/md/md-blocks.js +248 -0
  87. package/src/web/frontend/modules/md/md-parse.js +23 -507
  88. package/src/web/frontend/modules/md/md-render.js +258 -0
  89. package/src/web/frontend/modules/md/style.css +7 -1605
  90. package/src/web/frontend/modules/md/styles/chrome.css +252 -0
  91. package/src/web/frontend/modules/md/styles/docs.css +185 -0
  92. package/src/web/frontend/modules/md/styles/editor.css +308 -0
  93. package/src/web/frontend/modules/md/styles/panels.css +372 -0
  94. package/src/web/frontend/modules/md/styles/shell.css +363 -0
  95. package/src/web/frontend/modules/md/styles/templates.css +125 -0
  96. package/src/web/frontend/page/dag/edges.js +55 -0
  97. package/src/web/frontend/page/dag/head-bar.jsx +46 -0
  98. package/src/web/frontend/page/dag/index.jsx +57 -420
  99. package/src/web/frontend/page/dag/layout.js +83 -0
  100. package/src/web/frontend/page/dag/model.js +47 -0
  101. package/src/web/frontend/page/dag/node-card.jsx +123 -0
  102. package/src/web/frontend/page/dag/use-interactions.js +135 -0
  103. package/src/web/frontend/page/dir/task-ack.js +38 -0
  104. package/src/web/frontend/page/dir/task-actions.js +379 -0
  105. package/src/web/frontend/page/dir/task-beside-header.jsx +18 -0
  106. package/src/web/frontend/page/dir/task-board-section.jsx +38 -0
  107. package/src/web/frontend/page/dir/task-chain.js +172 -0
  108. package/src/web/frontend/page/dir/task-derived-ctx.js +46 -0
  109. package/src/web/frontend/page/dir/task-dock-panel.jsx +227 -0
  110. package/src/web/frontend/page/dir/task-dock.js +79 -0
  111. package/src/web/frontend/page/dir/task-feedback.js +207 -0
  112. package/src/web/frontend/page/dir/task-goal-section.jsx +50 -0
  113. package/src/web/frontend/page/dir/task-goal.js +36 -0
  114. package/src/web/frontend/page/dir/task-history-view.jsx +44 -0
  115. package/src/web/frontend/page/dir/task-not-found.jsx +23 -0
  116. package/src/web/frontend/page/dir/task-preview-modal.jsx +82 -0
  117. package/src/web/frontend/page/dir/task-sel-menu.js +54 -0
  118. package/src/web/frontend/page/dir/task-status-bar.jsx +61 -0
  119. package/src/web/frontend/page/dir/task-utils.js +7 -0
  120. package/src/web/frontend/page/dir/task.jsx +117 -1532
  121. package/src/web/frontend/page/repos/bind-modals.jsx +118 -0
  122. package/src/web/frontend/page/repos/board-admin.jsx +226 -0
  123. package/src/web/frontend/page/repos/board-refs.jsx +97 -0
  124. package/src/web/frontend/page/repos/doc-search-modal.jsx +241 -0
  125. package/src/web/frontend/page/repos/filters-bar.jsx +44 -0
  126. package/src/web/frontend/page/repos/index.jsx +248 -1834
  127. package/src/web/frontend/page/repos/pending-section.jsx +163 -0
  128. package/src/web/frontend/page/repos/ref-panel.jsx +406 -0
  129. package/src/web/frontend/page/repos/remote-modal.jsx +112 -0
  130. package/src/web/frontend/page/repos/repo-form-modal.jsx +219 -0
  131. package/src/web/frontend/page/repos/repo-table.jsx +216 -0
  132. package/src/web/frontend/page/settings/prompt-template-params.js +214 -0
  133. package/src/web/frontend/page/settings/prompt-templates-section.jsx +1 -213
  134. package/src/web/frontend/style-v2.css +6 -1232
  135. package/src/web/frontend/style.css +10 -2434
  136. package/src/web/frontend/styles/base.css +139 -0
  137. package/src/web/frontend/styles/board.css +322 -0
  138. package/src/web/frontend/styles/buttons-cards.css +244 -0
  139. package/src/web/frontend/styles/modals.css +458 -0
  140. package/src/web/frontend/styles/panels.css +366 -0
  141. package/src/web/frontend/styles/repos-admin.css +207 -0
  142. package/src/web/frontend/styles/repos.css +330 -0
  143. package/src/web/frontend/styles/settings.css +244 -0
  144. package/src/web/frontend/styles/submit-bar.css +124 -0
  145. package/src/web/frontend/styles-v2/dag.css +285 -0
  146. package/src/web/frontend/styles-v2/dir.css +210 -0
  147. package/src/web/frontend/styles-v2/shell.css +251 -0
  148. package/src/web/frontend/styles-v2/sidebar.css +199 -0
  149. package/src/web/frontend/styles-v2/views.css +287 -0
  150. package/src/web/frontend/workspace/layout.js +399 -0
  151. package/src/web/frontend/workspace/open.js +246 -0
  152. package/src/web/frontend/workspace/panels.js +417 -0
  153. package/src/web/frontend/workspace.js +8 -1044
  154. package/src/web/public/assets/Introduction-Dnh0L_ss.js +1 -0
  155. package/src/web/public/assets/app-context-D7HAx67n.js +1 -0
  156. package/src/web/public/assets/bar-CgCAhY5x.js +1 -0
  157. package/src/web/public/assets/{board-view-t8CKtq17.js → board-view-CZKZsyk-.js} +1 -1
  158. package/src/web/public/assets/{button-M9TUn-AR.js → button-Cmo-6aoW.js} +1 -1
  159. package/src/web/public/assets/cloud-DMeqfWK9.js +3 -0
  160. package/src/web/public/assets/composer-launch-Bf4rXhLs.js +1 -0
  161. package/src/web/public/assets/composer-panel-C0qsxE7e.js +1 -0
  162. package/src/web/public/assets/dag-BBtSqd-X.js +1 -0
  163. package/src/web/public/assets/dir-UUWImKeX.js +5 -0
  164. package/src/web/public/assets/frontmatter-QvrjUNzF.js +2 -0
  165. package/src/web/public/assets/group-DFMGHQ-H.js +1 -0
  166. package/src/web/public/assets/index-CgEWvYQk.js +2 -0
  167. package/src/web/public/assets/md-history-CKumOs4q.js +39 -0
  168. package/src/web/public/assets/md-parse-awNLHAzO.js +13 -0
  169. package/src/web/public/assets/{member-picker--32VkTmv.js → member-picker-BAgkj36N.js} +1 -1
  170. package/src/web/public/assets/model-DzdWfp14.js +2 -0
  171. package/src/web/public/assets/{overview-B788GcJE.js → overview-BrcPfsJO.js} +1 -1
  172. package/src/web/public/assets/progress-DHDlz9O9.js +3 -0
  173. package/src/web/public/assets/refs-CqvRGv8w.js +1 -0
  174. package/src/web/public/assets/repos-DGrGWDnX.js +14 -0
  175. package/src/web/public/assets/route-crumb-yyPGKKKq.js +1 -0
  176. package/src/web/public/assets/settings-9zNucAPD.js +6 -0
  177. package/src/web/public/assets/{status-tag-BPbfa4zt.js → status-tag-bDdrFgpZ.js} +1 -1
  178. package/src/web/public/assets/task-CG4fzV6s.js +11 -0
  179. package/src/web/public/assets/{task-status-BP6y8MVu.js → task-status-BnymQMTw.js} +1 -1
  180. package/src/web/public/assets/templates-DdHWIxUE.js +1 -0
  181. package/src/web/public/assets/tool-bar-D8q3kOOl.js +1 -0
  182. package/src/web/public/assets/upload-BIMbGcCB.js +1 -0
  183. package/src/web/public/assets/workspace-C_5X2gIr.js +28 -0
  184. package/src/web/public/index.html +8 -4
  185. package/src/web/public/assets/Introduction-DKqRmABL.js +0 -1
  186. package/src/web/public/assets/bar-B8QJ4EnF.js +0 -1
  187. package/src/web/public/assets/cloud-C2O_1vT5.js +0 -3
  188. package/src/web/public/assets/composer-launch-BgMj0T3Y.js +0 -1
  189. package/src/web/public/assets/composer-panel-C5XUApWJ.js +0 -1
  190. package/src/web/public/assets/dag-CWAWk_gt.js +0 -1
  191. package/src/web/public/assets/dir-Cu5B5z6J.js +0 -5
  192. package/src/web/public/assets/group-YA-FgKS3.js +0 -1
  193. package/src/web/public/assets/index-DxX-ZzRP.js +0 -30
  194. package/src/web/public/assets/md-history-4sXoj4RH.js +0 -28
  195. package/src/web/public/assets/md-parse-C2bDc3IZ.js +0 -25
  196. package/src/web/public/assets/progress-CfzFVSDu.js +0 -3
  197. package/src/web/public/assets/refs-qtxw66hp.js +0 -1
  198. package/src/web/public/assets/repos-CpVuGaP2.js +0 -14
  199. package/src/web/public/assets/route-crumb-B8oEN8BB.js +0 -1
  200. package/src/web/public/assets/settings-BmWNBqcv.js +0 -6
  201. package/src/web/public/assets/task-DsFCNaOJ.js +0 -11
  202. package/src/web/public/assets/templates-4Xaj2m9L.js +0 -1
  203. package/src/web/public/assets/tool-bar-CfBWzhpV.js +0 -1
  204. package/src/web/public/assets/upload-L1g-pfvZ.js +0 -1
package/CHANGELOG.md CHANGED
@@ -2,15 +2,28 @@
2
2
 
3
3
  本文件记录对外可见的变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
4
4
 
5
- ## [0.41.0] - 2026-11-10 新建任务按钮拆两级命中区
5
+ ## [0.41.1] - 2026-11-10 组内成员行补本机路径
6
6
 
7
7
  ### Changed
8
8
 
9
- - **新建按钮拆成两级(#161)**:group / dir 的「新建任务」按钮**视觉上仍是一颗**,
10
- 但命中区分两层——主区点击 = **按默认模板直接新建**;按钮内嵌箭头区 = 模板下拉
11
- (选模板新建)。组页此前整颗钮点击只开下拉,目录页则是「新建页」+ 独立「模板 ▾」
12
- 两颗钮——现统一为拆分钮(目录页的独立模板钮移除,其下拉内容并入箭头区)。
13
- 工具区模块表随之移除 `tpl` 项(旧布局里存过的 id 由 normalizeLayout 丢弃)。
9
+ - **交付上下文的「组内成员」每行补本机磁盘路径(#163)**:`- 名字:(描述)`
10
+ 变为 `- 名字:(描述)(D:\...路径)`——agent 看到兄弟仓库名就能直接定位盘上
11
+ 位置,不用再查清单。数据来自仓库登记的 path(未登记路径的成员行不变);
12
+ 默认上下文模板与旧纯文本渲染器同口径更新,`group.peers` 数组新增 `path` 字段。
13
+
14
+ ## [0.41.0] - 2026-11-10 任务级文档绑定进原文
15
+
16
+ ### Added
17
+
18
+ - **任务级文档绑定「进原文」(#162)**:`localtask attach --ref <文档> --inline` 落
19
+ 「文档资料」绑定(role=doc)——交付时把文档全文附进〔附件〕段末尾的〔文档原文〕段
20
+ (截断 2 万字,截断时给出完整版读取命令;标题取文档首行 `# `),agent 无需再跑
21
+ `docs get`,减少反复访问 nx-kv 的开销。绑定读侧只读(自有树 / 绑定闭包内,
22
+ 缺失不播种、闭包外拒绝),读不到全文时 fail-open 退回路径 + 取用命令。
23
+ - **绑定说明(desc)全链路透出(#162)**:`localtask attach --note` 现在在默认
24
+ 嵌入路径也会落库(此前只落正文、说明丢失),交付〔附件〕段清单行与
25
+ `localtask attachments` 都透出;正文同步整组重写 inline 边时边上说明原样保留。
26
+ 文档侧 `docs attach --note` 同样受益(重写保留)。
14
27
 
15
28
  ## [0.40.0] - 2026-11-09 参考仓库两类绑定 + schema v4
16
29
 
@@ -42,6 +55,16 @@
42
55
  - 存储版本 v3 → v4:新增 `group_refs` 表,存量 ext_linked 绑定迁移到组级。
43
56
  旧库自动迁移,无需手工操作。
44
57
 
58
+ ## [0.40.1] - 2026-11-10 新建任务按钮拆两级命中区
59
+
60
+ ### Changed
61
+
62
+ - **新建按钮拆成两级(#161)**:group / dir 的「新建任务」按钮**视觉上仍是一颗**,
63
+ 但命中区分两层——主区点击 = **按默认模板直接新建**;按钮内嵌箭头区 = 模板下拉
64
+ (选模板新建)。组页此前整颗钮点击只开下拉,目录页则是「新建页」+ 独立「模板 ▾」
65
+ 两颗钮——现统一为拆分钮(目录页的独立模板钮移除,其下拉内容并入箭头区)。
66
+ 工具区模块表随之移除 `tpl` 项(旧布局里存过的 id 由 normalizeLayout 丢弃)。
67
+
45
68
  ## [0.39.1] - 2026-11-09 验证确认版
46
69
 
47
70
  - 零代码变更:0.39.0 的交付上下文「倒序聚焦 + 历史精简」经现场验证确认生效
package/README.md CHANGED
@@ -189,6 +189,7 @@ nx-kv localtask attach --id 3 --path "D:\doc\需求.docx" # 本机文件
189
189
  nx-kv localtask attach --id 3 --url https://example.com/design # 外部链接
190
190
  nx-kv localtask attach --id 3 --task 7 # 同主题另一条任务(引用,不是副本)
191
191
  nx-kv localtask attach --id 3 --ref board/quickget.md # 文档库 md
192
+ nx-kv localtask attach --id 3 --ref board/quickget.md --inline # 文档进原文:交付带全文(截断 2 万字),--note 作为该绑定的一行简介一并透出
192
193
  nx-kv localtask attach --id 3 --path "D:\doc\需求.docx" --no-embed # 只挂附件区,不改正文
193
194
  nx-kv localtask attachments --id 3 # 清单(正文内嵌 / 附件区)
194
195
  nx-kv localtask detach --id 3 --attachment <id> # 解除关系,资源进孤儿池
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.41.0",
3
+ "version": "0.41.1",
4
4
  "description": "nx-kv — KV 清单管理中枢(远程)+ 本机本地任务队列(localtask):serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,7 +17,7 @@
17
17
  "start": "pnpm run build && node bin/cli.mjs serve",
18
18
  "link:local": "node scripts/link-local.mjs",
19
19
  "unlink:local": "node scripts/link-local.mjs --unlink",
20
- "lint": "eslint . && node scripts/check-tdz.mjs --all && node scripts/check-schema-decisions.mjs",
20
+ "lint": "eslint . && node scripts/check-tdz.mjs --all && node scripts/check-schema-decisions.mjs && node scripts/check-lines.mjs",
21
21
  "check:schema": "node scripts/check-schema-decisions.mjs",
22
22
  "test": "pnpm run lint && pnpm run build && pnpm run test:smoke && pnpm run test:unit",
23
23
  "test:smoke": "node tests/smoke.mjs",
@@ -0,0 +1,104 @@
1
+ // 文档索引:refs 行的解析/建/删,与任务、文档两块正文的整库重扫(迁移与索引用;幂等)。
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import { isAbsolute, join, relative, resolve } from 'node:path';
4
+ import { refIdFor } from './ids.js';
5
+ import { syncRefAttachments, syncTaskAttachments } from './relations.js';
6
+
7
+ /**
8
+ * 把一个「文档标识」解析成 refs.id:先按 id,再按 locator(原样 / 反斜杠归一),
9
+ * 都没有返回 null。CLI `--ref` 与面板选择器共用这一条,避免各自猜地址语法。
10
+ */
11
+ export function resolveRefId(conn, input) {
12
+ const raw = String(input || '').trim();
13
+ if (!raw) return null;
14
+ const byId = conn.get('SELECT id FROM refs WHERE id = :id AND deleted_at IS NULL', { id: raw });
15
+ if (byId) return byId.id;
16
+ const loc = raw.replace(/\\/g, '/');
17
+ const byLoc = conn.get(
18
+ 'SELECT id FROM refs WHERE locator = :loc AND deleted_at IS NULL', { loc }
19
+ );
20
+ if (byLoc) return byLoc.id;
21
+ const derived = refIdFor(loc);
22
+ const byDerived = conn.get('SELECT id FROM refs WHERE id = :id AND deleted_at IS NULL', { id: derived });
23
+ return byDerived ? byDerived.id : null;
24
+ }
25
+
26
+ /** 确保 refs 行存在(文档保存 / 索引重建共用;已有行不重置 state)。 */
27
+ export function ensureDocRef(conn, { locator, atMs = Date.now() } = {}) {
28
+ const loc = String(locator || '').trim().replace(/\\/g, '/');
29
+ if (!loc) return null;
30
+ const id = refIdFor(loc);
31
+ conn.run(
32
+ `INSERT INTO refs (id, type, locator, state, version, deleted_at, created_at, updated_at)
33
+ VALUES (:id, 'md', :locator, 'orphan', 0, NULL, :at, :at)
34
+ ON CONFLICT(id) DO UPDATE SET type = 'md', locator = excluded.locator, updated_at = excluded.updated_at`,
35
+ { id, locator: loc, at: atMs }
36
+ );
37
+ return id;
38
+ }
39
+
40
+ /** 文档删除:refs 行消失,ref_attach / ref_bindings 随之 CASCADE。 */
41
+ export function forgetDocRef(conn, locator) {
42
+ const loc = String(locator || '').trim().replace(/\\/g, '/');
43
+ if (!loc) return 0;
44
+ const r = conn.run('DELETE FROM refs WHERE id = :id', { id: refIdFor(loc) });
45
+ return Number(r.changes) || 0;
46
+ }
47
+
48
+ /** 全量重扫任务正文(迁移与导入后用;幂等)。 */
49
+ export function syncTaskAttachmentIndex(conn, { atMs = Date.now() } = {}) {
50
+ const rows = conn.all('SELECT id, body FROM tasks ORDER BY id');
51
+ let n = 0;
52
+ for (const row of rows) n += syncTaskAttachments(conn, { taskId: row.id, text: row.body, atMs });
53
+ return n;
54
+ }
55
+
56
+ /** 全量重扫 docs 自有树 + 外部 .md(迁移与索引重建用;幂等)。 */
57
+ export function syncDocAttachmentIndex(conn, { docsRoot, atMs = Date.now() } = {}) {
58
+ const root = String(docsRoot || '');
59
+ const files = [];
60
+ const walk = (dir) => {
61
+ let entries = [];
62
+ try {
63
+ entries = readdirSync(dir, { withFileTypes: true });
64
+ } catch {
65
+ return;
66
+ }
67
+ for (const e of entries) {
68
+ const abs = join(dir, e.name);
69
+ if (e.isDirectory()) walk(abs);
70
+ else if (e.isFile() && /\.md$/i.test(e.name)) files.push(abs);
71
+ }
72
+ };
73
+ if (root && existsSync(root)) walk(root);
74
+ let n = 0;
75
+ const covered = new Set();
76
+ for (const abs of files.sort()) {
77
+ const locator = relative(root, abs).replace(/\\/g, '/');
78
+ covered.add(resolve(abs).replace(/\\/g, '/').toLowerCase());
79
+ let text = '';
80
+ try {
81
+ text = readFileSync(abs, 'utf8');
82
+ } catch {
83
+ continue;
84
+ }
85
+ const refId = ensureDocRef(conn, { locator, atMs });
86
+ n += syncRefAttachments(conn, { refId, text, atMs });
87
+ }
88
+ // 外部 .md(refs.locator 是绝对路径):不在 docs 树里,但同样是文档库的一行。
89
+ // 迁移必须把它们的正文引用也落库,否则「存量文档的图片」只有正文 fileId 字符串。
90
+ for (const row of conn.all("SELECT id, locator FROM refs WHERE type = 'md'")) {
91
+ const loc = String(row.locator || '');
92
+ if (!isAbsolute(loc) || !existsSync(loc)) continue;
93
+ if (covered.has(resolve(loc).replace(/\\/g, '/').toLowerCase())) continue;
94
+ if (!/\.md$/i.test(loc)) continue;
95
+ let text = '';
96
+ try {
97
+ text = readFileSync(loc, 'utf8');
98
+ } catch {
99
+ continue;
100
+ }
101
+ n += syncRefAttachments(conn, { refId: row.id, text, atMs });
102
+ }
103
+ return n;
104
+ }
@@ -0,0 +1,96 @@
1
+ // 标识与正文解析:fileId / ref / url / task 四类资源的稳定 id 公式,
2
+ // 以及 markdown 正文 → 资源引用清单的纯函数。本文件不碰数据库与文件系统。
3
+ import { createHash } from 'node:crypto';
4
+
5
+ // 不 import fileapi:它经 config → db/index → bootstrap → migrator 会绕回本模块。
6
+ // 这里只需要「按扩展名补一个够用的 MIME」,真实 MIME 由上传/同步路径写入。
7
+ const MIME_BY_EXT = {
8
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp',
9
+ gif: 'image/gif', svg: 'image/svg+xml', pdf: 'application/pdf',
10
+ md: 'text/markdown; charset=utf-8', txt: 'text/plain; charset=utf-8',
11
+ json: 'application/json; charset=utf-8', csv: 'text/csv; charset=utf-8',
12
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
13
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
14
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
15
+ };
16
+ export function mimeFromName(name) {
17
+ const ext = String(name || '').split('.').pop().toLowerCase();
18
+ return MIME_BY_EXT[ext] || '';
19
+ }
20
+
21
+ /** 与 shared/attach.js 同一口径(core 不能反向 import shared)。 */
22
+ const FILE_ID_RE = /^[0-9a-fA-F]{16,}(\.[A-Za-z0-9]{1,8})?$/;
23
+ const MD_LINK_RE = /!?\[([^\]]*)\]\(\s*([^)\s]+)\s*\)/g;
24
+ const NXKV_TASK_RE = /^nxkv:\/\/task\/(\d+)$/i;
25
+ const NXKV_REF_RE = /^nxkv:\/\/ref\/([A-Za-z0-9_-]+)$/i;
26
+
27
+ const sha1 = (s) => createHash('sha1').update(String(s), 'utf8').digest('hex');
28
+
29
+ export function isFileId(value) {
30
+ return FILE_ID_RE.test(String(value ?? '').trim());
31
+ }
32
+
33
+ /** refs.locator → ref_id(与 import-json 的 refIdOf 同一公式;路径统一 POSIX)。 */
34
+ export function refIdFor(locator) {
35
+ return 'ref_' + sha1(String(locator ?? '').replace(/\\/g, '/')).slice(0, 16);
36
+ }
37
+
38
+ export function urlAttachmentId(url) {
39
+ return 'att_url_' + sha1(String(url || '').trim().toLowerCase()).slice(0, 16);
40
+ }
41
+
42
+ export function taskAttachmentId(topicKey, seq) {
43
+ return 'att_task_' + sha1(`${String(topicKey || '')}:${Number(seq) || 0}`).slice(0, 16);
44
+ }
45
+
46
+ export function refAttachmentId(refId) {
47
+ return 'att_ref_' + sha1(String(refId || '')).slice(0, 16);
48
+ }
49
+
50
+ export function metaOf(row) {
51
+ try {
52
+ const v = JSON.parse(String((row && row.meta) || '{}'));
53
+ return v && typeof v === 'object' ? v : {};
54
+ } catch {
55
+ return {};
56
+ }
57
+ }
58
+
59
+ /**
60
+ * 正文 → 资源引用清单(顺序即 position)。只认:
61
+ * file:markdown 目标就是 fileId;
62
+ * task:nxkv://task/<全局 tasks.id>;
63
+ * ref:nxkv://ref/<ref_id>;
64
+ * url:markdown 目标是 http(s) 绝对地址。
65
+ * 其它链接(相对路径、锚点、普通 wiki 双链)不落资源表。
66
+ */
67
+ export function parseAttachmentRefs(text) {
68
+ const out = [];
69
+ const seen = new Set();
70
+ for (const m of String(text ?? '').matchAll(MD_LINK_RE)) {
71
+ const name = String(m[1] || '').trim();
72
+ const target = String(m[2] || '').trim();
73
+ const isImage = m[0].startsWith('![');
74
+ let ref = null;
75
+ if (isFileId(target)) {
76
+ ref = { kind: 'file', id: target, name: name || target, isImage };
77
+ } else {
78
+ const task = target.match(NXKV_TASK_RE);
79
+ const doc = target.match(NXKV_REF_RE);
80
+ if (task) ref = { kind: 'task', targetTaskId: Number(task[1]), name: name || `任务 ${task[1]}` };
81
+ else if (doc) ref = { kind: 'ref', targetRefId: doc[1], name: name || doc[1] };
82
+ else if (/^https?:\/\//i.test(target)) ref = { kind: 'url', url: target, name: name || target };
83
+ }
84
+ if (!ref) continue;
85
+ // 同一资源出现多次只保留第一条(关系表一资源一 role 一行,position 取首次出现)
86
+ const key = ref.id || (ref.kind === 'task' ? `task:${ref.targetTaskId}` : '')
87
+ || (ref.kind === 'ref' ? `ref:${ref.targetRefId}` : '')
88
+ || (ref.kind === 'url' ? `url:${ref.url.toLowerCase()}` : '');
89
+ if (seen.has(key)) continue;
90
+ seen.add(key);
91
+ ref.position = out.length;
92
+ ref.role = ref.kind === 'task' || ref.kind === 'ref' ? 'reference' : 'inline';
93
+ out.push(ref);
94
+ }
95
+ return out;
96
+ }
@@ -0,0 +1,189 @@
1
+ // 查询与生命周期:行视图、列表查询、孤儿资源清理、删除、旧 manifest 归档。
2
+ import { existsSync, readdirSync, renameSync, unlinkSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { metaOf } from './ids.js';
5
+
6
+ const ATT_SELECT = `SELECT id, kind, name, local_path, url, mime, size, hash, storage, group_id,
7
+ target_kind, target_key, target_seq, meta, deleted_at, created_at, updated_at
8
+ FROM attachments`;
9
+
10
+ function rowView(row) {
11
+ return {
12
+ id: row.id,
13
+ kind: row.kind,
14
+ name: row.name,
15
+ localPath: row.local_path,
16
+ url: row.url,
17
+ mime: row.mime,
18
+ size: Number(row.size) || 0,
19
+ hash: row.hash,
20
+ storage: row.storage,
21
+ groupId: Number(row.group_id) || 0,
22
+ targetKind: row.target_kind,
23
+ targetKey: row.target_key,
24
+ targetSeq: row.target_seq === null || row.target_seq === undefined ? null : Number(row.target_seq),
25
+ meta: metaOf(row),
26
+ deletedAt: row.deleted_at,
27
+ createdAt: Number(row.created_at) || 0,
28
+ updatedAt: Number(row.updated_at) || 0,
29
+ };
30
+ }
31
+
32
+ export function getAttachment(conn, id) {
33
+ const row = conn.get(`${ATT_SELECT} WHERE id = :id`, { id: String(id || '') });
34
+ return row ? rowView(row) : null;
35
+ }
36
+
37
+ export function listTaskAttachments(conn, taskId) {
38
+ return conn
39
+ .all(
40
+ `SELECT a.id, a.kind, a.name, a.local_path, a.url, a.mime, a.size, a.hash, a.storage,
41
+ a.group_id, a.target_kind, a.target_key, a.target_seq, a.meta,
42
+ a.deleted_at, a.created_at, a.updated_at, ta.role, ta.position, ta.note
43
+ FROM task_attach ta JOIN attachments a ON a.id = ta.attachment_id
44
+ WHERE ta.task_id = :id AND a.deleted_at IS NULL
45
+ ORDER BY ta.position, a.id`,
46
+ { id: Number(taskId) }
47
+ )
48
+ .map((r) => ({ ...rowView(r), role: r.role, position: Number(r.position) || 0, note: r.note }));
49
+ }
50
+
51
+ /** CLI 只有 topicKey + seq 时的查询入口。 */
52
+ export function listTaskAttachmentsBySeq(conn, { topicKey, seq }) {
53
+ const row = conn.get(
54
+ `SELECT t.id FROM tasks t JOIN topics k ON k.id = t.topic_id
55
+ WHERE k.key = :key AND t.seq = :seq`,
56
+ { key: String(topicKey || ''), seq: Number(seq) }
57
+ );
58
+ return row ? listTaskAttachments(conn, Number(row.id)) : [];
59
+ }
60
+
61
+ export function listRefAttachments(conn, refId) {
62
+ return conn
63
+ .all(
64
+ `SELECT a.id, a.kind, a.name, a.local_path, a.url, a.mime, a.size, a.hash, a.storage,
65
+ a.group_id, a.target_kind, a.target_key, a.target_seq, a.meta,
66
+ a.deleted_at, a.created_at, a.updated_at, ra.role, ra.position, ra.note
67
+ FROM ref_attach ra JOIN attachments a ON a.id = ra.attachment_id
68
+ WHERE ra.ref_id = :id AND a.deleted_at IS NULL
69
+ ORDER BY ra.position, a.id`,
70
+ { id: String(refId || '') }
71
+ )
72
+ .map((r) => ({ ...rowView(r), role: r.role, position: Number(r.position) || 0, note: r.note }));
73
+ }
74
+
75
+ /**
76
+ * 无主资源:没有任何 task_attach / ref_attach 边。
77
+ * 软删的任务/文档仍算「有主」(软删可恢复,不能在这里把字节删掉)。
78
+ */
79
+ export function listOrphans(conn) {
80
+ return conn
81
+ .all(
82
+ `${ATT_SELECT}
83
+ WHERE deleted_at IS NULL
84
+ AND NOT EXISTS (SELECT 1 FROM task_attach ta WHERE ta.attachment_id = attachments.id)
85
+ AND NOT EXISTS (SELECT 1 FROM ref_attach ra WHERE ra.attachment_id = attachments.id)
86
+ ORDER BY created_at, id`
87
+ )
88
+ .map(rowView);
89
+ }
90
+
91
+ function within(root, p) {
92
+ if (!root || !p) return false;
93
+ const a = resolve(root).replace(/\\/g, '/').toLowerCase();
94
+ const b = resolve(p).replace(/\\/g, '/').toLowerCase();
95
+ return b === a || b.startsWith(a.replace(/\/+$/, '') + '/');
96
+ }
97
+
98
+ /**
99
+ * 删除资源行(可选连字节一起删)。仍被任何任务/文档引用时拒绝——关系表是权威,
100
+ * 「解除关系」和「删资源」是两步,不能因为一次 detach --purge 误删别人在用的文件。
101
+ * @returns {{removed:boolean, reason?:string, attachment?:object}}
102
+ */
103
+ export function deleteAttachment(conn, id, { attachmentsRoot, purgeBytes = true } = {}) {
104
+ const row = getAttachment(conn, id);
105
+ if (!row) return { removed: false, reason: 'not-found' };
106
+ const still = conn.get(
107
+ `SELECT 1 AS x FROM task_attach WHERE attachment_id = :id
108
+ UNION ALL SELECT 1 FROM ref_attach WHERE attachment_id = :id LIMIT 1`,
109
+ { id: row.id }
110
+ );
111
+ if (still) return { removed: false, reason: 'in-use', attachment: row };
112
+ let bytesRemoved = false;
113
+ if (purgeBytes && row.kind === 'file' && row.localPath && within(attachmentsRoot, row.localPath)) {
114
+ try {
115
+ if (existsSync(row.localPath)) {
116
+ unlinkSync(row.localPath);
117
+ bytesRemoved = true;
118
+ }
119
+ } catch {
120
+ return { removed: false, reason: 'file-locked', attachment: row };
121
+ }
122
+ }
123
+ conn.run('DELETE FROM attachments WHERE id = :id', { id: row.id });
124
+ return { removed: true, bytesRemoved, attachment: row };
125
+ }
126
+
127
+ export function pruneOrphans(conn, { attachmentsRoot, dryRun = false } = {}) {
128
+ const rows = listOrphans(conn);
129
+ const removed = [];
130
+ const skipped = [];
131
+ for (const row of rows) {
132
+ if (dryRun) {
133
+ removed.push(row);
134
+ continue;
135
+ }
136
+ const still = conn.get(
137
+ `SELECT 1 AS x FROM task_attach WHERE attachment_id = :id
138
+ UNION ALL SELECT 1 FROM ref_attach WHERE attachment_id = :id LIMIT 1`,
139
+ { id: row.id }
140
+ );
141
+ if (still) {
142
+ skipped.push(row);
143
+ continue;
144
+ }
145
+ if (row.kind === 'file' && row.localPath && within(attachmentsRoot, row.localPath)) {
146
+ try {
147
+ if (existsSync(row.localPath)) unlinkSync(row.localPath);
148
+ } catch {
149
+ /* 文件被占用:留到下次,先不删行(否则会变成无记录的残文件) */
150
+ skipped.push(row);
151
+ continue;
152
+ }
153
+ }
154
+ conn.run('DELETE FROM attachments WHERE id = :id AND deleted_at IS NULL', { id: row.id });
155
+ removed.push(row);
156
+ }
157
+ return { removed, skipped };
158
+ }
159
+
160
+ /** 迁移后归档旧 manifest(运行时不再写它,归档只是留证据)。 */
161
+ export function archiveAttachmentManifests(root, tag) {
162
+ const out = [];
163
+ if (!root || !existsSync(root)) return out;
164
+ const candidates = [];
165
+ const local = join(root, 'local', 'manifest.json');
166
+ if (existsSync(local)) candidates.push(local);
167
+ let entries = [];
168
+ try {
169
+ entries = readdirSync(root, { withFileTypes: true });
170
+ } catch {
171
+ entries = [];
172
+ }
173
+ for (const e of entries) {
174
+ if (!e.isDirectory() || e.name === 'local') continue;
175
+ const p = join(root, e.name, 'manifest.json');
176
+ if (existsSync(p)) candidates.push(p);
177
+ }
178
+ for (const from of candidates) {
179
+ const to = from.replace(/manifest\.json$/i, `manifest.migrated-${tag}.json`);
180
+ try {
181
+ if (existsSync(to)) continue;
182
+ renameSync(from, to);
183
+ out.push({ from, to });
184
+ } catch {
185
+ /* 归档失败不影响运行时(DB 已是唯一真相) */
186
+ }
187
+ }
188
+ return out;
189
+ }
@@ -0,0 +1,153 @@
1
+ // 关系表写入(任务/文档共用一套语义)。
2
+ //
3
+ // role 是**边的语义**,不是资源的属性;同一资源对同一宿主只有一行(PK)。
4
+ // 冲突时的处置规则(2026-11-08 附件区改造):
5
+ // 已有 role 优先级 >= 新 role → 保留已有(正文同步不能把用户显式挂的东西降级);
6
+ // 否则升级(正文里出现的资源后来被显式挂载 → attach,删正文行也不会丢);
7
+ // 同 role 重复写只刷新 position(正文改了,顺序跟着改)。
8
+ // 优先级 attach > doc > reference > inline:越"显式"越不容易被正文覆盖。
9
+ import { parseAttachmentRefs } from './ids.js';
10
+ import { ensureAttachment } from './resources.js';
11
+
12
+ const ROLE_PRIORITY = { inline: 0, reference: 1, doc: 2, attach: 3 };
13
+ const HOST_TABLE = {
14
+ task: { table: 'task_attach', col: 'task_id', roles: ['inline', 'attach', 'doc'] },
15
+ ref: { table: 'ref_attach', col: 'ref_id', roles: ['inline', 'attach', 'reference'] },
16
+ };
17
+
18
+ function hostOf(host) {
19
+ const h = HOST_TABLE[String(host || '')];
20
+ if (!h) throw new Error(`未知附件宿主: ${host}(应为 task 或 ref)`);
21
+ return h;
22
+ }
23
+
24
+ /**
25
+ * 写一条宿主 ↔ 资源的关系(upsert,带 role 优先级)。
26
+ *
27
+ * note 是**边上的说明**(desc):只在与现存 role 同级且调用方**显式给了** note
28
+ * (!== undefined)时才更新——正文同步等不关心 note 的调用方不传,就不会把
29
+ * 用户写的说明冲掉(#162:attach --ref --note 走 embed 路径时说明不再丢)。
30
+ * @returns {string} 实际落库的 role
31
+ */
32
+ export function linkAttachment(conn, {
33
+ host, hostId, attachmentId, role = 'attach', position, note, atMs = Date.now(),
34
+ } = {}) {
35
+ const h = hostOf(host);
36
+ const hostVal = host === 'task' ? Number(hostId) : String(hostId || '');
37
+ const att = String(attachmentId || '');
38
+ if (!att) throw new Error('linkAttachment 需要 attachmentId');
39
+ if (!h.roles.includes(role)) throw new Error(`非法 role: ${role}(${host} 只允许 ${h.roles.join('/')})`);
40
+ const idOk = host === 'task' ? Number.isFinite(hostVal) : !!hostVal;
41
+ if (!idOk) throw new Error(`linkAttachment 需要有效的 ${host} 宿主 id`);
42
+
43
+ const cur = conn.get(
44
+ `SELECT role, position FROM ${h.table} WHERE ${h.col} = :host AND attachment_id = :att`,
45
+ { host: hostVal, att }
46
+ );
47
+ if (cur) {
48
+ const curRank = ROLE_PRIORITY[cur.role] ?? 0;
49
+ const newRank = ROLE_PRIORITY[role] ?? 0;
50
+ if (curRank > newRank) return cur.role; // 显式边不被正文降级
51
+ if (curRank === newRank) {
52
+ const pos = position === undefined ? cur.position : position;
53
+ if (note === undefined) {
54
+ conn.run(
55
+ `UPDATE ${h.table} SET position = :pos WHERE ${h.col} = :host AND attachment_id = :att`,
56
+ { pos: Number(pos) || 0, host: hostVal, att }
57
+ );
58
+ } else {
59
+ conn.run(
60
+ `UPDATE ${h.table} SET position = :pos, note = :note
61
+ WHERE ${h.col} = :host AND attachment_id = :att`,
62
+ { pos: Number(pos) || 0, note: String(note || ''), host: hostVal, att }
63
+ );
64
+ }
65
+ return cur.role;
66
+ }
67
+ conn.run(
68
+ `UPDATE ${h.table} SET role = :role, position = :pos, note = :note
69
+ WHERE ${h.col} = :host AND attachment_id = :att`,
70
+ { role, pos: Number(position) || 0, note: String(note || ''), host: hostVal, att }
71
+ );
72
+ return role;
73
+ }
74
+ let pos = position;
75
+ if (pos === undefined) {
76
+ // 附件区(非 inline)默认追加到末尾;inline 的 position 由正文解析给出
77
+ const row = conn.get(
78
+ `SELECT COALESCE(MAX(position), -1) + 1 AS next FROM ${h.table}
79
+ WHERE ${h.col} = :host AND role <> 'inline'`,
80
+ { host: hostVal }
81
+ );
82
+ pos = Number((row && row.next) || 0);
83
+ }
84
+ conn.run(
85
+ `INSERT INTO ${h.table} (${h.col}, attachment_id, role, position, note, created_at)
86
+ VALUES (:host, :att, :role, :pos, :note, :at)`,
87
+ { host: hostVal, att, role, pos: Number(pos) || 0, note: String(note || ''), at: atMs }
88
+ );
89
+ return role;
90
+ }
91
+
92
+ /** 解除一条关系(只删边,不删资源字节)。返回是否真的删掉。 */
93
+ export function unlinkAttachment(conn, { host, hostId, attachmentId } = {}) {
94
+ const h = hostOf(host);
95
+ const hostVal = host === 'task' ? Number(hostId) : String(hostId || '');
96
+ const att = String(attachmentId || '');
97
+ const r = conn.run(
98
+ `DELETE FROM ${h.table} WHERE ${h.col} = :host AND attachment_id = :att`,
99
+ { host: hostVal, att }
100
+ );
101
+ return Number(r.changes) || 0;
102
+ }
103
+
104
+ /** 任务正文里的资源整组重写(只动 inline 边,显式 attach/doc 保留)。 */
105
+ export function syncTaskAttachments(conn, { taskId, text, atMs = Date.now() } = {}) {
106
+ const id = Number(taskId);
107
+ if (!Number.isFinite(id)) return 0;
108
+ const refs = parseAttachmentRefs(text);
109
+ const ids = [];
110
+ for (const r of refs) {
111
+ const att = ensureAttachment(conn, r, { atMs });
112
+ if (att && !ids.includes(att)) ids.push(att);
113
+ }
114
+ // 整组重写前先把边上的说明(note,#162)抄下来:正文同步只管「正文里有哪些引用」,
115
+ // 不该把用户写在该边上的 desc 冲掉——重插时原样带回。
116
+ const notes = new Map(
117
+ conn.all("SELECT attachment_id, note FROM task_attach WHERE task_id = :id AND role = 'inline'", { id })
118
+ .map((r) => [r.attachment_id, r.note])
119
+ );
120
+ conn.run("DELETE FROM task_attach WHERE task_id = :id AND role = 'inline'", { id });
121
+ ids.forEach((att, pos) => {
122
+ linkAttachment(conn, {
123
+ host: 'task', hostId: id, attachmentId: att, role: 'inline', position: pos,
124
+ note: notes.has(att) ? notes.get(att) : undefined, atMs,
125
+ });
126
+ });
127
+ return ids.length;
128
+ }
129
+
130
+ /** 文档正文里的资源整组重写(inline + reference 边;显式 attach 保留)。 */
131
+ export function syncRefAttachments(conn, { refId, text, atMs = Date.now() } = {}) {
132
+ const id = String(refId || '');
133
+ if (!id) return 0;
134
+ const refs = parseAttachmentRefs(text);
135
+ const rows = [];
136
+ for (const r of refs) {
137
+ const att = ensureAttachment(conn, r, { atMs });
138
+ if (att && !rows.some((x) => x.id === att)) rows.push({ id: att, role: r.role });
139
+ }
140
+ // 同任务侧:整组重写保留边上的说明(note)。
141
+ const notes = new Map(
142
+ conn.all("SELECT attachment_id, note FROM ref_attach WHERE ref_id = :id AND role IN ('inline', 'reference')", { id })
143
+ .map((r) => [r.attachment_id, r.note])
144
+ );
145
+ conn.run("DELETE FROM ref_attach WHERE ref_id = :id AND role IN ('inline', 'reference')", { id });
146
+ rows.forEach((x, pos) => {
147
+ linkAttachment(conn, {
148
+ host: 'ref', hostId: id, attachmentId: x.id, role: x.role, position: pos,
149
+ note: notes.has(x.id) ? notes.get(x.id) : undefined, atMs,
150
+ });
151
+ });
152
+ return rows.length;
153
+ }