nx-kv 0.48.2 → 0.49.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 (80) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/package.json +1 -1
  3. package/src/core/attachmentdb/bodies.ts +161 -0
  4. package/src/core/attachmentdb/docs.ts +95 -33
  5. package/src/core/attachmentdb/ids.ts +27 -1
  6. package/src/core/attachmentdb/mdfile.ts +249 -0
  7. package/src/core/attachmentdb/query.ts +14 -1
  8. package/src/core/attachmentdb/resources.ts +23 -0
  9. package/src/core/attachmentdb.ts +22 -0
  10. package/src/core/db/bootstrap.ts +5 -5
  11. package/src/core/db/import-json/refs.ts +27 -13
  12. package/src/core/db/migrations/index.ts +7 -0
  13. package/src/core/db/migrations/v2-data.ts +4 -4
  14. package/src/core/db/migrations/v5.sql +100 -0
  15. package/src/core/db/migrations/v6-data.ts +261 -0
  16. package/src/core/db/migrations/v6.sql +67 -0
  17. package/src/core/db/version.ts +9 -1
  18. package/src/core/paths.ts +10 -0
  19. package/src/modules/docs/actions/_manifest.generated.ts +9 -0
  20. package/src/modules/docs/actions/doc-attach.ts +2 -1
  21. package/src/modules/docs/actions/doc-link-file.ts +28 -0
  22. package/src/modules/docs/actions/doc-mdfile.ts +28 -0
  23. package/src/modules/docs/actions/doc-mdfiles.ts +29 -0
  24. package/src/modules/docs/attach.ts +14 -1
  25. package/src/modules/docs/docref.ts +13 -1
  26. package/src/modules/docs/knowledge.ts +17 -19
  27. package/src/modules/docs/mdfile.ts +24 -0
  28. package/src/modules/docs/paths.ts +6 -9
  29. package/src/modules/docs/render.ts +24 -4
  30. package/src/modules/docs/seed.ts +1 -1
  31. package/src/modules/docs/service.ts +48 -18
  32. package/src/modules/docs/store.ts +120 -74
  33. package/src/modules/localtask/action-render.ts +2 -2
  34. package/src/modules/localtask/actions/localtask-attach.ts +4 -2
  35. package/src/modules/repos/service/bind-topics.ts +8 -18
  36. package/src/modules/repos/service.ts +1 -1
  37. package/src/modules/repos/transfer/export.ts +4 -1
  38. package/src/modules/tasktool/attach-resource.ts +37 -5
  39. package/src/modules/tasktool/attach-template.ts +45 -4
  40. package/src/modules/tasktool/attach.ts +47 -3
  41. package/src/modules/tasktool/doc-inline.ts +54 -29
  42. package/src/shared/prompt-blocks.ts +6 -1
  43. package/src/web/frontend/api/cli-tree.json +47 -2
  44. package/src/web/frontend/api/client.generated.ts +40 -4
  45. package/src/web/frontend/components/md/attach-area.tsx +58 -3
  46. package/src/web/frontend/components/md/attach-common.ts +2 -2
  47. package/src/web/frontend/modules/md/attach-mention.ts +6 -1
  48. package/src/web/frontend/modules/md/styles/chrome.css +25 -0
  49. package/src/web/frontend/page/dir/api.ts +5 -0
  50. package/src/web/frontend/page/dir/task-dock-panel.tsx +87 -2
  51. package/src/web/frontend/page/dir/task-status-bar.tsx +14 -1
  52. package/src/web/frontend/page/dir/task.tsx +2 -0
  53. package/src/web/frontend/page/doc/index.tsx +16 -15
  54. package/src/web/frontend/page/repos/doc-search-modal.tsx +7 -0
  55. package/src/web/public/assets/Introduction-BDS09bo3.js +6 -0
  56. package/src/web/public/assets/{bar-B52NTf_v.js → bar-DBtVMtRi.js} +1 -1
  57. package/src/web/public/assets/{cloud-Droja_aT.js → cloud-0AcS7Mtd.js} +1 -1
  58. package/src/web/public/assets/{composer-panel-DpiU2h50.js → composer-panel-D624x9uT.js} +1 -1
  59. package/src/web/public/assets/{deleted-panel-K9GgfR8t.js → deleted-panel-BeyVhrAI.js} +1 -1
  60. package/src/web/public/assets/{dir-DacRpcBt.js → dir-CYGqeYZU.js} +4 -4
  61. package/src/web/public/assets/{group-TPuU-QVc.js → group-B5cZqWIt.js} +1 -1
  62. package/src/web/public/assets/{index-BkLkooKe.js → index-BLEuH6mL.js} +2 -2
  63. package/src/web/public/assets/{index-DP3qBv1o.css → index-ChWwzUrF.css} +1 -1
  64. package/src/web/public/assets/{md-history-0GBWw4qr.js → md-history-Bpyib4z4.js} +3 -3
  65. package/src/web/public/assets/{overview-B3kHI66i.js → overview-DrsWuDVi.js} +1 -1
  66. package/src/web/public/assets/{prompt-blocks-BovFd039.js → prompt-blocks-CO8msDuJ.js} +1 -1
  67. package/src/web/public/assets/{refs-BDxfuH6R.js → refs-DMVuOOK9.js} +1 -1
  68. package/src/web/public/assets/{repos-C8jRM7wS.js → repos-C5OwK72H.js} +2 -2
  69. package/src/web/public/assets/{route-crumb-QvahotvN.js → route-crumb-6q3rIB-_.js} +1 -1
  70. package/src/web/public/assets/{settings-BBcdGLTc.js → settings-BH_l1Yek.js} +1 -1
  71. package/src/web/public/assets/{status-tag-BheHByek.js → status-tag-BD6cdnyb.js} +1 -1
  72. package/src/web/public/assets/task-B7AjuMiC.js +11 -0
  73. package/src/web/public/assets/task-utils-BNFx9yag.js +12 -0
  74. package/src/web/public/assets/{templates-CbRyW3PJ.js → templates-G7kHB-xI.js} +1 -1
  75. package/src/web/public/assets/tool-bar-DIXBM0wv.js +1 -0
  76. package/src/web/public/index.html +2 -2
  77. package/src/web/public/assets/Introduction-Du_dycft.js +0 -6
  78. package/src/web/public/assets/task-CUkQaLBZ.js +0 -11
  79. package/src/web/public/assets/task-utils-_JAWRAz6.js +0 -12
  80. package/src/web/public/assets/tool-bar-BAmT-BI-.js +0 -1
@@ -1,7 +1,8 @@
1
1
  // tasktool/attach-resource.js —— 附件的「资源视图模型」:关系表行 → 展示/取用信息。
2
2
  //
3
- // 资源类型只有四种(用户口径):file(含图片)/ url / task / ref。
3
+ // 资源类型只有五种(用户口径):file(含图片)/ url / task / ref / mdfile。
4
4
  // 旧数据里 kind='image' 或没有 kind 的一律按 file 处理(向后兼容)。
5
+ // mdfile = 本地 .md 文件的路径指针(字节在用户磁盘原地,storage='external')。
5
6
  //
6
7
  // 视图模型只依赖 core 与 shared(纯函数 + 关系表查询),不碰同步与云端:
7
8
  // file 型资源的可达性(本机副本绝对路径 vs fileId + 同步命令)由 fileStateOf 给出,
@@ -11,7 +12,7 @@ import { isAbsolute } from 'node:path';
11
12
  import { isImageName } from '../../core/fileapi.js';
12
13
  import { stripFrontmatter } from '../../shared/frontmatter.js';
13
14
 
14
- const KIND_LABEL: Record<string, string> = { file: '附件', url: '链接', task: '任务', ref: '文档' };
15
+ const KIND_LABEL: Record<string, string> = { file: '附件', url: '链接', task: '任务', ref: '文档', mdfile: 'md' };
15
16
  const IMAGE_LABEL = '图片';
16
17
  export const ORIGIN_LABEL = { inline: '正文内嵌', area: '附件区' };
17
18
  export const STATUS_LABEL: Record<string, string> = { pending: '待领取', claimed: '进行中', done: '已交付', cancelled: '已作废' };
@@ -30,10 +31,10 @@ function metaOf(row: any): Record<string, any> {
30
31
  }
31
32
  }
32
33
 
33
- /** 资源类型归一:image / 空 / 其它未知值 → file;url/task/ref 原样。 */
34
+ /** 资源类型归一:image / 空 / 其它未知值 → file;url/task/ref/mdfile 原样。 */
34
35
  function baseKind(row: any): string {
35
36
  const k = String((row && row.kind) || '');
36
- return k === 'url' || k === 'task' || k === 'ref' ? k : 'file';
37
+ return k === 'url' || k === 'task' || k === 'ref' || k === 'mdfile' ? k : 'file';
37
38
  }
38
39
 
39
40
  export function kindLabelOf(kind: unknown, isImage: unknown): string {
@@ -207,7 +208,9 @@ export function resourceOf(row: any, lookups: ResourceLookups = {}): any {
207
208
  // 兼容旧字段名(旧模板/旧 CLI 输出仍在读 area/areaLabel)
208
209
  area: origin,
209
210
  areaLabel: ORIGIN_LABEL[origin],
210
- storage: kind === 'file' ? String(row.storage || '') : kind === 'url' ? 'url' : 'internal',
211
+ storage: kind === 'file' ? String(row.storage || '')
212
+ : kind === 'url' ? 'url'
213
+ : kind === 'mdfile' ? 'external' : 'internal',
211
214
  synced: kind !== 'file',
212
215
  localPath: '',
213
216
  targetKind: String(row.targetKind || ''),
@@ -283,6 +286,35 @@ export function resourceOf(row: any, lookups: ResourceLookups = {}): any {
283
286
  };
284
287
  }
285
288
 
289
+ if (kind === 'mdfile') {
290
+ // 外部 md 文件指针:字节在用户磁盘原地(storage='external'),库里只有 abs_path + hash。
291
+ // 渲染分支只看 kind,不看 MIME / 扩展名。
292
+ const absPath = String(row.absPath || row.abs_path || meta.absPath || '');
293
+ const anchorDir = String(row.anchorDir || row.anchor_dir || meta.anchorDir || '');
294
+ const exists = !!absPath && existsSync(absPath);
295
+ const missing = !exists || (row.missingAt !== null && row.missingAt !== undefined);
296
+ const title = String(row.name || (absPath ? absPath.split(/[\\/]/).pop() : '') || base.id);
297
+ const readCmd = `nx-kv docs mdfile ${base.id}`;
298
+ const locator = `${title}${absPath ? `(${absPath})` : ''}`;
299
+ return {
300
+ ...base,
301
+ absPath,
302
+ anchorDir,
303
+ exists,
304
+ missing,
305
+ fileId: base.id,
306
+ title,
307
+ readCmd,
308
+ target: absPath || locator,
309
+ needsSync: false,
310
+ cmd: readCmd,
311
+ locator,
312
+ usage: missing
313
+ ? `外部 md 文件当前不可读(${absPath || '路径为空'}):用 ${readCmd} 查看状态;文件恢复后自动可读(不软删、不删行)`
314
+ : `这是外部 md 文件的路径指针(源文件不在库里):用 ${readCmd} 读取磁盘当前内容(读时核对指纹)`,
315
+ };
316
+ }
317
+
286
318
  // ref:文档库里的 md(locator 是 docs 树相对路径,或外部 md 的绝对路径)
287
319
  // 标题口径(#168):**文档标题**(正文首行的 # 标题)优先 —— 服务端在标注层
288
320
  // (tasktool/attach.js 的 annotateRefTitles)读盘补上并覆盖 title/name;
@@ -21,12 +21,14 @@ import { hostOfUrl, kindLabelOf, ORIGIN_LABEL, sizeTextOf, STATUS_LABEL } from '
21
21
  * address, storedAddress, addressDrift, resolved, purged, deleted, showCmd }
22
22
  * ref → { refId, title, relPath, readCmd, content, truncated }
23
23
  * content 只在「文档资料」绑定(role='doc',交付读全文)且真的读到时非空。
24
+ * mdfile → { absPath, anchorDir, content, truncated, stale, missing, readCmd }
25
+ * content 是读时从磁盘现取的正文(截断 2 万字);missing 时为空、stale 表示指纹漂移。
24
26
  * 通用 note = 边上的说明(desc,#162):attach --note 的落点,清单行透出。
25
27
  * 旧模板兼容:平铺别名 localPath / fileId / urlText / href / taskId / title /
26
28
  * seq / showCmd / refId / relPath / readCmd / target / area / areaLabel。
27
29
  */
28
30
  function ctxItemOf(a: any): any {
29
- const kind = ['url', 'task', 'ref'].includes(a.kind) ? a.kind : 'file';
31
+ const kind = ['url', 'task', 'ref', 'mdfile'].includes(a.kind) ? a.kind : 'file';
30
32
  const isImage = kind === 'file' && (a.isImage === undefined ? isImageName(a.name, a.mime) : !!a.isImage);
31
33
  const role = String(a.role || '');
32
34
  const origin =
@@ -131,6 +133,36 @@ function ctxItemOf(a: any): any {
131
133
  };
132
134
  }
133
135
 
136
+ if (kind === 'mdfile') {
137
+ const absPath = String(a.absPath || a.localPath || '');
138
+ const anchorDir = String(a.anchorDir || '');
139
+ const content = String(a.mdContent || '');
140
+ const truncated = !!a.mdTruncated;
141
+ const stale = !!a.mdStale;
142
+ const missing = a.mdMissing === undefined ? !absPath : !!a.mdMissing;
143
+ const readCmd = String(a.readCmd || `nx-kv docs mdfile ${item.id}`);
144
+ const mdfile = { absPath, anchorDir, content, truncated, stale, missing, readCmd };
145
+ const usage = String(a.usage || (missing
146
+ ? `外部 md 文件当前不可读(${absPath || '路径为空'}):用 ${readCmd} 查看状态`
147
+ : `这是外部 md 文件(源文件不在库里):用 ${readCmd} 读取磁盘当前内容${stale ? ';内容已变化,与登记指纹不一致' : ''}`));
148
+ return {
149
+ ...item,
150
+ absPath,
151
+ anchorDir,
152
+ path: absPath,
153
+ mdPath: absPath,
154
+ content,
155
+ truncated,
156
+ stale,
157
+ missing,
158
+ mdfile,
159
+ usage,
160
+ cmd: String(a.cmd !== undefined ? a.cmd : readCmd),
161
+ locator: String(a.locator || absPath || item.name),
162
+ needsSync: false,
163
+ };
164
+ }
165
+
134
166
  const refId = String(a.refId || a.targetKey || '');
135
167
  const relPath = String(a.relPath || a.locator || '');
136
168
  // docTitle:文档资料绑定读到全文时提取的首行 # 标题(比文件名更说明内容,#162)
@@ -143,13 +175,19 @@ function ctxItemOf(a: any): any {
143
175
  const ref = { refId, title, relPath, readCmd, content, truncated };
144
176
  // 文档资料绑定(role='doc',#162):读到了全文 → usage 指向「文档原文」段;
145
177
  // 没读到(fail-open)→ 退回普通取用命令,不假装内容存在。
178
+ // 外部 md 未登记附件时必须说清楚「为什么没有正文」并给登记命令,
179
+ // 否则用户会以为文档本身是空的(2026-11 收口口径)。
146
180
  let usage = String(a.usage || '');
147
181
  if (a.role === 'doc') {
148
182
  usage = content
149
183
  ? `这是文档资料绑定(进原文):全文已附在本清单末尾的「文档原文」段${truncated ? `,内容有截断——完整版用 ${readCmd} 读取` : ''}`
150
- : readCmd
151
- ? `这是文档资料绑定(进原文),但本次未能读到全文:用 ${readCmd} 读取`
152
- : `这是文档资料绑定(进原文),但本次未能读到全文(refId ${refId}):先用 nx-kv docs list 定位路径,再 docs get 读取`;
184
+ : a.docMissing
185
+ ? `这是文档资料绑定(进原文),但无法内联:${String(a.docMissingReason || '正文缺失')}` +
186
+ `${a.docRegisterCmd ? `。先登记为附件:${a.docRegisterCmd}` : ''}` +
187
+ `${readCmd ? `;登记后用 ${readCmd} 读取` : ''}`
188
+ : readCmd
189
+ ? `这是文档资料绑定(进原文),但本次未能读到全文:用 ${readCmd} 读取`
190
+ : `这是文档资料绑定(进原文),但本次未能读到全文(refId ${refId}):先用 nx-kv docs list 定位路径,再 docs get 读取`;
153
191
  } else {
154
192
  usage = usage || (readCmd
155
193
  ? `这是文档库里的 md 文件:用 ${readCmd} 读取`
@@ -236,6 +274,9 @@ export function attachmentInstruction(attachments: unknown, sync: unknown): stri
236
274
  if (a.kind === 'ref' && a.ref && a.ref.content) {
237
275
  lines.push(`〔文档原文 · ${a.ref.title}〕(${a.ref.relPath}):`, '', a.ref.content, '');
238
276
  }
277
+ if (a.kind === 'mdfile' && a.mdfile && a.mdfile.content) {
278
+ lines.push(`〔外部 md · ${a.name}〕(${a.mdfile.absPath}${a.mdfile.truncated ? ',已截断' : ''}${a.mdfile.stale ? ',内容有变化' : ''}):`, '', a.mdfile.content, '');
279
+ }
239
280
  }
240
281
  return lines.join('\n');
241
282
  }
@@ -38,6 +38,8 @@ import {
38
38
  ensureUrlAttachment,
39
39
  linkAttachment,
40
40
  listTaskAttachmentsBySeq,
41
+ readMdfile,
42
+ registerMdfile,
41
43
  resolveRefId,
42
44
  unlinkAttachment,
43
45
  updateAttachmentNote,
@@ -103,6 +105,34 @@ async function annotateRefTitles(attachments: any[]): Promise<any[]> {
103
105
  return attachments;
104
106
  }
105
107
 
108
+ /**
109
+ * mdfile 行的交付注入:读磁盘原文件(读时校验指纹),把正文挂到
110
+ * `mdContent/mdTruncated/mdStale/mdMissing`,模板侧按 mdfile 分支渲染。
111
+ * 读失败(文件没了)只标 missing,不拖垮交付(fail-open)。
112
+ */
113
+ const MDFILE_INLINE_MAX = 20000;
114
+
115
+ async function annotateMdfileContent(attachments: any[]): Promise<any[]> {
116
+ const rows = attachments.filter((a) => a.kind === 'mdfile');
117
+ if (!rows.length) return attachments;
118
+ const db = getDb();
119
+ for (const a of rows) {
120
+ try {
121
+ const r = readMdfile(db, a.id);
122
+ if (!r) continue;
123
+ a.absPath = r.absPath || a.absPath || '';
124
+ a.mdMissing = r.missing;
125
+ a.mdStale = r.stale;
126
+ a.mdContent = r.body.length > MDFILE_INLINE_MAX ? r.body.slice(0, MDFILE_INLINE_MAX) : r.body;
127
+ a.mdTruncated = r.body.length > MDFILE_INLINE_MAX;
128
+ } catch {
129
+ a.mdMissing = true;
130
+ a.mdContent = '';
131
+ }
132
+ }
133
+ return attachments;
134
+ }
135
+
106
136
  export interface AnnotateTaskDeliveryOptions {
107
137
  /** 是否允许为未命中的附件跑一次云端同步(预览传 false:只读盘、不发网) */
108
138
  sync?: boolean;
@@ -150,8 +180,9 @@ export async function annotateTaskDelivery(
150
180
 
151
181
  const mirror = await cloudMirrorIndex(gid, cfg.attachmentsDir);
152
182
  const attachments = annotateFileRows(rows, targetLookupsOf(getDb(), rows), store, mirror);
183
+ await annotateMdfileContent(attachments);
153
184
  await annotateRefTitles(attachments);
154
- if (inlineDocs) await inlineDocContent(attachments);
185
+ if (inlineDocs) await inlineDocContent(attachments, { id: (task as any).id, key: (task as any).key || (task as any).topicKey });
155
186
  return { task: { ...task, attachments }, sync };
156
187
  }
157
188
 
@@ -167,6 +198,8 @@ export interface AttachToTaskOptions {
167
198
  url?: unknown;
168
199
  task?: unknown;
169
200
  ref?: unknown;
201
+ /** 本地 md 文件(kind=mdfile:只登记路径指针,不复制正文) */
202
+ mdfile?: unknown;
170
203
  note?: unknown;
171
204
  noEmbed?: unknown;
172
205
  inline?: unknown;
@@ -190,9 +223,10 @@ export interface AttachToTaskOptions {
190
223
  * --url <链接> 外部 URL(kind=url)
191
224
  * --task <seq> 同主题下的另一条任务(kind=task,nxkv://task/<id>)
192
225
  * --ref <路径|id> 文档库里的 ref(kind=ref,nxkv://ref/<refId>)
226
+ * --mdfile <路径> 本地 md 文件(kind=mdfile,nxkv://mdfile/<attId>;字节不入库)
193
227
  */
194
228
  export async function attachToTask({
195
- id, cwd, key, path, fileId, name, kind, url, task, ref, note, noEmbed, inline,
229
+ id, cwd, key, path, fileId, name, kind, url, task, ref, mdfile, note, noEmbed, inline,
196
230
  }: AttachToTaskOptions = {}): Promise<Record<string, any>> {
197
231
  const cur = await service.getTask({ id, cwd, key }); // 存在性与参数校验都在队列本体
198
232
  const topicKey = cur.key || key || '';
@@ -294,11 +328,21 @@ export async function attachToTask({
294
328
  ) as string; // 同上:登记失败落空串,由下方 !attachmentId 统一报错
295
329
  resolvedKind = 'ref';
296
330
  markdown = `[${displayName || String(ref).split('/').pop()}](nxkv://ref/${refId})`;
331
+ } else if (mdfile) {
332
+ // 外部 md 文件:登记指针(kind=mdfile / storage=external),正文留在磁盘原地
333
+ const rec = tx(
334
+ (conn) => registerMdfile(conn, { path: mdfile, name: displayName }),
335
+ { db, mode: 'IMMEDIATE' }
336
+ );
337
+ attachmentId = rec.id;
338
+ displayName = displayName || rec.name;
339
+ resolvedKind = 'mdfile';
340
+ markdown = `[${displayName}](nxkv://mdfile/${rec.id})`;
297
341
  }
298
342
 
299
343
  if (!attachmentId) {
300
344
  throw badInput(
301
- '需要 --path <本机文件>、--fileId <已有附件>、--url <链接>、--task <编号> 或 --ref <文档> 之一'
345
+ '需要 --path <本机文件>、--fileId <已有附件>、--url <链接>、--task <编号>、--ref <文档> 或 --mdfile <本地 md> 之一'
302
346
  );
303
347
  }
304
348
  const wantInline = !!inline;
@@ -4,13 +4,15 @@
4
4
  // 而不是只给一条 `docs get` 命令——agent 少跑一轮 nx-kv(任务原文口径:
5
5
  // 「减少反复访问 nxkv 的开销」)。
6
6
  //
7
- // 读侧纪律:
8
- // - **只读**:自有 rel 直接读 docs 树,缺失不播种(交付/预览都不许有写副作用);
9
- // - 外部绝对路径必须落在绑定闭包内(与 docs get 的读侧守卫同口径,
10
- // 否则交付链就成了任意文件读入口);
7
+ // 读侧纪律(2026-11 DOCS_DIR 收口后):
8
+ // - **只读、只认 DB**:自有 rel 走 docs store 的 DB 读取,缺失不播种;
9
+ // - 外部绝对路径**不再直读盘**:必须先在 attachments 里登记成 mdfile,
10
+ // 经 `readMdfile`(唯一文件读入口)取正文;没登记 → 显式提示 + 给登记命令;
11
11
  // - fail-open:读不到 → 内容留空,清单与取用命令照给,绝不拖垮领取。
12
12
  import { isAbsolute } from 'node:path';
13
13
  import { MAX_INLINE_DOC_CHARS } from './attach-resource.js';
14
+ import { findMdfileByPath, noBodyReason, readMdfile, relKindOf } from '../../core/attachmentdb.js';
15
+ import { getDb } from '../../core/db/index.js';
14
16
 
15
17
  let docsStoreMod: any = null;
16
18
  async function docsStore(): Promise<any> {
@@ -18,59 +20,82 @@ async function docsStore(): Promise<any> {
18
20
  return docsStoreMod;
19
21
  }
20
22
 
21
- let docsBridgeMod: any = null;
22
- async function docsBridge(): Promise<any> {
23
- if (!docsBridgeMod) docsBridgeMod = await import('../docs/repos-bridge.js');
24
- return docsBridgeMod;
23
+ /** 逻辑 rel(external/<sha1>)→ 原始绝对路径;不是 ref 行就返回 ''。 */
24
+ function locatorOfRel(db: any, rel: string): string {
25
+ const row = db.get('SELECT locator FROM refs WHERE rel = :rel AND deleted_at IS NULL', { rel });
26
+ return String(row?.locator || '');
27
+ }
28
+
29
+ /** 外部 md 正文:只认已登记的 mdfile(唯一文件读入口)。 */
30
+ function readExternalViaMdfile(db: any, locator: string): string | null {
31
+ const rec = findMdfileByPath(db, locator);
32
+ if (!rec) return null;
33
+ const read = readMdfile(db, rec.id);
34
+ if (!read || read.missing) return null;
35
+ return read.body;
25
36
  }
26
37
 
27
38
  /**
28
- * 读一篇 ref 资源的正文(进原文用)。locator = refs 表的 locator:
29
- * 自有树相对路径 / 外部绝对路径。目录绑定、缺失、闭包外 → null(fail-open)。
39
+ * 读一篇 ref 资源的正文(进原文用)。locator = refs 表的 locator / rel:
40
+ * 自有树相对路径 / 外部绝对路径 / external/<sha1> 逻辑名。
41
+ * 目录绑定、缺失、未登记 mdfile → null(fail-open)。
30
42
  */
31
43
  export async function readRefDocBody(locator: unknown): Promise<string | null> {
32
44
  const raw = String(locator || '').trim();
33
45
  if (!raw) return null;
34
- const store = await docsStore();
46
+ const db = getDb();
35
47
  if (!isAbsolute(raw)) {
36
48
  try {
37
- return await store.readOwnDoc(raw);
49
+ return await (await docsStore()).readOwnDoc(raw);
38
50
  } catch {
39
- return null; // 缺失不播种:交付只读
51
+ // 不是自有文档:可能是不在库里的历史壳行 / 外部逻辑名,继续按外部处理
40
52
  }
41
53
  }
42
- const { loadStore } = await docsBridge().then((m: any) => m.reposBridge());
43
- const s = await loadStore();
44
- const closure = await store.externalClosure(s);
45
- const abs = store.resolveExternal(raw, closure);
46
- if (!abs) return null; // 闭包外一律不给(任意文件读闸门)
47
- const fsp = await import('node:fs/promises');
48
- const st = await fsp.stat(abs).catch(() => null);
49
- if (!st || !st.isFile()) return null;
50
- try {
51
- return await fsp.readFile(abs, 'utf8');
52
- } catch {
53
- return null;
54
+ const abs = isAbsolute(raw) ? raw : locatorOfRel(db, raw);
55
+ if (!isAbsolute(abs)) return null;
56
+ // 外部 md 必须先登记成 mdfile 附件;未登记不允许直读盘(DOCS_DIR 收口)
57
+ return readExternalViaMdfile(db, abs);
58
+ }
59
+
60
+ /** 交付里没内联时的人读原因。 */
61
+ function missingReasonOf(raw: string): string {
62
+ if (!isAbsolute(raw) && !raw.startsWith('external/')) {
63
+ return noBodyReason(relKindOf(raw, false));
54
64
  }
65
+ return '该文档未登记为附件,无法内联';
55
66
  }
56
67
 
57
68
  /**
58
69
  * 给附件视图模型补「文档原文」:role='doc' 且 kind='ref' 的项读全文(截断 2 万字)。
59
70
  * 就地写 docContent / docTruncated,并把文档首行 # 标题带到 docTitle——
60
71
  * 绑定条目常只有文件名,agent 看「〔文档原文 · <真标题>〕」比看文件名更知道里面是什么。
61
- * 读不到就留空——调用方照常渲染路径与命令。
72
+ * 读不到就留空,并显式标 `docMissing` + 原因;外部 md 另带**可直接执行**的登记命令。
62
73
  */
63
- export async function inlineDocContent(items: any): Promise<void> {
74
+ export async function inlineDocContent(items: any, task?: { id?: unknown; key?: unknown }): Promise<void> {
75
+ const db = getDb();
76
+ const seq = Number(task?.id) || 0;
77
+ const key = String(task?.key || '');
64
78
  for (const a of Array.isArray(items) ? items : []) {
65
79
  if (a.kind !== 'ref' || a.role !== 'doc' || a.docContent) continue;
80
+ const raw = String(a.relPath || a.targetKey || a.locator || '');
66
81
  let body: string | null = null;
67
82
  try {
68
- body = await readRefDocBody(a.relPath || a.targetKey || '');
83
+ body = await readRefDocBody(raw);
69
84
  } catch {
70
85
  body = null;
71
86
  }
72
87
  const text = String(body ?? '');
73
- if (!text.trim()) continue;
88
+ if (!text.trim()) {
89
+ // v6:没有正文的条目在交付清单里显式标 missing(不输出空串冒充正文)
90
+ a.docMissing = true;
91
+ a.docMissingReason = missingReasonOf(raw);
92
+ const abs = isAbsolute(raw) ? raw : locatorOfRel(db, raw);
93
+ if (abs) {
94
+ const addr = [seq ? `--id ${seq}` : '', key ? `--key ${key}` : ''].filter(Boolean).join(' ');
95
+ a.docRegisterCmd = `nx-kv localtask attach ${addr ? addr + ' ' : ''}--mdfile "${abs}"`;
96
+ }
97
+ continue;
98
+ }
74
99
  const m = /^#\s+(.+)$/m.exec(text);
75
100
  const title = m?.[1] ?? '';
76
101
  if (title.trim()) a.docTitle = title.trim();
@@ -123,7 +123,7 @@ export const DEFAULT_ATTACH_TEMPLATE = [
123
123
  '',
124
124
  '附件清单:',
125
125
  '{{#each attach.list}}',
126
- ' - [{{originLabel}}] {{kindLabel}} {{name}}{{#if sizeText}}({{sizeText}}){{/if}}:{{#if file}}{{#if file.exists}}{{file.localPath}}{{else}}未同步到本地(fileId {{file.fileId}}){{/if}}{{/if}}{{#if url}}{{url.href}}{{/if}}{{#if task}}{{#if task.resolved}}#{{task.seq}} {{task.title}} · 地址 {{task.address}}({{task.statusLabel}}){{else}}地址 {{task.address}}({{task.statusLabel}}){{/if}}{{/if}}{{#if ref}}{{ref.title}}{{#if ref.relPath}}({{ref.relPath}}){{/if}}{{/if}}{{#if note}} # {{note}}{{/if}}',
126
+ ' - [{{originLabel}}] {{kindLabel}} {{name}}{{#if sizeText}}({{sizeText}}){{/if}}:{{#if file}}{{#if file.exists}}{{file.localPath}}{{else}}未同步到本地(fileId {{file.fileId}}){{/if}}{{/if}}{{#if url}}{{url.href}}{{/if}}{{#if task}}{{#if task.resolved}}#{{task.seq}} {{task.title}} · 地址 {{task.address}}({{task.statusLabel}}){{else}}地址 {{task.address}}({{task.statusLabel}}){{/if}}{{/if}}{{#if ref}}{{ref.title}}{{#if ref.relPath}}({{ref.relPath}}){{/if}}{{/if}}{{#if mdfile}}{{mdfile.absPath}}{{#if mdfile.missing}}(源文件已不在){{/if}}{{/if}}{{#if note}} # {{note}}{{/if}}',
127
127
  '{{/each}}',
128
128
  '',
129
129
  '取用方式:',
@@ -133,6 +133,11 @@ export const DEFAULT_ATTACH_TEMPLATE = [
133
133
  '{{#if attach.syncSummary}}',
134
134
  '同步情况:{{attach.syncSummary.text}}',
135
135
  '{{/if}}',
136
+ '{{#each attach.list}}{{#if mdfile}}{{#if mdfile.content}}〔外部 md · {{name}}〕({{mdfile.absPath}}{{#if mdfile.truncated}},已截断{{/if}}{{#if mdfile.stale}},内容有变化{{/if}}):',
137
+ '',
138
+ '{{mdfile.content}}',
139
+ '',
140
+ '{{/if}}{{/if}}{{/each}}',
136
141
  '{{#each attach.list}}{{#if ref}}{{#if ref.content}}〔文档原文 · {{ref.title}}〕({{ref.relPath}}):',
137
142
  '',
138
143
  '{{ref.content}}',
@@ -926,7 +926,7 @@
926
926
  "action": {
927
927
  "id": "doc.attach",
928
928
  "module": "docs",
929
- "summary": "给文档挂资源:--path / --fileId / --url / --task / --doc 之一;默认追加进正文,--no-embed 只挂附件区(不写正文)",
929
+ "summary": "给文档挂资源:--path / --fileId / --url / --task / --doc / --mdfile 之一;默认追加进正文,--no-embed 只挂附件区(不写正文)",
930
930
  "usage": "docs attach",
931
931
  "http": "POST /api/docs/attach"
932
932
  },
@@ -977,6 +977,21 @@
977
977
  },
978
978
  "children": []
979
979
  },
980
+ {
981
+ "name": "link-file",
982
+ "path": [
983
+ "docs",
984
+ "link-file"
985
+ ],
986
+ "action": {
987
+ "id": "doc.link-file",
988
+ "module": "docs",
989
+ "summary": "把本地 md 文件登记为 mdfile 附件并挂到文档附件区:只存路径指针,不复制正文,不改文档正文",
990
+ "usage": "docs link-file",
991
+ "http": "POST /api/docs/link-file"
992
+ },
993
+ "children": []
994
+ },
980
995
  {
981
996
  "name": "list",
982
997
  "path": [
@@ -992,6 +1007,36 @@
992
1007
  },
993
1008
  "children": []
994
1009
  },
1010
+ {
1011
+ "name": "mdfile",
1012
+ "path": [
1013
+ "docs",
1014
+ "mdfile"
1015
+ ],
1016
+ "action": {
1017
+ "id": "doc.mdfile",
1018
+ "module": "docs",
1019
+ "summary": "读本地 md 文件的正文(只读原文件,核对指纹;文件缺失时返回空正文并标 missing)",
1020
+ "usage": "docs mdfile",
1021
+ "http": "GET /api/docs/mdfile"
1022
+ },
1023
+ "children": []
1024
+ },
1025
+ {
1026
+ "name": "mdfiles",
1027
+ "path": [
1028
+ "docs",
1029
+ "mdfiles"
1030
+ ],
1031
+ "action": {
1032
+ "id": "doc.mdfiles",
1033
+ "module": "docs",
1034
+ "summary": "列出已登记的本地 md 文件(mdfile 附件;--missing 只看失效行)",
1035
+ "usage": "docs mdfiles",
1036
+ "http": "GET /api/docs/mdfiles"
1037
+ },
1038
+ "children": []
1039
+ },
995
1040
  {
996
1041
  "name": "remove",
997
1042
  "path": [
@@ -1145,7 +1190,7 @@
1145
1190
  "action": {
1146
1191
  "id": "localtask.attach",
1147
1192
  "module": "localtask",
1148
- "summary": "给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文)",
1193
+ "summary": "给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档)/ --mdfile(本地 md 指针);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文)",
1149
1194
  "usage": "localtask attach",
1150
1195
  "http": "POST /api/localtasks/attach"
1151
1196
  },
@@ -25,7 +25,10 @@ import type {
25
25
  DocAttachmentsAction,
26
26
  DocDetachAction,
27
27
  DocGetAction,
28
+ DocLinkFileAction,
28
29
  DocListAction,
30
+ DocMdfileAction,
31
+ DocMdfilesAction,
29
32
  DocRemoveAction,
30
33
  DocUpdateAction,
31
34
  DocsBindAction,
@@ -288,7 +291,7 @@ export interface ApiClient {
288
291
  docAdd2(input: z.input<InstanceType<typeof DocAddAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocAddAction>['run']>>>;
289
292
  /** 改一条附件绑定的说明(desc):--attachment <资源 id> --note <说明>(只动说明,角色/位置不变) */
290
293
  attachNote(input: z.input<InstanceType<typeof DocAttachNoteAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocAttachNoteAction>['run']>>>;
291
- /** 给文档挂资源:--path / --fileId / --url / --task / --doc 之一;默认追加进正文,--no-embed 只挂附件区(不写正文) */
294
+ /** 给文档挂资源:--path / --fileId / --url / --task / --doc / --mdfile 之一;默认追加进正文,--no-embed 只挂附件区(不写正文) */
292
295
  attach(input: z.input<InstanceType<typeof DocAttachAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocAttachAction>['run']>>>;
293
296
  /** 这篇文档用了哪些资源(ref_attach:图片/文件/URL/内部 task、ref 引用) */
294
297
  attachments(input: z.input<InstanceType<typeof DocAttachmentsAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocAttachmentsAction>['run']>>>;
@@ -296,8 +299,14 @@ export interface ApiClient {
296
299
  detach(input: z.input<InstanceType<typeof DocDetachAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocDetachAction>['run']>>>;
297
300
  /** 读文档全文:rel:<路径>(或裸相对路径)= 自有;path:<绝对路径> = 外部(须在绑定闭包内);约定路径缺失时惰性播种 */
298
301
  docGet(input: z.input<InstanceType<typeof DocGetAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocGetAction>['run']>>>;
302
+ /** 把本地 md 文件登记为 mdfile 附件并挂到文档附件区:只存路径指针,不复制正文,不改文档正文 */
303
+ linkFile(input: z.input<InstanceType<typeof DocLinkFileAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocLinkFileAction>['run']>>>;
299
304
  /** 文档树索引(自有 + 可选外部;零副作用,双链解析的数据源) */
300
305
  docList2(input?: z.input<InstanceType<typeof DocListAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocListAction>['run']>>>;
306
+ /** 读本地 md 文件的正文(只读原文件,核对指纹;文件缺失时返回空正文并标 missing) */
307
+ mdfile(input: z.input<InstanceType<typeof DocMdfileAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocMdfileAction>['run']>>>;
308
+ /** 列出已登记的本地 md 文件(mdfile 附件;--missing 只看失效行) */
309
+ mdfiles(input?: z.input<InstanceType<typeof DocMdfilesAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocMdfilesAction>['run']>>>;
301
310
  /** 删除自有文档(外部绑定不可删) */
302
311
  docRemove2(input: z.input<InstanceType<typeof DocRemoveAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocRemoveAction>['run']>>>;
303
312
  /** 写文档正文(面板保存走这里;自有走 own 树、外部走绑定闭包内原文件;写盘后摘要回写 desc / 组内 note) */
@@ -316,7 +325,7 @@ export interface ApiClient {
316
325
  localtaskAdd(input: z.input<InstanceType<typeof LocaltaskAddAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof LocaltaskAddAction>['run']>>>;
317
326
  /** 改一条附件绑定的说明(desc):--attachment <资源 id> --note <说明>(只动说明,角色/位置不变) */
318
327
  localtaskAttachNote(input: z.input<InstanceType<typeof LocaltaskAttachNoteAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof LocaltaskAttachNoteAction>['run']>>>;
319
- /** 给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文) */
328
+ /** 给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档)/ --mdfile(本地 md 指针);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文) */
320
329
  localtaskAttach(input: z.input<InstanceType<typeof LocaltaskAttachAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof LocaltaskAttachAction>['run']>>>;
321
330
  /** 列出某条任务引用的附件(正文里的 ![名](fileId) 嵌入),以及本地是否已有(给 agent 直接读本地文件) */
322
331
  localtaskAttachments(input: z.input<InstanceType<typeof LocaltaskAttachmentsAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof LocaltaskAttachmentsAction>['run']>>>;
@@ -859,7 +868,7 @@ export function createApiClient(transport: Transport): ApiClient {
859
868
  async attach(input: z.input<InstanceType<typeof DocAttachAction>['_input']>) {
860
869
  const inp = input ?? ({} as z.input<InstanceType<typeof DocAttachAction>['_input']>);
861
870
  const path = `/api/docs/attach`;
862
- const body = { "ref": inp["ref"], "path": inp["path"], "fileId": inp["fileId"], "url": inp["url"], "task": inp["task"], "doc": inp["doc"], "name": inp["name"], "note": inp["note"], "noEmbed": inp["noEmbed"], "no-embed": inp["no-embed"] };
871
+ const body = { "ref": inp["ref"], "path": inp["path"], "fileId": inp["fileId"], "url": inp["url"], "task": inp["task"], "doc": inp["doc"], "mdfile": inp["mdfile"], "name": inp["name"], "note": inp["note"], "noEmbed": inp["noEmbed"], "no-embed": inp["no-embed"] };
863
872
  return (await transport.request("POST", path, body)) as Awaited<ReturnType<InstanceType<typeof DocAttachAction>['run']>>;
864
873
  },
865
874
  // action: doc.attachments
@@ -889,6 +898,13 @@ export function createApiClient(transport: Transport): ApiClient {
889
898
  if (query) path += path.includes('?') ? '&' + query : '?' + query;
890
899
  return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof DocGetAction>['run']>>;
891
900
  },
901
+ // action: doc.link-file
902
+ async linkFile(input: z.input<InstanceType<typeof DocLinkFileAction>['_input']>) {
903
+ const inp = input ?? ({} as z.input<InstanceType<typeof DocLinkFileAction>['_input']>);
904
+ const path = `/api/docs/link-file`;
905
+ const body = { "ref": inp["ref"], "path": inp["path"], "name": inp["name"], "note": inp["note"] };
906
+ return (await transport.request("POST", path, body)) as Awaited<ReturnType<InstanceType<typeof DocLinkFileAction>['run']>>;
907
+ },
892
908
  // action: doc.list
893
909
  async docList2(input?: z.input<InstanceType<typeof DocListAction>['_input']>) {
894
910
  const inp = input ?? ({} as z.input<InstanceType<typeof DocListAction>['_input']>);
@@ -899,6 +915,26 @@ export function createApiClient(transport: Transport): ApiClient {
899
915
  if (query) path += path.includes('?') ? '&' + query : '?' + query;
900
916
  return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof DocListAction>['run']>>;
901
917
  },
918
+ // action: doc.mdfile
919
+ async mdfile(input: z.input<InstanceType<typeof DocMdfileAction>['_input']>) {
920
+ const inp = input ?? ({} as z.input<InstanceType<typeof DocMdfileAction>['_input']>);
921
+ let path = `/api/docs/mdfile`;
922
+ const q = new URLSearchParams();
923
+ if (inp["attachment"] !== undefined) q.set("attachment", String(inp["attachment"]));
924
+ const query = q.toString();
925
+ if (query) path += path.includes('?') ? '&' + query : '?' + query;
926
+ return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof DocMdfileAction>['run']>>;
927
+ },
928
+ // action: doc.mdfiles
929
+ async mdfiles(input?: z.input<InstanceType<typeof DocMdfilesAction>['_input']>) {
930
+ const inp = input ?? ({} as z.input<InstanceType<typeof DocMdfilesAction>['_input']>);
931
+ let path = `/api/docs/mdfiles`;
932
+ const q = new URLSearchParams();
933
+ if (inp["missing"] !== undefined) q.set("missing", String(inp["missing"]));
934
+ const query = q.toString();
935
+ if (query) path += path.includes('?') ? '&' + query : '?' + query;
936
+ return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof DocMdfilesAction>['run']>>;
937
+ },
902
938
  // action: doc.remove
903
939
  async docRemove2(input: z.input<InstanceType<typeof DocRemoveAction>['_input']>) {
904
940
  const inp = input ?? ({} as z.input<InstanceType<typeof DocRemoveAction>['_input']>);
@@ -964,7 +1000,7 @@ export function createApiClient(transport: Transport): ApiClient {
964
1000
  async localtaskAttach(input: z.input<InstanceType<typeof LocaltaskAttachAction>['_input']>) {
965
1001
  const inp = input ?? ({} as z.input<InstanceType<typeof LocaltaskAttachAction>['_input']>);
966
1002
  const path = `/api/localtasks/attach`;
967
- const body = { "id": inp["id"], "cwd": inp["cwd"], "key": inp["key"], "path": inp["path"], "fileId": inp["fileId"], "url": inp["url"], "task": inp["task"], "ref": inp["ref"], "inline": inp["inline"], "name": inp["name"], "kind": inp["kind"], "note": inp["note"], "noEmbed": inp["noEmbed"], "no-embed": inp["no-embed"] };
1003
+ const body = { "id": inp["id"], "cwd": inp["cwd"], "key": inp["key"], "path": inp["path"], "fileId": inp["fileId"], "url": inp["url"], "task": inp["task"], "ref": inp["ref"], "mdfile": inp["mdfile"], "inline": inp["inline"], "name": inp["name"], "kind": inp["kind"], "note": inp["note"], "noEmbed": inp["noEmbed"], "no-embed": inp["no-embed"] };
968
1004
  return (await transport.request("POST", path, body)) as Awaited<ReturnType<InstanceType<typeof LocaltaskAttachAction>['run']>>;
969
1005
  },
970
1006
  // action: localtask.attachments