nx-kv 0.54.1 → 0.54.2

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 (31) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/assets/nx-kv/references/A05-/351/231/204/344/273/266.md +9 -0
  3. package/assets/nx-kv/references/B02-CLI/351/200/237/346/237/245.md +1 -1
  4. package/package.json +1 -1
  5. package/src/core/attachmentdb/folder.ts +97 -0
  6. package/src/core/attachmentdb/ids.ts +6 -1
  7. package/src/core/attachmentdb/resources.ts +2 -0
  8. package/src/core/attachmentdb.ts +6 -0
  9. package/src/core/db/migrations/index.ts +2 -0
  10. package/src/core/db/migrations/v10.sql +86 -0
  11. package/src/core/db/version.ts +3 -1
  12. package/src/modules/docs/actions/doc-attach.ts +2 -1
  13. package/src/modules/docs/attach.ts +14 -1
  14. package/src/modules/localtask/action-render.ts +2 -2
  15. package/src/modules/localtask/actions/localtask-attach.ts +4 -2
  16. package/src/modules/tasktool/attach-resource.ts +29 -3
  17. package/src/modules/tasktool/attach-template.ts +25 -1
  18. package/src/modules/tasktool/attach.ts +16 -2
  19. package/src/shared/prompt-blocks.ts +2 -2
  20. package/src/web/frontend/api/cli-tree.json +2 -2
  21. package/src/web/frontend/api/client.generated.ts +4 -4
  22. package/src/web/frontend/page/settings/prompt-template-params.ts +12 -2
  23. package/src/web/public/assets/{composer-panel-D2OattCj.js → composer-panel-BCtBThwX.js} +1 -1
  24. package/src/web/public/assets/{dir-BOhkvibf.js → dir-26TlooV0.js} +1 -1
  25. package/src/web/public/assets/{group-0T2ZesQD.js → group-DDPw8Oun.js} +1 -1
  26. package/src/web/public/assets/{index-B2y5VfCY.js → index-CHHQ1EtL.js} +2 -2
  27. package/src/web/public/assets/settings-JX0JIscd.js +8 -0
  28. package/src/web/public/assets/{task-skIHoMBy.js → task-DeRZSdrv.js} +1 -1
  29. package/src/web/public/assets/{templates-dDCoK97L.js → templates-CFCratP_.js} +1 -1
  30. package/src/web/public/index.html +1 -1
  31. package/src/web/public/assets/settings-BjaJ9Ch2.js +0 -8
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  本文件记录对外可见的变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
4
4
 
5
+ ## [0.54.2] - 2026-11-14 附件支持本地文件夹(#127)
6
+
7
+ ### Added
8
+
9
+ - **第六种附件类型 `folder`**:把本机文件夹路径当作附件登记。库里只存规范化绝对路径 +
10
+ 展示名(`storage=external`、`size=0`、`hash=''`),目录内容**不入库、不复制、不打包**;
11
+ 交付给 agent 的是路径 + 「先列目录看结构,再用 Read 读需要的文件」的取用说明。
12
+ - **CLI / HTTP**:`localtask attach --folder <目录>`、`docs attach --folder <目录>`;
13
+ 正文里写 `nxkv://folder/<attId>`,同一路径重复登记幂等(大小写不敏感唯一索引)。
14
+ - **提示词模板变量**(用户明确要求):`attach.list[]` 新增 `folder` 子对象
15
+ `{absPath, exists, missing, readCmd}`,内置附件模板清单行加 `{{#if folder}}` 分支,
16
+ 设置面板的模板变量表新增「文件夹型」分组;`kindLabel` 为「文件夹」。
17
+
18
+ ### Changed
19
+
20
+ - **schema v10**:SQLite 不能 ALTER CHECK,按 v5 的 12-step 模式重建 `attachments`
21
+ (`task_attach` / `ref_attach` 快照 → DROP 前清空 → 回填),5 个既有索引原样重建,
22
+ 新增 `ux_attachments_folder_path`。真实库已自动 9→10 升级(106 条附件全部保留)。
23
+ - 附件资源视图 / 模板 ctx / CLI render / skill A05·B02 同步支持 folder。
24
+
25
+ ### 验证
26
+
27
+ - 单测覆盖 v9→v10 数据不丢、CHECK 生效、目录登记幂等、正文 `nxkv://folder/…` 可解析、
28
+ 模板 ctx 有 `folder.*` 且把绝对路径交给 agent;实机 `localtask attach --folder` 通过。
29
+
5
30
  ## [0.54.1] - 2026-11-14 任务新增 plan 临时草稿态(#126)
6
31
 
7
32
  ### Added
@@ -29,6 +29,8 @@ nx-kv localtask attach --id <n> --url <https://…> # 外链(kind=url
29
29
  nx-kv localtask attach --id <n> --ref <refId> --inline # 引用库内文档,--inline 附全文(≤2 万字)
30
30
  nx-kv localtask attach --id <n> --task <m> # 引用同主题的另一条任务(nxkv://task/<id>)
31
31
  nx-kv localtask attach --id <n> --path F --noEmbed # 只登记,不改正文
32
+ nx-kv localtask attach --id <n> --folder <本机目录> # 文件夹附件(kind=folder,只存路径,不复制目录内容)
33
+ nx-kv docs attach --ref <refId> --folder <本机目录> # 文档侧同样支持
32
34
  nx-kv localtask detach --id <n> --attachment <id> # 摘掉一条(--purge 连文件一起删)
33
35
  nx-kv localtask attachments --id <n> --json # 引用了哪些附件(含本地绝对路径)
34
36
  ```
@@ -44,3 +46,10 @@ nx-kv localtask attachments --id <n> --json # 引用了哪些附件
44
46
  | 把 fileId 当 URL 拼地址 | 用 instruction 给的本地路径 Read |
45
47
  | 手工把 fileId 写进正文 | 用 `attach`,它会写正确的 markdown 片段 |
46
48
  | 附件缺失时凭上下文猜内容 | 明确告诉用户「附件没在本机仓」 |
49
+
50
+ ## 文件夹附件(kind=folder)
51
+
52
+ 目录**没有字节**:库里只登记规范化绝对路径 + 展示名(`storage=external`、`size=0`),
53
+ 不复制、不打包目录内容。交付模板给 agent 的是 `folder.absPath` / `folder.exists` /
54
+ `folder.missing` / `folder.readCmd`,取用说明是「先列目录看结构,再用 Read 读需要的文件」。
55
+ 正文里写 `nxkv://folder/<attId>`;同一路径重复登记幂等。
@@ -23,7 +23,7 @@
23
23
  | `localtask remove` | `--id N` `--purge` | 软删除;`--purge` 连附件一起删 |
24
24
  | `localtask remove-many` | `--ids 1,2,3` `--purge` | 批量删 |
25
25
  | `localtask task restore` | `--id N` | 恢复软删的任务 |
26
- | `localtask attach` | `--id N` + `--path F` \| `--fileId X` \| `--url U` \| `--task N` \| `--ref R` \| `--mdfile F`;`--note` `--inline` `--noEmbed` | 加附件/引用。`--noEmbed` 只登记不改正文 |
26
+ | `localtask attach` | `--id N` + `--path F` \| `--fileId X` \| `--url U` \| `--task N` \| `--ref R` \| `--mdfile F` \| `--folder D`;`--note` `--inline` `--noEmbed` | 加附件/引用。`--folder` 登记目录路径指针(kind=folder,不复制内容);`--noEmbed` 只登记不改正文 |
27
27
  | `localtask detach` | `--id N` `--attachment <id>` `--purge` | 摘掉一条附件(`--purge` 连文件) |
28
28
  | `localtask attachments` | `--id N` | 附件清单(含本地绝对路径) |
29
29
  | `localtask events` | `--timeout` `--limit` | 事件流(长轮询,面板用) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.54.1",
3
+ "version": "0.54.2",
4
4
  "description": "nx-kv — 本机任务队列(localtask)+ 文档库 + 仓库登记:serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,97 @@
1
+ // 本地文件夹附件(#127):只登记一个绝对路径指针,目录内容不入库。
2
+ //
3
+ // 与 mdfile 同为 `storage='external'`,区别在于:
4
+ // · mdfile 是单个 .md 文件,登记时读指纹、交付时附正文;
5
+ // · folder 是目录,没有字节(size=0 / hash='' / mime=''),交付只给路径,
6
+ // 由 agent 按需列目录 / 读里面的文件。
7
+ import { existsSync, statSync } from 'node:fs';
8
+ import { basename, resolve } from 'node:path';
9
+ import { createHash } from 'node:crypto';
10
+ import { badInput, conflict } from '../errors.js';
11
+
12
+ const sha1 = (s: string): string => createHash('sha1').update(s).digest('hex');
13
+
14
+ /** 规范化文件夹绝对路径:解析相对路径、去掉尾部斜杠、身份种子用 POSIX + 小写盘符。 */
15
+ export function normalizeFolderPath(input: unknown): string {
16
+ const raw = String(input ?? '').trim().replace(/["']+$/, '');
17
+ if (!raw) return '';
18
+ const abs = resolve(raw);
19
+ return abs.replace(/[\\/]+$/, '') || abs;
20
+ }
21
+
22
+ /** 稳定 id:`att_folder_<sha1(规范化路径).slice(0,16)>`;同一路径幂等。 */
23
+ export function folderAttachmentId(path: unknown): string {
24
+ let seed = normalizeFolderPath(path).replace(/\\/g, '/');
25
+ if (/^[A-Z]:/.test(seed)) seed = seed.charAt(0).toLowerCase() + seed.slice(1);
26
+ return 'att_folder_' + sha1(seed).slice(0, 16);
27
+ }
28
+
29
+ /** 登记(或刷新)一条文件夹附件;返回 { id, name, absPath }。 */
30
+ export function registerFolder(conn: any, { path, name, atMs = Date.now() }: {
31
+ path?: unknown; name?: unknown; atMs?: number;
32
+ } = {}): { id: string; name: string; absPath: string } {
33
+ const absPath = normalizeFolderPath(path);
34
+ if (!absPath) throw badInput('folder 需要文件夹路径');
35
+ if (!existsSync(absPath)) throw badInput(`文件夹不存在: ${absPath}`);
36
+ const st = statSync(absPath);
37
+ if (!st.isDirectory()) throw badInput(`不是文件夹: ${absPath}`);
38
+
39
+ const displayName = String(name || '').trim() || basename(absPath);
40
+ const id = folderAttachmentId(absPath);
41
+ const cur = conn.get('SELECT id, kind FROM attachments WHERE id = :id', { id });
42
+ if (cur && cur.kind !== 'folder') {
43
+ throw conflict(`附件 id 冲突:${id} 已被 kind=${cur.kind} 占用,无法登记为 folder`);
44
+ }
45
+
46
+ const upsert = (targetId: string): void => conn.run(
47
+ `INSERT INTO attachments
48
+ (id, kind, name, local_path, url, mime, size, hash, storage, group_id,
49
+ target_kind, target_key, target_seq, dedupe_key, meta,
50
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at)
51
+ VALUES (:id, 'folder', :name, '', '', '', 0, '', 'external', 0,
52
+ '', '', NULL, '', '{}',
53
+ :absPath, :absPath, NULL, :at, NULL, :at, :at)
54
+ ON CONFLICT(id) DO UPDATE SET
55
+ name = excluded.name,
56
+ abs_path = excluded.abs_path,
57
+ anchor_dir = excluded.anchor_dir,
58
+ missing_at = NULL,
59
+ last_seen_at = excluded.last_seen_at,
60
+ deleted_at = NULL,
61
+ updated_at = excluded.updated_at`,
62
+ { id: targetId, name: displayName, absPath, at: atMs },
63
+ );
64
+
65
+ try {
66
+ upsert(id);
67
+ } catch {
68
+ // Windows 大小写差异撞 ux_attachments_folder_path → 回到已登记那一行
69
+ const other = conn.get(
70
+ "SELECT id FROM attachments WHERE kind = 'folder' AND deleted_at IS NULL AND abs_path = :absPath COLLATE NOCASE",
71
+ { absPath },
72
+ );
73
+ if (!other) throw conflict(`文件夹已用另一条记录登记: ${absPath}`);
74
+ upsert(String(other.id));
75
+ return { id: String(other.id), name: displayName, absPath };
76
+ }
77
+ return { id, name: displayName, absPath };
78
+ }
79
+
80
+ /** 正文里出现 nxkv://folder/<id> 时:行必须已存在,否则不认这条引用。 */
81
+ export function ensureFolderAttachment(conn: any, { id, name = '', atMs = Date.now() }: {
82
+ id?: string | null; name?: string; atMs?: number;
83
+ } = {}): string | null {
84
+ const attId = String(id || '').trim();
85
+ if (!attId) return null;
86
+ const row = conn.get(
87
+ "SELECT id, name FROM attachments WHERE id = :id AND kind = 'folder' AND deleted_at IS NULL",
88
+ { id: attId },
89
+ );
90
+ if (!row) return null;
91
+ if (name && !row.name) {
92
+ conn.run('UPDATE attachments SET name = :name, updated_at = :at WHERE id = :id', {
93
+ id: attId, name: String(name), at: atMs,
94
+ });
95
+ }
96
+ return attId;
97
+ }
@@ -25,6 +25,7 @@ const MD_LINK_RE = /!?\[([^\]]*)\]\(\s*([^)\s]+)\s*\)/g;
25
25
  const NXKV_TASK_RE = /^nxkv:\/\/task\/(\d+)$/i;
26
26
  const NXKV_REF_RE = /^nxkv:\/\/ref\/([A-Za-z0-9_-]+)$/i;
27
27
  const NXKV_MDFILE_RE = /^nxkv:\/\/mdfile\/([A-Za-z0-9_-]+)$/i;
28
+ const NXKV_FOLDER_RE = /^nxkv:\/\/folder\/([A-Za-z0-9_-]+)$/i;
28
29
 
29
30
  const sha1 = (s: unknown): string => createHash('sha1').update(String(s), 'utf8').digest('hex');
30
31
 
@@ -33,13 +34,14 @@ export type AttachmentRole = 'inline' | 'reference' | 'doc' | 'attach';
33
34
 
34
35
  /** 正文里解析出的一条引用;position / role 在入清单时补齐。 */
35
36
  export interface AttachmentRef {
36
- kind: 'file' | 'url' | 'task' | 'ref' | 'mdfile';
37
+ kind: 'file' | 'url' | 'task' | 'ref' | 'mdfile' | 'folder';
37
38
  id?: string;
38
39
  name: string;
39
40
  isImage?: boolean;
40
41
  targetTaskId?: number;
41
42
  targetRefId?: string;
42
43
  targetMdfileId?: string;
44
+ targetFolderId?: string;
43
45
  url?: string;
44
46
  position?: number;
45
47
  role?: AttachmentRole;
@@ -117,9 +119,11 @@ export function parseAttachmentRefs(text?: unknown): AttachmentRef[] {
117
119
  const task = target.match(NXKV_TASK_RE);
118
120
  const doc = target.match(NXKV_REF_RE);
119
121
  const md = target.match(NXKV_MDFILE_RE);
122
+ const dir = target.match(NXKV_FOLDER_RE);
120
123
  if (task) ref = { kind: 'task', targetTaskId: Number(task[1]), name: name || `任务 ${task[1]}` };
121
124
  else if (doc) ref = { kind: 'ref', targetRefId: doc[1], name: name || (doc[1] ?? '') };
122
125
  else if (md) ref = { kind: 'mdfile', targetMdfileId: md[1], name: name || (md[1] ?? '') };
126
+ else if (dir) ref = { kind: 'folder', targetFolderId: dir[1], name: name || (dir[1] ?? '') };
123
127
  else if (/^https?:\/\//i.test(target)) ref = { kind: 'url', url: target, name: name || target };
124
128
  }
125
129
  if (!ref) continue;
@@ -127,6 +131,7 @@ export function parseAttachmentRefs(text?: unknown): AttachmentRef[] {
127
131
  const key = ref.id || (ref.kind === 'task' ? `task:${ref.targetTaskId}` : '')
128
132
  || (ref.kind === 'ref' ? `ref:${ref.targetRefId}` : '')
129
133
  || (ref.kind === 'mdfile' ? `mdfile:${ref.targetMdfileId}` : '')
134
+ || (ref.kind === 'folder' ? `folder:${ref.targetFolderId}` : '')
130
135
  || (ref.kind === 'url' ? `url:${(ref.url ?? '').toLowerCase()}` : '');
131
136
  if (seen.has(key)) continue;
132
137
  seen.add(key);
@@ -9,6 +9,7 @@ import {
9
9
  urlAttachmentId,
10
10
  } from './ids.js';
11
11
  import type { AttachmentRef } from './ids.js';
12
+ import { ensureFolderAttachment } from './folder.js';
12
13
 
13
14
  export interface UpsertFileAttachmentInput {
14
15
  id?: string;
@@ -282,5 +283,6 @@ export function ensureAttachment(conn: any, ref: AttachmentRef | null | undefine
282
283
  }
283
284
  if (ref.kind === 'ref') return ensureRefAttachment(conn, { refId: ref.targetRefId, name: ref.name, atMs });
284
285
  if (ref.kind === 'mdfile') return ensureMdfileAttachment(conn, { id: ref.targetMdfileId, name: ref.name, atMs });
286
+ if (ref.kind === 'folder') return ensureFolderAttachment(conn, { id: ref.targetFolderId, name: ref.name, atMs });
285
287
  return null;
286
288
  }
@@ -39,6 +39,12 @@ export {
39
39
  registerMdfile,
40
40
  } from './attachmentdb/mdfile.js';
41
41
  export type { MdfileRecord, MdfileRow, ReadMdfileResult } from './attachmentdb/mdfile.js';
42
+ export {
43
+ ensureFolderAttachment,
44
+ folderAttachmentId,
45
+ normalizeFolderPath,
46
+ registerFolder,
47
+ } from './attachmentdb/folder.js';
42
48
  export {
43
49
  linkAttachment,
44
50
  syncRefAttachments,
@@ -59,6 +59,7 @@ export const DIRECT_EDGES: MigrationStep[] = [
59
59
  { from: 6, to: 7, file: 'v7.sql', title: 'refs 描述字段(desc)' },
60
60
  { from: 7, to: 8, file: 'v8.sql', title: '去 rel:ref 只按 id / locator 寻址(bindings 补 tag)', apply: migrateRefsRel },
61
61
  { from: 8, to: 9, file: 'v9.sql', title: '任务新增 plan 状态(不进队列的临时草稿;重建 tasks 扩 CHECK)' },
62
+ { from: 9, to: 10, file: 'v10.sql', title: '附件新增 folder 类型(本地文件夹路径指针;重建 attachments 扩 CHECK)' },
62
63
  ];
63
64
 
64
65
  // 人读版本说明(docs/decisions 是决策的唯一权威位置,里面对应一份 date 化的 .md)
@@ -72,6 +73,7 @@ export const VERSION_NOTES = {
72
73
  7: 'docs/decisions/versions/2026-11-12-v7.md',
73
74
  8: 'docs/decisions/versions/2026-11-13-v8.md',
74
75
  9: 'docs/decisions/versions/2026-11-14-v9.md',
76
+ 10: 'docs/decisions/versions/2026-11-14-v10.md',
75
77
  };
76
78
 
77
79
  const keyOf = (from: number, to: number): string => `${from}->${to}`;
@@ -0,0 +1,86 @@
1
+ -- schema v10:附件新增 kind='folder'(本地文件夹路径指针)
2
+ --
3
+ -- 口径(#127):文件夹和 mdfile 一样是**外部路径指针**——字节(目录内容)不入库、
4
+ -- 不复制、不打包,只登记一个规范化绝对路径 + 展示名;交付时把路径给 agent,
5
+ -- 由它自己按需列目录 / 读文件。文件夹没有字节,size=0 / hash='' / mime=''。
6
+ --
7
+ -- SQLite 不能 ALTER 既有 CHECK → 按 v5 的 12-step 模式重建 attachments。
8
+ -- DROP TABLE 会级联删 task_attach / ref_attach 的行(defer_foreign_keys 只推迟
9
+ -- 校验、不推迟级联动作),所以先 TEMP 快照、DROP 前清空、重建后按显式列名回填。
10
+ --
11
+ -- @decision docs/decisions/2026-11-14-folder-attachment.md
12
+ PRAGMA defer_foreign_keys = ON;
13
+
14
+ CREATE TEMP TABLE _v10_task_attach AS
15
+ SELECT task_id, attachment_id, role, position, note, created_at FROM task_attach;
16
+ CREATE TEMP TABLE _v10_ref_attach AS
17
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM ref_attach;
18
+
19
+ -- @decision docs/decisions/2026-11-14-folder-attachment.md
20
+ CREATE TABLE attachments_new (
21
+ id TEXT PRIMARY KEY,
22
+ kind TEXT NOT NULL CHECK (kind IN ('file', 'url', 'task', 'ref', 'mdfile', 'folder')),
23
+ name TEXT NOT NULL DEFAULT '',
24
+ local_path TEXT NOT NULL DEFAULT '',
25
+ url TEXT NOT NULL DEFAULT '',
26
+ mime TEXT NOT NULL DEFAULT '',
27
+ size INTEGER NOT NULL DEFAULT 0 CHECK (size >= 0),
28
+ hash TEXT NOT NULL DEFAULT '',
29
+ storage TEXT NOT NULL DEFAULT '' CHECK (storage IN ('', 'local', 'cloud', 'external')),
30
+ group_id INTEGER NOT NULL DEFAULT 0,
31
+ target_kind TEXT NOT NULL DEFAULT '' CHECK (target_kind IN ('', 'task', 'ref')),
32
+ target_key TEXT NOT NULL DEFAULT '',
33
+ target_seq INTEGER,
34
+ dedupe_key TEXT NOT NULL DEFAULT '',
35
+ meta TEXT NOT NULL DEFAULT '{}'
36
+ CHECK (json_valid(meta) AND json_type(meta) = 'object'),
37
+ abs_path TEXT NOT NULL DEFAULT '',
38
+ anchor_dir TEXT NOT NULL DEFAULT '',
39
+ missing_at INTEGER,
40
+ last_seen_at INTEGER,
41
+ deleted_at INTEGER,
42
+ created_at INTEGER NOT NULL,
43
+ updated_at INTEGER NOT NULL
44
+ );
45
+
46
+ INSERT INTO attachments_new (
47
+ id, kind, name, local_path, url, mime, size, hash, storage, group_id,
48
+ target_kind, target_key, target_seq, dedupe_key, meta,
49
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at
50
+ )
51
+ SELECT
52
+ id, kind, name, local_path, url, mime, size, hash, storage, group_id,
53
+ target_kind, target_key, target_seq, dedupe_key, meta,
54
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at
55
+ FROM attachments;
56
+
57
+ -- @decision docs/decisions/2026-11-14-folder-attachment.md
58
+ DROP TABLE attachments;
59
+
60
+ ALTER TABLE attachments_new RENAME TO attachments;
61
+
62
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_dedupe
63
+ ON attachments (dedupe_key) WHERE dedupe_key <> '' AND deleted_at IS NULL;
64
+ CREATE INDEX IF NOT EXISTS ix_attachments_kind ON attachments (kind, deleted_at);
65
+ CREATE INDEX IF NOT EXISTS ix_attachments_target ON attachments (target_kind, target_key, target_seq);
66
+ CREATE INDEX IF NOT EXISTS ix_attachments_group ON attachments (storage, group_id, deleted_at);
67
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_mdfile_path
68
+ ON attachments (abs_path COLLATE NOCASE)
69
+ WHERE kind = 'mdfile' AND deleted_at IS NULL;
70
+ -- 同一文件夹路径(大小写不敏感)只登记一行;mdfile 与 folder 各自独立
71
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_folder_path
72
+ ON attachments (abs_path COLLATE NOCASE)
73
+ WHERE kind = 'folder' AND deleted_at IS NULL;
74
+
75
+ -- DROP TABLE 是否级联取决于连接上的 foreign_keys:先清空再回填,两种情形都不重不漏
76
+ DELETE FROM task_attach;
77
+ DELETE FROM ref_attach;
78
+ INSERT OR REPLACE INTO task_attach (task_id, attachment_id, role, position, note, created_at)
79
+ SELECT task_id, attachment_id, role, position, note, created_at FROM _v10_task_attach;
80
+ INSERT OR REPLACE INTO ref_attach (ref_id, attachment_id, role, position, note, created_at)
81
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM _v10_ref_attach;
82
+
83
+ -- @decision docs/decisions/2026-11-14-folder-attachment.md
84
+ DROP TABLE _v10_task_attach;
85
+ -- @decision docs/decisions/2026-11-14-folder-attachment.md
86
+ DROP TABLE _v10_ref_attach;
@@ -32,7 +32,9 @@
32
32
  */
33
33
  // v9(2026-11-14):tasks.status 新增 `plan`(不进队列的临时草稿态);
34
34
  // SQLite 不能 ALTER CHECK,按 v5 的 12-step 模式重建 tasks 并快照/回填所有关系表。
35
- export const CURRENT_SCHEMA_VERSION = 9;
35
+ // v10(2026-11-14):attachments.kind 新增 `folder`(本地文件夹路径指针,
36
+ // 不复制目录内容);同样按 v5 的 12-step 模式重建以扩 CHECK。
37
+ export const CURRENT_SCHEMA_VERSION = 10;
36
38
 
37
39
  /**
38
40
  * 运行时最低 Node 版本。
@@ -18,6 +18,7 @@ const input = z.object({
18
18
  task: z.string().optional().describe("任务全局 id(kind=task)"),
19
19
  doc: z.string().optional().describe("另一篇文档的 ref/path(kind=ref)"),
20
20
  mdfile: z.string().optional().describe("本地 .md 文件路径(kind=mdfile:只登记指针,不复制正文)"),
21
+ folder: z.string().optional().describe("本地文件夹路径(kind=folder:只登记目录路径,不复制内容)"),
21
22
  name: z.string().optional().describe("显示名(默认取文件名/原名)"),
22
23
  note: z.string().optional().describe("附件区备注"),
23
24
  noEmbed: z.boolean().optional().describe("只写 ref_attach(role=attach),不改正文"),
@@ -29,7 +30,7 @@ export class DocAttachAction extends ActionBase<typeof input> {
29
30
  id: 'doc.attach',
30
31
  cli: ['docs', 'attach'],
31
32
  http: ['POST', '/api/docs/attach'],
32
- summary: '给文档挂资源:--path / --fileId / --url / --task / --doc / --mdfile 之一;默认追加进正文,--no-embed 只挂附件区(不写正文)',
33
+ summary: '给文档挂资源:--path / --fileId / --url / --task / --doc / --mdfile / --folder 之一;默认追加进正文,--no-embed 只挂附件区(不写正文)',
33
34
  args: ['ref'],
34
35
  input,
35
36
  render: renderAttach,
@@ -13,6 +13,7 @@ import {
13
13
  linkAttachment,
14
14
  listRefAttachments,
15
15
  registerMdfile,
16
+ registerFolder,
16
17
  unlinkAttachment,
17
18
  updateAttachmentNote,
18
19
  upsertFileAttachment,
@@ -84,6 +85,8 @@ export interface AttachToDocCtx {
84
85
  doc?: unknown;
85
86
  /** 本地 md 文件(登记为 kind=mdfile,不复制正文) */
86
87
  mdfile?: unknown;
88
+ /** 本地文件夹(登记为 kind=folder,只存路径) */
89
+ folder?: unknown;
87
90
  noEmbed?: unknown;
88
91
  note?: unknown;
89
92
  [key: string]: unknown;
@@ -185,10 +188,20 @@ export async function attachToDoc(ctx: AttachToDocCtx): Promise<AttachToDocResul
185
188
  displayName = displayName || rec.name;
186
189
  kind = 'mdfile';
187
190
  markdown = `[${displayName}](nxkv://mdfile/${rec.id})`;
191
+ } else if (ctx.folder) {
192
+ // 本地文件夹:只登记路径指针(kind=folder, storage=external),目录内容不入库
193
+ const rec = tx(
194
+ (conn) => registerFolder(conn, { path: ctx.folder, name: displayName }),
195
+ { db, mode: 'IMMEDIATE' }
196
+ );
197
+ attachmentId = rec.id;
198
+ displayName = displayName || rec.name;
199
+ kind = 'folder';
200
+ markdown = `[${displayName}](nxkv://folder/${rec.id})`;
188
201
  }
189
202
 
190
203
  if (!attachmentId) {
191
- throw badInput('需要 --path / --fileId / --url / --task / --doc / --mdfile 之一');
204
+ throw badInput('需要 --path / --fileId / --url / --task / --doc / --mdfile / --folder 之一');
192
205
  }
193
206
 
194
207
  const noEmbed = !!(ctx.noEmbed ?? ctx['no-embed']);
@@ -55,8 +55,8 @@ export function renderTaskAttachments(d: RenderInput): string {
55
55
  for (const a of rows) {
56
56
  const docMark = a.role === 'doc' ? ' 〔进原文〕' : '';
57
57
  const noteMark = a.note ? ` # ${a.note}` : '';
58
- lines.push(` ${a.kind === 'image' ? '图片' : a.kind === 'url' ? '链接' : a.kind === 'task' ? '任务' : a.kind === 'ref' ? '文档' : a.kind === 'mdfile' ? 'md' : '附件'} ${a.name} [${a.id}]${docMark}${noteMark}`);
59
- lines.push(` ${a.localPath || a.url || (a.kind === 'mdfile' ? a.absPath : '') || a.target || '(本机附件仓缺失)'}${a.kind === 'mdfile' && a.missing ? ' (源文件已不在)' : ''}`);
58
+ lines.push(` ${a.kind === 'image' ? '图片' : a.kind === 'url' ? '链接' : a.kind === 'task' ? '任务' : a.kind === 'ref' ? '文档' : a.kind === 'mdfile' ? 'md' : a.kind === 'folder' ? '文件夹' : '附件'} ${a.name} [${a.id}]${docMark}${noteMark}`);
59
+ lines.push(` ${a.localPath || a.url || (a.kind === 'mdfile' || a.kind === 'folder' ? a.absPath : '') || a.target || '(本机附件仓缺失)'}${a.kind === 'mdfile' && a.missing ? ' (源文件已不在)' : ''}`);
60
60
  }
61
61
  }
62
62
  return lines.join('\n');
@@ -16,6 +16,7 @@ const input = z.object({
16
16
  task: z.string().optional().describe("同主题下的任务编号(kind=task,落 nxkv://task/<id>)"),
17
17
  ref: z.string().optional().describe("文档路径或 ref id(kind=ref,落 nxkv://ref/<refId>)"),
18
18
  mdfile: z.string().optional().describe("本地 .md 文件路径(kind=mdfile:只登记指针,不复制正文;web 的 md 栏按此过滤)"),
19
+ folder: z.string().optional().describe("本地文件夹路径(kind=folder:只登记目录路径,不复制目录内容;交付给 agent 的是绝对路径)"),
19
20
  inline: z.boolean().optional().describe("文档进原文:交付时附全文(截断 2 万字)而不是只给路径;仅 --ref 有效"),
20
21
  name: z.string().optional().describe("显示名 / 本地文件名(默认取原名)"),
21
22
  kind: z.string().optional().describe("image | file(仅 --path/--fileId 用;不给按扩展名判)"),
@@ -29,10 +30,10 @@ export class LocaltaskAttachAction extends ActionBase<typeof input> {
29
30
  id: 'localtask.attach',
30
31
  cli: ['localtask', 'attach'],
31
32
  http: ['POST', '/api/localtasks/attach'],
32
- summary: '给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档)/ --mdfile(本地 md 指针);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文)',
33
+ summary: '给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档)/ --mdfile(本地 md 指针)/ --folder(本地文件夹路径);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文)',
33
34
  input,
34
35
  render: (d: any) =>
35
- `已附加 ${d.fileId}(${d.kind === 'image' ? '图片' : d.kind === 'url' ? '链接' : d.kind === 'task' ? '任务' : d.kind === 'ref' ? '文档' : d.kind === 'mdfile' ? 'md' : '文件'})到主题「${d.name}」#${d.task.id} · ${d.role === 'doc' ? '文档资料(交付进原文)' : d.area === 'area' ? '附件区(未写正文)' : '正文内嵌'}${d.markdown ? `\n嵌入: ${d.markdown}` : ''}`,
36
+ `已附加 ${d.fileId}(${d.kind === 'image' ? '图片' : d.kind === 'url' ? '链接' : d.kind === 'task' ? '任务' : d.kind === 'ref' ? '文档' : d.kind === 'mdfile' ? 'md' : d.kind === 'folder' ? '文件夹' : '文件'})到主题「${d.name}」#${d.task.id} · ${d.role === 'doc' ? '文档资料(交付进原文)' : d.area === 'area' ? '附件区(未写正文)' : '正文内嵌'}${d.markdown ? `\n嵌入: ${d.markdown}` : ''}`,
36
37
  })
37
38
  override async run(ctx: ActionInput<this['_input']>) {
38
39
 
@@ -47,6 +48,7 @@ export class LocaltaskAttachAction extends ActionBase<typeof input> {
47
48
  task: ctx.task,
48
49
  ref: ctx.ref,
49
50
  mdfile: ctx.mdfile,
51
+ folder: ctx.folder,
50
52
  inline: ctx.inline,
51
53
  name: ctx.name,
52
54
  kind: ctx.kind,
@@ -11,7 +11,7 @@ import { existsSync } from 'node:fs';
11
11
  import { isImageName } from '../../core/filekind.js';
12
12
  import { stripFrontmatter } from '../../shared/frontmatter.js';
13
13
 
14
- const KIND_LABEL: Record<string, string> = { file: '附件', url: '链接', task: '任务', ref: '文档', mdfile: 'md' };
14
+ const KIND_LABEL: Record<string, string> = { file: '附件', url: '链接', task: '任务', ref: '文档', mdfile: 'md', folder: '文件夹' };
15
15
  const IMAGE_LABEL = '图片';
16
16
  export const ORIGIN_LABEL = { inline: '正文内嵌', area: '附件区' };
17
17
  export const STATUS_LABEL: Record<string, string> = { pending: '待领取', claimed: '进行中', done: '已完成', cancelled: '已作废' };
@@ -33,7 +33,7 @@ function metaOf(row: any): Record<string, any> {
33
33
  /** 资源类型归一:image / 空 / 其它未知值 → file;url/task/ref/mdfile 原样。 */
34
34
  function baseKind(row: any): string {
35
35
  const k = String((row && row.kind) || '');
36
- return k === 'url' || k === 'task' || k === 'ref' || k === 'mdfile' ? k : 'file';
36
+ return k === 'url' || k === 'task' || k === 'ref' || k === 'mdfile' || k === 'folder' ? k : 'file';
37
37
  }
38
38
 
39
39
  export function kindLabelOf(kind: unknown, isImage: unknown): string {
@@ -205,7 +205,7 @@ export function resourceOf(row: any, lookups: ResourceLookups = {}): any {
205
205
  areaLabel: ORIGIN_LABEL[origin],
206
206
  storage: kind === 'file' ? String(row.storage || '')
207
207
  : kind === 'url' ? 'url'
208
- : kind === 'mdfile' ? 'external' : 'internal',
208
+ : kind === 'mdfile' || kind === 'folder' ? 'external' : 'internal',
209
209
  synced: kind !== 'file',
210
210
  localPath: '',
211
211
  targetKind: String(row.targetKind || ''),
@@ -281,6 +281,32 @@ export function resourceOf(row: any, lookups: ResourceLookups = {}): any {
281
281
  };
282
282
  }
283
283
 
284
+ if (kind === 'folder') {
285
+ // 本地文件夹指针:库里只有 abs_path,目录内容不入库;交付只给路径让 agent 自己列目录。
286
+ const absPath = String(row.absPath || row.abs_path || meta.absPath || '');
287
+ const exists = !!absPath && existsSync(absPath);
288
+ const missing = !exists || (row.missingAt !== null && row.missingAt !== undefined);
289
+ const title = String(row.name || (absPath ? absPath.split(/[\\/]/).pop() : '') || base.id);
290
+ const readCmd = `nx-kv file content ${base.id}`;
291
+ const locator = `${title}${absPath ? `(${absPath})` : ''}`;
292
+ return {
293
+ ...base,
294
+ absPath,
295
+ exists,
296
+ missing,
297
+ fileId: base.id,
298
+ title,
299
+ readCmd,
300
+ target: absPath || locator,
301
+ needsSync: false,
302
+ cmd: readCmd,
303
+ locator,
304
+ usage: missing
305
+ ? `文件夹当前不可访问(${absPath || '路径为空'}):请确认目录是否还在本机`
306
+ : `这是本地文件夹的路径指针(目录内容不在库里):先列目录 ${absPath} 看结构,再用 Read 读需要的文件`,
307
+ };
308
+ }
309
+
284
310
  if (kind === 'mdfile') {
285
311
  // 外部 md 文件指针:字节在用户磁盘原地(storage='external'),库里只有 abs_path + hash。
286
312
  // 渲染分支只看 kind,不看 MIME / 扩展名。
@@ -21,13 +21,14 @@ import { hostOfUrl, kindLabelOf, ORIGIN_LABEL, sizeTextOf, STATUS_LABEL } from '
21
21
  * ref → { refId, title, desc, readCmd, content, truncated }
22
22
  * content 只在「文档资料」绑定(role='doc',交付读全文)且真的读到时非空。
23
23
  * mdfile → { absPath, anchorDir, content, truncated, stale, missing, readCmd }
24
+ * folder → { absPath, exists, missing, readCmd }(#127:目录内容不入库,只给路径)
24
25
  * content 是读时从磁盘现取的正文(截断 2 万字);missing 时为空、stale 表示指纹漂移。
25
26
  * 通用 note = 边上的说明(desc,#162):attach --note 的落点,清单行透出。
26
27
  * 旧模板兼容:平铺别名 localPath / fileId / urlText / href / taskId / title /
27
28
  * seq / showCmd / refId / target / area / areaLabel。
28
29
  */
29
30
  function ctxItemOf(a: any): any {
30
- const kind = ['url', 'task', 'ref', 'mdfile'].includes(a.kind) ? a.kind : 'file';
31
+ const kind = ['url', 'task', 'ref', 'mdfile', 'folder'].includes(a.kind) ? a.kind : 'file';
31
32
  const isImage = kind === 'file' && (a.isImage === undefined ? isImageName(a.name, a.mime) : !!a.isImage);
32
33
  const role = String(a.role || '');
33
34
  const origin =
@@ -132,6 +133,29 @@ function ctxItemOf(a: any): any {
132
133
  };
133
134
  }
134
135
 
136
+ if (kind === 'folder') {
137
+ const absPath = String(a.absPath || a.localPath || '');
138
+ const exists = a.exists === undefined ? !!absPath : !!a.exists;
139
+ const missing = a.missing === undefined ? !exists : !!a.missing;
140
+ const readCmd = String(a.readCmd || `nx-kv file content ${item.id}`);
141
+ const folder = { absPath, exists, missing, readCmd };
142
+ const usage = String(a.usage || (missing
143
+ ? `文件夹当前不可访问(${absPath || '路径为空'}):请确认目录是否还在本机`
144
+ : `这是本地文件夹的路径指针:先列目录 ${absPath} 看结构,再用 Read 读需要的文件`));
145
+ return {
146
+ ...item,
147
+ absPath,
148
+ path: absPath,
149
+ exists,
150
+ missing,
151
+ folder,
152
+ usage,
153
+ cmd: String(a.cmd !== undefined ? a.cmd : readCmd),
154
+ locator: String(a.locator || absPath || item.name),
155
+ needsSync: false,
156
+ };
157
+ }
158
+
135
159
  if (kind === 'mdfile') {
136
160
  const absPath = String(a.absPath || a.localPath || '');
137
161
  const anchorDir = String(a.anchorDir || '');
@@ -36,6 +36,7 @@ import {
36
36
  listTaskAttachmentsBySeq,
37
37
  readMdfile,
38
38
  registerMdfile,
39
+ registerFolder,
39
40
  resolveRefId,
40
41
  unlinkAttachment,
41
42
  updateAttachmentNote,
@@ -167,6 +168,8 @@ export interface AttachToTaskOptions {
167
168
  ref?: unknown;
168
169
  /** 本地 md 文件(kind=mdfile:只登记路径指针,不复制正文) */
169
170
  mdfile?: unknown;
171
+ /** 本地文件夹(kind=folder:只登记路径指针,不复制目录内容) */
172
+ folder?: unknown;
170
173
  note?: unknown;
171
174
  noEmbed?: unknown;
172
175
  inline?: unknown;
@@ -191,9 +194,10 @@ export interface AttachToTaskOptions {
191
194
  * --task <seq> 同主题下的另一条任务(kind=task,nxkv://task/<id>)
192
195
  * --ref <路径|id> 文档库里的 ref(kind=ref,nxkv://ref/<refId>)
193
196
  * --mdfile <路径> 本地 md 文件(kind=mdfile,nxkv://mdfile/<attId>;字节不入库)
197
+ * --folder <目录> 本地文件夹(kind=folder,nxkv://folder/<attId>;只登记路径,不复制目录内容)
194
198
  */
195
199
  export async function attachToTask({
196
- id, cwd, key, path, fileId, name, kind, url, task, ref, mdfile, note, noEmbed, inline,
200
+ id, cwd, key, path, fileId, name, kind, url, task, ref, mdfile, folder, note, noEmbed, inline,
197
201
  }: AttachToTaskOptions = {}): Promise<Record<string, any>> {
198
202
  const cur = await service.getTask({ id, cwd, key }); // 存在性与参数校验都在队列本体
199
203
  const topicKey = cur.key || key || '';
@@ -322,11 +326,21 @@ export async function attachToTask({
322
326
  displayName = displayName || rec.name;
323
327
  resolvedKind = 'mdfile';
324
328
  markdown = `[${displayName}](nxkv://mdfile/${rec.id})`;
329
+ } else if (folder) {
330
+ // 本地文件夹:只登记路径指针(kind=folder / storage=external),目录内容不入库
331
+ const rec = tx(
332
+ (conn) => registerFolder(conn, { path: folder, name: displayName }),
333
+ { db, mode: 'IMMEDIATE' }
334
+ );
335
+ attachmentId = rec.id;
336
+ displayName = displayName || rec.name;
337
+ resolvedKind = 'folder';
338
+ markdown = `[${displayName}](nxkv://folder/${rec.id})`;
325
339
  }
326
340
 
327
341
  if (!attachmentId) {
328
342
  throw badInput(
329
- '需要 --path <本机文件>、--fileId <已有附件>、--url <链接>、--task <编号>、--ref <文档> 或 --mdfile <本地 md> 之一'
343
+ '需要 --path <本机文件>、--fileId <已有附件>、--url <链接>、--task <编号>、--ref <文档>、--mdfile <本地 md> 或 --folder <本地目录> 之一'
330
344
  );
331
345
  }
332
346
  const wantInline = !!inline;
@@ -137,11 +137,11 @@ export const DEFAULT_CONTEXT_TEMPLATE = [
137
137
  */
138
138
  export const DEFAULT_ATTACH_TEMPLATE = [
139
139
  '{{#if attach}}',
140
- '〔附件〕本任务包含 {{attach.count}} 个附件(正文内嵌 {{attach.inlineCount}} · 附件区 {{attach.areaCount}})。请先识别附件内容(图片先看图、文档先读内容)再开始处理,不要跳过附件。',
140
+ '〔附件〕本任务包含 {{attach.count}} 个附件(正文内嵌 {{attach.inlineCount}} · 附件区 {{attach.areaCount}})。请先识别附件内容(图片先看图、文档先读内容、文件夹先列目录)再开始处理,不要跳过附件。',
141
141
  '',
142
142
  '附件清单:',
143
143
  '{{#each attach.list}}',
144
- ' - [{{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}}{{#if mdfile}}{{mdfile.absPath}}{{#if mdfile.missing}}(源文件已不在){{/if}}{{/if}}{{#if note}} # {{note}}{{/if}}',
144
+ ' - [{{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}}{{#if mdfile}}{{mdfile.absPath}}{{#if mdfile.missing}}(源文件已不在){{/if}}{{/if}}{{#if folder}}{{folder.absPath}}{{#if folder.missing}}(目录已不在){{/if}}{{/if}}{{#if note}} # {{note}}{{/if}}',
145
145
  '{{/each}}',
146
146
  '',
147
147
  '取用方式:',