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
@@ -0,0 +1,181 @@
1
+ // 文档附件(ref_attach:文档的资源关系,与任务侧同一套语义)。
2
+ import { getDoc, updateDoc } from './service.js';
3
+ import { badInput } from '../../core/errors.js';
4
+ import { getDb } from '../../core/db/index.js';
5
+ import { tx } from '../../core/db/tx.js';
6
+ import {
7
+ deleteAttachment,
8
+ ensureDocRef,
9
+ ensureRefAttachment,
10
+ ensureTaskAttachment,
11
+ ensureUrlAttachment,
12
+ linkAttachment,
13
+ listRefAttachments,
14
+ refIdFor,
15
+ resolveRefId,
16
+ unlinkAttachment,
17
+ upsertFileAttachment,
18
+ } from '../../core/attachmentdb.js';
19
+ import { localUpload } from '../../core/localatt.js';
20
+ import { contentTypeOf, isImageName } from '../../core/fileapi.js';
21
+ import { attachmentsRootFromEnv } from '../../core/paths.js';
22
+ import { readFile } from 'node:fs/promises';
23
+ import { basename, resolve as resolvePath } from 'node:path';
24
+
25
+ const clean = (v) => String(v || '').trim();
26
+
27
+ /** 取文档的 locator(refs 的稳定键):自有 = rel,外部 = 绝对路径(POSIX)。 */
28
+ async function docLocatorOf(ref) {
29
+ const d = await getDoc({ ref });
30
+ if (!d || d.missing) throw badInput('文档不存在: ' + String(ref || ''));
31
+ if (d.dir) throw badInput('目录绑定不能挂附件(请指定单个文档)');
32
+ const locator = String(d.rel || d.path || '').replace(/\\/g, '/');
33
+ if (!locator) throw badInput('无法定位文档: ' + String(ref || ''));
34
+ return { d, locator };
35
+ }
36
+
37
+ /** 这篇文档用了哪些资源(ref_attach:图片/文件/URL/内部 task、ref 引用)。 */
38
+ export async function listDocAttachments({ ref } = {}) {
39
+ const d = await getDoc({ ref });
40
+ const locator = String(d.rel || d.path || '').replace(/\\/g, '/');
41
+ if (!locator) throw badInput('无法定位文档: ' + String(ref || ''));
42
+ return { refId: refIdFor(locator), locator, attachments: listRefAttachments(getDb(), refIdFor(locator)) };
43
+ }
44
+
45
+ /**
46
+ * 文档挂附件(`docs attach`):与任务侧同一条写入路径——
47
+ * attachments(资源)+ ref_attach(关系,role=attach);
48
+ * 默认把 markdown 追加进正文,`--no-embed` 只挂附件区。
49
+ */
50
+ export async function attachToDoc(ctx) {
51
+ const { d, locator } = await docLocatorOf(ctx.ref);
52
+ const db = getDb();
53
+ const displayName0 = clean(ctx.name);
54
+ let attachmentId = '';
55
+ let kind = '';
56
+ let displayName = displayName0;
57
+ let markdown = '';
58
+
59
+ const mod = await import('../../shared/attach.js');
60
+ if (ctx.path) {
61
+ const abs = resolvePath(String(ctx.path));
62
+ let buffer;
63
+ try {
64
+ buffer = await readFile(abs);
65
+ } catch (e) {
66
+ throw badInput(`读不到文件: ${abs}(${(e && e.code) || e.message})`);
67
+ }
68
+ const fileName = displayName || basename(abs);
69
+ const rec = await localUpload({ name: fileName, buffer, contentType: contentTypeOf(fileName) });
70
+ displayName = rec.name;
71
+ kind = isImageName(rec.name, rec.contentType) ? 'image' : 'file';
72
+ tx(
73
+ (conn) => upsertFileAttachment(conn, {
74
+ id: rec.fileId,
75
+ name: rec.name,
76
+ localPath: rec.path,
77
+ mime: rec.contentType,
78
+ size: rec.size,
79
+ storage: 'local',
80
+ meta: { isImage: kind === 'image', source: 'docs-cli' },
81
+ }),
82
+ { db, mode: 'IMMEDIATE' }
83
+ );
84
+ attachmentId = rec.fileId;
85
+ markdown = mod.embedMarkdown({ name: displayName, id: rec.fileId, kind });
86
+ } else if (ctx.fileId) {
87
+ const fid = String(ctx.fileId).trim();
88
+ if (!mod.looksLikeFileId(fid)) throw badInput(`附件 id 不合法: ${fid}`);
89
+ kind = isImageName(fid, '') ? 'image' : 'file';
90
+ displayName = displayName || fid;
91
+ tx(
92
+ (conn) => upsertFileAttachment(conn, { id: fid, name: displayName, meta: { isImage: kind === 'image' } }),
93
+ { db, mode: 'IMMEDIATE' }
94
+ );
95
+ attachmentId = fid;
96
+ markdown = mod.embedMarkdown({ name: displayName, id: fid, kind });
97
+ } else if (ctx.url) {
98
+ const u = String(ctx.url).trim();
99
+ if (!/^https?:\/\//i.test(u)) throw badInput(`--url 需要 http(s) 绝对地址: ${u}`);
100
+ attachmentId = tx((conn) => ensureUrlAttachment(conn, { url: u, name: displayName }), { db, mode: 'IMMEDIATE' });
101
+ if (!attachmentId) throw badInput(`URL 登记失败: ${u}`);
102
+ kind = 'url';
103
+ markdown = `[${displayName || u}](${u})`;
104
+ } else if (ctx.task) {
105
+ const tid = Number(String(ctx.task).replace(/^#/, ''));
106
+ if (!Number.isFinite(tid)) throw badInput(`--task 需要任务全局 id: ${ctx.task}`);
107
+ attachmentId = tx((conn) => ensureTaskAttachment(conn, { taskId: tid, name: displayName }), { db, mode: 'IMMEDIATE' });
108
+ if (!attachmentId) throw badInput(`任务不存在: ${ctx.task}`);
109
+ kind = 'task';
110
+ markdown = `[${displayName || `任务 #${tid}`}](nxkv://task/${tid})`;
111
+ } else if (ctx.doc) {
112
+ const target = await docLocatorOf(ctx.doc);
113
+ const refId =
114
+ resolveRefId(db, target.locator) ||
115
+ tx((conn) => ensureDocRef(conn, { locator: target.locator }), { db, mode: 'IMMEDIATE' });
116
+ if (!refId) throw badInput(`找不到文档: ${ctx.doc}`);
117
+ attachmentId = tx((conn) => ensureRefAttachment(conn, { refId, name: displayName }), { db, mode: 'IMMEDIATE' });
118
+ if (!attachmentId) throw badInput(`找不到文档: ${ctx.doc}`);
119
+ kind = 'ref';
120
+ markdown = `[${displayName || target.locator.split('/').pop()}](nxkv://ref/${refId})`;
121
+ }
122
+
123
+ if (!attachmentId) {
124
+ throw badInput('需要 --path / --fileId / --url / --task / --doc 之一');
125
+ }
126
+
127
+ const noEmbed = !!(ctx.noEmbed ?? ctx['no-embed']);
128
+ const role = noEmbed ? 'attach' : 'inline';
129
+ if (noEmbed) {
130
+ tx(
131
+ (conn) => {
132
+ const refId = ensureDocRef(conn, { locator });
133
+ linkAttachment(conn, { host: 'ref', hostId: refId, attachmentId, role: 'attach', note: ctx.note });
134
+ },
135
+ { db, mode: 'IMMEDIATE' }
136
+ );
137
+ } else {
138
+ const body = d.body || '';
139
+ const next = body ? `${body}\n${markdown}` : markdown;
140
+ await updateDoc({ ref: ctx.ref, body: next });
141
+ }
142
+
143
+ return {
144
+ status: 'ok',
145
+ ref: locator,
146
+ attachmentId,
147
+ kind,
148
+ area: noEmbed ? 'area' : 'inline',
149
+ role,
150
+ markdown,
151
+ };
152
+ }
153
+
154
+ /** 解除文档与资源的关系;--purge 在无人引用时连资源行与本机字节一起删。 */
155
+ export async function detachFromDoc({ ref, attachment, purge } = {}) {
156
+ const { locator } = await docLocatorOf(ref);
157
+ const attId = String(attachment || '').trim();
158
+ if (!attId) throw badInput('需要 --attachment <资源 id>(见 docs attachments 输出)');
159
+ const db = getDb();
160
+ let unlinked = 0;
161
+ let purgeResult = null;
162
+ tx(
163
+ (conn) => {
164
+ const refId = ensureDocRef(conn, { locator });
165
+ unlinked = unlinkAttachment(conn, { host: 'ref', hostId: refId, attachmentId: attId });
166
+ if (purge && unlinked) {
167
+ purgeResult = deleteAttachment(conn, attId, { attachmentsRoot: attachmentsRootFromEnv() });
168
+ }
169
+ },
170
+ { db, mode: 'IMMEDIATE' }
171
+ );
172
+ return {
173
+ status: 'ok',
174
+ ref: locator,
175
+ attachment: attId,
176
+ unlinked,
177
+ purged: !!(purgeResult && purgeResult.removed),
178
+ purgeReason: purgeResult ? purgeResult.reason || '' : '',
179
+ bytesRemoved: !!(purgeResult && purgeResult.bytesRemoved),
180
+ };
181
+ }
@@ -6,425 +6,26 @@
6
6
  //
7
7
  // resource: 'doc' 触发 CRUD 五件断言(tests/unit/registry.test.mjs):
8
8
  // doc.list / doc.get / doc.add / doc.update / doc.remove 必须齐备且两端可调。
9
- import * as paths from './paths.js';
10
- import * as store from './store.js';
9
+ //
10
+ // 业务逻辑在 ./service.js(CRUD + 外部写回),附件在 ./attach.js,
11
+ // CLI 人读渲染在 ./render.js —— 本文件只剩模块声明与 action 表。
11
12
  import * as seed from './seed.js';
12
13
  import * as refs from './refs.js';
13
14
  import * as links from './links.js';
14
- import { reposBridge } from './repos-bridge.js';
15
- import { badInput, blocked } from '../../core/errors.js';
16
- import { getDb } from '../../core/db/index.js';
17
- import { tx } from '../../core/db/tx.js';
15
+ import { addDoc, getDoc, listDocs, removeDoc, updateDoc } from './service.js';
16
+ import { attachToDoc, detachFromDoc, listDocAttachments } from './attach.js';
18
17
  import {
19
- deleteAttachment,
20
- ensureDocRef,
21
- ensureRefAttachment,
22
- ensureTaskAttachment,
23
- ensureUrlAttachment,
24
- linkAttachment,
25
- listRefAttachments,
26
- refIdFor,
27
- resolveRefId,
28
- syncRefAttachments,
29
- unlinkAttachment,
30
- upsertFileAttachment,
31
- } from '../../core/attachmentdb.js';
32
- import { localUpload } from '../../core/localatt.js';
33
- import { contentTypeOf, isImageName } from '../../core/fileapi.js';
34
- import { attachmentsRootFromEnv } from '../../core/paths.js';
35
- import { readFile } from 'node:fs/promises';
36
- import { basename, resolve as resolvePath } from 'node:path';
37
- import fsp from 'node:fs/promises';
38
- import path from 'node:path';
39
-
40
- const clean = (v) => String(v || '').trim();
41
-
42
- // list/get 的人读渲染共用的标题行:rel 或 path,缺省标题来自正文首个 #
43
- function docHead(d) {
44
- const addr = d.rel ? d.rel : d.path || d.docId;
45
- const head = d.title ? `「${d.title}」` : '';
46
- const extra = d.summary && d.summary !== d.title ? ` · ${d.summary}` : '';
47
- return `${addr}${head}${extra}`;
48
- }
49
-
50
- // ─── 查 ────────────────────────────────────────────────────────────────
51
-
52
- // 树索引(零副作用,不播种——agent/前端拿它当双链解析的数据源)
53
- async function listDocs({ external } = {}) {
54
- const docs = [];
55
- for (const f of await store.listOwnDocs()) {
56
- const title = /^#\s+(.+)$/m.exec(f.size <= 512 * 1024 ? await safeRead(f.abs) : '');
57
- docs.push({
58
- docId: paths.ownDocId(f.rel),
59
- rel: f.rel,
60
- name: f.rel.replace(/\.md$/i, '').split('/').pop(),
61
- title: title ? title[1].trim() : '',
62
- size: f.size,
63
- });
64
- }
65
- const out = { docs, count: docs.length };
66
- if (external) {
67
- const { loadStore } = await reposBridge();
68
- const s = await loadStore();
69
- const closure = await store.externalClosure(s);
70
- const files = await store.listExternalDocs(closure);
71
- out.external = files.map((abs) => ({ docId: paths.extDocId(abs), path: abs, name: abs.replace(/\\/g, '/').split('/').pop().replace(/\.md$/i, '') }));
72
- out.bound = closure.map((c) => ({ path: c.path, owner: c.owner, exists: c.exists, isDir: c.isDir }));
73
- }
74
- return out;
75
- }
76
-
77
- async function safeRead(abs) {
78
- try {
79
- return await fsp.readFile(abs, 'utf8');
80
- } catch {
81
- return '';
82
- }
83
- }
84
-
85
- // 读全文:自有(惰性播种)/ 外部(闭包内才放行);目录绑定返回文件清单
86
- async function getDoc({ ref } = {}) {
87
- if (!clean(ref)) throw badInput('请给文档标识:自有 rel:<路径>(或裸相对路径),外部 path:<绝对路径>');
88
- const parsed = paths.parseDocId(ref);
89
- if (parsed.kind === 'own') {
90
- let body = null;
91
- try {
92
- body = await store.readOwnDoc(parsed.rel);
93
- } catch {
94
- const seeded = await seed.ensureSeedForRel(parsed.rel);
95
- if (seeded === null) {
96
- return { docId: paths.ownDocId(parsed.rel), rel: parsed.rel, missing: true, writable: true, title: '', summary: '', body: '' };
97
- }
98
- body = seeded;
99
- }
100
- return outOwn(parsed.rel, body);
101
- }
102
- // 外部:先过绑定闭包,闭包外一律拒绝——doc.get 不能变成任意文件读入口
103
- const { loadStore } = await reposBridge();
104
- const s = await loadStore();
105
- const closure = await store.externalClosure(s);
106
- const abs = store.resolveExternal(parsed.path, closure);
107
- if (!abs) throw blocked(`外部路径不在绑定闭包内(先 docs bind 登记): ${parsed.path}`);
108
- let st = null;
109
- try {
110
- st = await fsp.stat(abs);
111
- } catch {
112
- /* 缺失:按 missing 返回 */
113
- }
114
- if (!st) {
115
- return { docId: paths.extDocId(abs), path: abs, missing: true, writable: true, title: '', summary: '', body: '' };
116
- }
117
- if (st.isDirectory()) {
118
- const files = await store.listExternalDocs([{ path: abs, exists: true, isDir: true }], { maxDepth: 3, maxFiles: 200 });
119
- return { docId: paths.extDocId(abs), path: abs, dir: true, writable: false, files };
120
- }
121
- return outExternal(abs, await safeRead(abs));
122
- }
123
-
124
- // ─── 增 / 改 / 删 ──────────────────────────────────────────────────────
125
- //
126
- // 读写口径(2026-11 任务 #88「简介文档优化」):
127
- // rel: 自有树(~/.nx-kv/docs/)——可读可写可删
128
- // path: 外部(Obsidian vault / 任意登记目录)——**登记在册即可写**:
129
- // 读侧要求路径在绑定闭包内;写侧再校验一次(闭包 + .md + 非目录),
130
- // 等于「文档集里的每一篇都能就地改」,同时不把 PATCH 变成任意文件写入口。
131
- // 删除仍不给外部:删除是可恢复性最差的操作,让它回来源做。
132
-
133
- // body-file 只给 CLI(templates 先例):HTTP 是面板的通道,不该变成任意读本机文件的入口
134
- async function bodyOf({ body, bodyFile }, opts) {
135
- const fileArg = opts && opts.transport === 'http' ? undefined : bodyFile;
136
- if (typeof body === 'string') return body;
137
- if (fileArg !== undefined) {
138
- const { readFileSync } = await import('node:fs');
139
- return readFileSync(fileArg === '-' ? 0 : fileArg, 'utf8');
140
- }
141
- return null;
142
- }
143
-
144
- async function addDoc(ctx, opts) {
145
- const rel = await store.writeOwnDoc(ctx.rel, (await bodyOf(ctx, opts)) ?? '');
146
- const body = await store.readOwnDoc(rel);
147
- const summary = await seed.writeBackSummary(rel, body);
148
- return { docId: paths.ownDocId(rel), rel, bytes: Buffer.byteLength(body, 'utf8'), summary };
149
- }
150
-
151
- // 外部文档写回(面板/CLI 均可):路径必须仍在**绑定闭包**内——闭包是唯一的授权来源,
152
- // 否则 PATCH 就成了任意文件写入口(与 getDoc 的读侧守卫同口径)。
153
- // 目录绑定只允许改写目录内的 .md;单文件绑定只允许那一个文件。
154
- async function writeExternalDoc(abs, body) {
155
- const { loadStore } = await reposBridge();
156
- const s = await loadStore();
157
- const closure = await store.externalClosure(s);
158
- const hit = store.resolveExternal(abs, closure);
159
- if (!hit) throw blocked(`外部路径不在绑定闭包内(先 docs bind 登记): ${abs}`);
160
- if (!/\.md$/i.test(abs)) throw badInput('只能写回 .md 文档: ' + abs);
161
- let st = null;
162
- try {
163
- st = await fsp.stat(abs);
164
- } catch {
165
- st = null;
166
- }
167
- if (st && st.isDirectory()) throw blocked('这是目录绑定,不能整体写回: ' + abs);
168
- await fsp.mkdir(path.dirname(abs), { recursive: true });
169
- await fsp.writeFile(abs, body, 'utf8');
170
- const saved = await safeRead(abs);
171
- // 外部文档同样是「文档库的一行」:正文里的 fileId / nxkv 链接也落 ref_attach。
172
- // 与自有树同一事务口径(ensureDocRef 幂等;refs 只装 .md)。
173
- const db = getDb();
174
- tx(
175
- (conn) => {
176
- const refId = ensureDocRef(conn, { locator: abs });
177
- syncRefAttachments(conn, { refId, text: saved });
178
- },
179
- { db, mode: 'IMMEDIATE' }
180
- );
181
- return { docId: paths.extDocId(abs), path: abs, bytes: Buffer.byteLength(saved, 'utf8'), external: true };
182
- }
183
-
184
- async function updateDoc(ctx, opts) {
185
- const parsed = paths.parseDocId(ctx.ref);
186
- const body = await bodyOf(ctx, opts);
187
- if (body === null) throw badInput('请给 --body <正文>(多行用 --body-file <文件> 或 - 读管道)');
188
- // 外部绑定:登记在册 = 我的文档集,允许就地写回来源文件(闭包内校验)
189
- if (parsed.kind !== 'own') return writeExternalDoc(parsed.path, body);
190
- // 不存在即创建(面板保存语义:脏页签保存不该因为别人先建了而失败,也不该在这里静默分叉出第二份)
191
- const rel = await store.writeOwnDoc(parsed.rel, body);
192
- const saved = await store.readOwnDoc(rel);
193
- const summary = await seed.writeBackSummary(rel, saved);
194
- return { docId: paths.ownDocId(rel), rel, bytes: Buffer.byteLength(saved, 'utf8'), summary };
195
- }
196
-
197
- async function removeDoc({ ref } = {}) {
198
- const parsed = paths.parseDocId(ref);
199
- if (parsed.kind !== 'own') throw blocked('外部绑定是只读引用,不能在这里删除');
200
- const rel = await store.removeOwnDoc(parsed.rel);
201
- return { docId: paths.ownDocId(rel), rel };
202
- }
203
-
204
- // ─── 出参整形 ──────────────────────────────────────────────────────────
205
-
206
- function outOwn(rel, body) {
207
- const { summaryFromMd } = seed;
208
- const m = /^#\s+(.+)$/m.exec(body);
209
- return {
210
- docId: paths.ownDocId(rel),
211
- rel,
212
- title: m ? m[1].trim() : '',
213
- summary: summaryFromMd(body),
214
- body,
215
- writable: true,
216
- };
217
- }
218
-
219
- function outExternal(abs, body) {
220
- const m = /^#\s+(.+)$/m.exec(body);
221
- return {
222
- docId: paths.extDocId(abs),
223
- path: abs,
224
- title: m ? m[1].trim() : '',
225
- summary: seed.summaryFromMd(body),
226
- body,
227
- // 登记在册的外部文档 = 用户的文档集,允许就地写回来源文件(写侧另过闭包校验)
228
- writable: true,
229
- external: true,
230
- };
231
- }
232
-
233
- // ─── CLI 人读渲染 ──────────────────────────────────────────────────────
234
-
235
- const renderList = (d) => {
236
- const lines = [`自有文档 ${d.count} 个(~/.nx-kv/docs/,env NX_KV_DOCS_DIR 可覆盖)`];
237
- for (const x of d.docs) lines.push(` ${x.rel} ${x.title || x.name}`);
238
- if (d.external?.length) {
239
- lines.push(`外部文档 ${d.external.length} 个(只读引用):`);
240
- for (const x of d.external) lines.push(` ${x.path}`);
241
- }
242
- if (!d.count && !d.external?.length) {
243
- lines.push('(还没有文档——描述字符串会在首次读取时播种为 md,或直接 docs seed --apply)');
244
- }
245
- return lines.join('\n');
246
- };
247
-
248
- const renderGet = (d) => {
249
- if (d.missing) return `(文档不存在: ${d.rel || d.path})`;
250
- if (d.dir) return `(外部目录绑定: ${d.path},${d.files.length} 个文档)\n ${d.files.slice(0, 20).join('\n ')}`;
251
- const head = [`【${d.title || docHead(d)}】`, ` ${d.rel || d.path}${d.external ? ' (外部 · 可写回来源)' : ''}`, ''];
252
- return head.join('\n') + d.body;
253
- };
254
-
255
- const renderWritten = (d) =>
256
- `已写入 ${d.rel}(${d.bytes} 字节)${d.summary ? `\n摘要已回写: ${d.summary}` : ''}`;
257
-
258
- const renderSeed = (d) => {
259
- if (d.written !== undefined) return `已播种 ${d.written} 份文档:\n ${(d.items || []).join('\n ') || '(无)'}`;
260
- if (!d.count) return '没有需要播种的文档(字符串字段都为空,或约定路径已有 md)';
261
- return `待播种 ${d.count} 份(--apply 执行):\n ${d.items.map((x) => `${x.rel} ←「${x.title}」`).join('\n ')}`;
262
- };
263
-
264
- const renderRef = (d) =>
265
- `${d.ref ? '已绑定' : '已拆绑定(回到约定路径)'}: ${d.kind} ${d.name} → ${d.ref ? (d.ref.rel ? 'rel:' + d.ref.rel : 'path:' + d.ref.path) : '约定路径'}`;
266
-
267
- const renderNoteRef = (d) =>
268
- `${d.ref ? '已绑定' : '已拆绑定'}: 「${d.boardName}」× ${d.repoKey} → ${d.ref ? (d.ref.rel ? 'rel:' + d.ref.rel : 'path:' + d.ref.path) : '约定路径'}`;
269
-
270
- const renderLink = (d) => {
271
- if (d.removed !== undefined) return `已移除组绑定: ${d.removed}(剩 ${d.count} 条)`;
272
- const lines = [`「${d.boardName}」的组绑定(${d.count} 条):`];
273
- for (const l of d.links) {
274
- lines.push(` ${l.rel ? 'rel:' + l.rel : 'path:' + l.path}${l.tag ? ` [${l.tag}]` : ''}${l.note ? ` · ${l.note}` : ''}`);
275
- }
276
- return lines.join('\n');
277
- };
278
-
279
- // ─── 附件(ref_attach:文档的资源关系,与任务侧同一套语义) ──────────────
280
-
281
- /** 取文档的 locator(refs 的稳定键):自有 = rel,外部 = 绝对路径(POSIX)。 */
282
- async function docLocatorOf(ref) {
283
- const d = await getDoc({ ref });
284
- if (!d || d.missing) throw badInput('文档不存在: ' + String(ref || ''));
285
- if (d.dir) throw badInput('目录绑定不能挂附件(请指定单个文档)');
286
- const locator = String(d.rel || d.path || '').replace(/\\/g, '/');
287
- if (!locator) throw badInput('无法定位文档: ' + String(ref || ''));
288
- return { d, locator };
289
- }
290
-
291
- /**
292
- * 文档挂附件(`docs attach`):与任务侧同一条写入路径——
293
- * attachments(资源)+ ref_attach(关系,role=attach);
294
- * 默认把 markdown 追加进正文,`--no-embed` 只挂附件区。
295
- */
296
- async function attachToDoc(ctx) {
297
- const { d, locator } = await docLocatorOf(ctx.ref);
298
- const db = getDb();
299
- const displayName0 = clean(ctx.name);
300
- let attachmentId = '';
301
- let kind = '';
302
- let displayName = displayName0;
303
- let markdown = '';
304
-
305
- const mod = await import('../../shared/attach.js');
306
- if (ctx.path) {
307
- const abs = resolvePath(String(ctx.path));
308
- let buffer;
309
- try {
310
- buffer = await readFile(abs);
311
- } catch (e) {
312
- throw badInput(`读不到文件: ${abs}(${(e && e.code) || e.message})`);
313
- }
314
- const fileName = displayName || basename(abs);
315
- const rec = await localUpload({ name: fileName, buffer, contentType: contentTypeOf(fileName) });
316
- displayName = rec.name;
317
- kind = isImageName(rec.name, rec.contentType) ? 'image' : 'file';
318
- tx(
319
- (conn) => upsertFileAttachment(conn, {
320
- id: rec.fileId,
321
- name: rec.name,
322
- localPath: rec.path,
323
- mime: rec.contentType,
324
- size: rec.size,
325
- storage: 'local',
326
- meta: { isImage: kind === 'image', source: 'docs-cli' },
327
- }),
328
- { db, mode: 'IMMEDIATE' }
329
- );
330
- attachmentId = rec.fileId;
331
- markdown = mod.embedMarkdown({ name: displayName, id: rec.fileId, kind });
332
- } else if (ctx.fileId) {
333
- const fid = String(ctx.fileId).trim();
334
- if (!mod.looksLikeFileId(fid)) throw badInput(`附件 id 不合法: ${fid}`);
335
- kind = isImageName(fid, '') ? 'image' : 'file';
336
- displayName = displayName || fid;
337
- tx(
338
- (conn) => upsertFileAttachment(conn, { id: fid, name: displayName, meta: { isImage: kind === 'image' } }),
339
- { db, mode: 'IMMEDIATE' }
340
- );
341
- attachmentId = fid;
342
- markdown = mod.embedMarkdown({ name: displayName, id: fid, kind });
343
- } else if (ctx.url) {
344
- const u = String(ctx.url).trim();
345
- if (!/^https?:\/\//i.test(u)) throw badInput(`--url 需要 http(s) 绝对地址: ${u}`);
346
- attachmentId = tx((conn) => ensureUrlAttachment(conn, { url: u, name: displayName }), { db, mode: 'IMMEDIATE' });
347
- if (!attachmentId) throw badInput(`URL 登记失败: ${u}`);
348
- kind = 'url';
349
- markdown = `[${displayName || u}](${u})`;
350
- } else if (ctx.task) {
351
- const tid = Number(String(ctx.task).replace(/^#/, ''));
352
- if (!Number.isFinite(tid)) throw badInput(`--task 需要任务全局 id: ${ctx.task}`);
353
- attachmentId = tx((conn) => ensureTaskAttachment(conn, { taskId: tid, name: displayName }), { db, mode: 'IMMEDIATE' });
354
- if (!attachmentId) throw badInput(`任务不存在: ${ctx.task}`);
355
- kind = 'task';
356
- markdown = `[${displayName || `任务 #${tid}`}](nxkv://task/${tid})`;
357
- } else if (ctx.doc) {
358
- const target = await docLocatorOf(ctx.doc);
359
- const refId =
360
- resolveRefId(db, target.locator) ||
361
- tx((conn) => ensureDocRef(conn, { locator: target.locator }), { db, mode: 'IMMEDIATE' });
362
- if (!refId) throw badInput(`找不到文档: ${ctx.doc}`);
363
- attachmentId = tx((conn) => ensureRefAttachment(conn, { refId, name: displayName }), { db, mode: 'IMMEDIATE' });
364
- if (!attachmentId) throw badInput(`找不到文档: ${ctx.doc}`);
365
- kind = 'ref';
366
- markdown = `[${displayName || target.locator.split('/').pop()}](nxkv://ref/${refId})`;
367
- }
368
-
369
- if (!attachmentId) {
370
- throw badInput('需要 --path / --fileId / --url / --task / --doc 之一');
371
- }
372
-
373
- const noEmbed = !!(ctx.noEmbed ?? ctx['no-embed']);
374
- const role = noEmbed ? 'attach' : 'inline';
375
- if (noEmbed) {
376
- tx(
377
- (conn) => {
378
- const refId = ensureDocRef(conn, { locator });
379
- linkAttachment(conn, { host: 'ref', hostId: refId, attachmentId, role: 'attach', note: ctx.note });
380
- },
381
- { db, mode: 'IMMEDIATE' }
382
- );
383
- } else {
384
- const body = d.body || '';
385
- const next = body ? `${body}\n${markdown}` : markdown;
386
- await updateDoc({ ref: ctx.ref, body: next });
387
- }
388
-
389
- return {
390
- status: 'ok',
391
- ref: locator,
392
- attachmentId,
393
- kind,
394
- area: noEmbed ? 'area' : 'inline',
395
- role,
396
- markdown,
397
- };
398
- }
399
-
400
- /** 解除文档与资源的关系;--purge 在无人引用时连资源行与本机字节一起删。 */
401
- async function detachFromDoc({ ref, attachment, purge } = {}) {
402
- const { locator } = await docLocatorOf(ref);
403
- const attId = String(attachment || '').trim();
404
- if (!attId) throw badInput('需要 --attachment <资源 id>(见 docs attachments 输出)');
405
- const db = getDb();
406
- let unlinked = 0;
407
- let purgeResult = null;
408
- tx(
409
- (conn) => {
410
- const refId = ensureDocRef(conn, { locator });
411
- unlinked = unlinkAttachment(conn, { host: 'ref', hostId: refId, attachmentId: attId });
412
- if (purge && unlinked) {
413
- purgeResult = deleteAttachment(conn, attId, { attachmentsRoot: attachmentsRootFromEnv() });
414
- }
415
- },
416
- { db, mode: 'IMMEDIATE' }
417
- );
418
- return {
419
- status: 'ok',
420
- ref: locator,
421
- attachment: attId,
422
- unlinked,
423
- purged: !!(purgeResult && purgeResult.removed),
424
- purgeReason: purgeResult ? purgeResult.reason || '' : '',
425
- bytesRemoved: !!(purgeResult && purgeResult.bytesRemoved),
426
- };
427
- }
18
+ renderAttach,
19
+ renderAttachments,
20
+ renderDetach,
21
+ renderGet,
22
+ renderLink,
23
+ renderList,
24
+ renderNoteRef,
25
+ renderRef,
26
+ renderSeed,
27
+ renderWritten,
28
+ } from './render.js';
428
29
 
429
30
  export default {
430
31
  id: 'docs',
@@ -507,24 +108,8 @@ export default {
507
108
  http: ['GET', '/api/docs/attachments'],
508
109
  summary: '这篇文档用了哪些资源(ref_attach:图片/文件/URL/内部 task、ref 引用)',
509
110
  args: ['ref'],
510
- run: async (ctx) => {
511
- const d = await getDoc({ ref: ctx.ref });
512
- const locator = String(d.rel || d.path || '').replace(/\\/g, '/');
513
- if (!locator) throw badInput('无法定位文档: ' + String(ctx.ref || ''));
514
- return { refId: refIdFor(locator), locator, attachments: listRefAttachments(getDb(), refIdFor(locator)) };
515
- },
516
- render: (d) => {
517
- if (!d.attachments.length) {
518
- return `「${d.locator}」没有登记资源(docs attach --no-embed 可只挂到附件区)`;
519
- }
520
- const areaOf = (role) => (role === 'attach' ? '附件区' : '正文内嵌');
521
- const lines = [`「${d.locator}」的资源(${d.attachments.length})`];
522
- for (const a of d.attachments) {
523
- const where = a.localPath || a.url || (a.kind === 'task' ? `task ${a.targetKey}#${a.targetSeq}` : a.targetKey);
524
- lines.push(` ${a.id} [${a.kind}/${a.role} · ${areaOf(a.role)}] ${a.name || '-'} ${where || ''}`);
525
- }
526
- return lines.join('\n');
527
- },
111
+ run: (ctx) => listDocAttachments(ctx),
112
+ render: renderAttachments,
528
113
  },
529
114
  {
530
115
  id: 'doc.attach',
@@ -545,8 +130,7 @@ export default {
545
130
  'no-embed': { type: 'boolean', hint: '同 --noEmbed' },
546
131
  },
547
132
  run: attachToDoc,
548
- render: (d) =>
549
- `已附加 ${d.attachmentId}(${d.kind})到「${d.ref}」· ${d.area === 'area' ? '附件区(未写正文)' : '正文内嵌'}${d.markdown ? `\n嵌入: ${d.markdown}` : ''}`,
133
+ render: renderAttach,
550
134
  },
551
135
  {
552
136
  id: 'doc.detach',
@@ -559,19 +143,7 @@ export default {
559
143
  purge: { type: 'boolean', hint: '连资源与字节一起删(仍被引用时拒绝)' },
560
144
  },
561
145
  run: detachFromDoc,
562
- render: (d) => {
563
- const head = d.unlinked
564
- ? `已解除「${d.ref}」与附件 ${d.attachment} 的关系`
565
- : `「${d.ref}」本来就没有引用附件 ${d.attachment}`;
566
- const tail = d.purged
567
- ? ';资源已删除(含本机字节)'
568
- : d.purgeReason === 'in-use'
569
- ? ';资源仍被其他任务/文档引用,未删字节'
570
- : d.purgeReason === 'file-locked'
571
- ? ';文件被占用,未删字节'
572
- : '';
573
- return head + tail;
574
- },
146
+ render: renderDetach,
575
147
  },
576
148
  {
577
149
  id: 'docs.seed',