nx-kv 0.66.1 → 0.66.3

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 (96) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/assets/nx-kv/references/A03-/346/226/207/346/241/243/344/270/216/345/275/222/345/261/236.md +1 -1
  3. package/package.json +1 -1
  4. package/src/core/attachmentdb/ids.ts +14 -1
  5. package/src/core/attachmentdb/query.ts +0 -38
  6. package/src/core/attachmentdb/repo.ts +98 -0
  7. package/src/core/attachmentdb.ts +5 -1
  8. package/src/core/db/migrations/index.ts +2 -0
  9. package/src/core/db/migrations/v15.sql +88 -0
  10. package/src/core/db/version.ts +4 -1
  11. package/src/modules/claim/assemble.ts +0 -5
  12. package/src/modules/claim/host.ts +1 -3
  13. package/src/modules/claim/preview.ts +0 -1
  14. package/src/modules/docs/actions/docs-detach.ts +1 -2
  15. package/src/modules/docs/attach.ts +3 -17
  16. package/src/modules/docs/render.ts +4 -13
  17. package/src/modules/localtask/actions/localtask-attach.ts +4 -2
  18. package/src/modules/localtask/actions/localtask-config.ts +2 -11
  19. package/src/modules/localtask/actions/localtask-detach.ts +1 -3
  20. package/src/modules/localtask/infra/repo/settings.ts +1 -9
  21. package/src/modules/localtask/lifecycle/task-templates.ts +0 -13
  22. package/src/modules/localtask/lifecycle/topics.ts +3 -6
  23. package/src/modules/localtask/ops/attach-resource.ts +46 -4
  24. package/src/modules/localtask/ops/attach-template.ts +73 -3
  25. package/src/modules/localtask/ops/attach.ts +45 -18
  26. package/src/modules/localtask/ui/action-render.ts +3 -12
  27. package/src/modules/promptplug/compose.ts +1 -3
  28. package/src/modules/promptplug/factory.ts +13 -2
  29. package/src/modules/promptplug/plugins/attachment.ts +56 -6
  30. package/src/modules/promptplug/plugins/context.ts +11 -2
  31. package/src/modules/promptplug/template-store.ts +72 -11
  32. package/src/shared/prompt-blocks.ts +2 -23
  33. package/src/web/frontend/api/cli-tree.json +4 -4
  34. package/src/web/frontend/api/client.generated.ts +8 -8
  35. package/src/web/frontend/api/tasks.ts +117 -0
  36. package/src/web/frontend/components/Introduction/index.tsx +50 -3
  37. package/src/web/frontend/components/Introduction/style.css +6 -0
  38. package/src/web/frontend/components/Introduction/use-intro.ts +25 -0
  39. package/src/web/frontend/components/md/attachments/attach-area.tsx +9 -11
  40. package/src/web/frontend/components/md/attachments/attach-common.ts +12 -5
  41. package/src/web/frontend/components/md/attachments/attach-modal.tsx +54 -9
  42. package/src/web/frontend/components/md/attachments/attach-repo-pick.tsx +48 -0
  43. package/src/web/frontend/components/sidebar/task-children.tsx +14 -11
  44. package/src/web/frontend/{page/dir → components/task-panel}/dag-editor.tsx +1 -1
  45. package/src/web/frontend/components/task-panel/task-ops.ts +299 -0
  46. package/src/web/frontend/components/task-panel/task-page.tsx +495 -0
  47. package/src/web/frontend/components/tool-acts/modules.ts +3 -0
  48. package/src/web/frontend/page/dir/api.ts +4 -108
  49. package/src/web/frontend/page/dir/index.tsx +148 -331
  50. package/src/web/frontend/page/dir/task-board-section.tsx +3 -0
  51. package/src/web/frontend/page/dir/task-dock-panel.tsx +1 -1
  52. package/src/web/frontend/page/dir/task.tsx +1 -1
  53. package/src/web/frontend/page/doc/doc-dock.tsx +1 -1
  54. package/src/web/frontend/page/group/api.ts +3 -21
  55. package/src/web/frontend/page/group/group-project-memo.ts +41 -0
  56. package/src/web/frontend/page/group/index.tsx +287 -426
  57. package/src/web/frontend/page/settings/api.ts +1 -2
  58. package/src/web/frontend/page/settings/prompt-templates-section.tsx +12 -44
  59. package/src/web/public/assets/{bar-Dy_QDX2h.js → bar-D7cWe7Kp.js} +1 -1
  60. package/src/web/public/assets/{composer-launch-B7DH53Yf.js → composer-launch--nJGFG35.js} +1 -1
  61. package/src/web/public/assets/{composer-panel-Cj1J16r-.js → composer-panel-Dhivt7UJ.js} +1 -1
  62. package/src/web/public/assets/{dag-DXRPHVl8.js → dag-DUhHxgTk.js} +1 -1
  63. package/src/web/public/assets/dir-CkYGYT9e.js +1 -0
  64. package/src/web/public/assets/doc-DgYKv2wo.css +1 -0
  65. package/src/web/public/assets/doc-QBHQi1EV.js +6 -0
  66. package/src/web/public/assets/group-CfJxWA7V.js +1 -0
  67. package/src/web/public/assets/group-project-memo-G-O6sPRw.js +1 -0
  68. package/src/web/public/assets/index-ByAPGidL.js +3 -0
  69. package/src/web/public/assets/{list-filter-CWxiOSg_.js → list-search-B2S2g8kn.js} +1 -1
  70. package/src/web/public/assets/md-history-DdM6P9Gq.js +47 -0
  71. package/src/web/public/assets/{progress-MPse2JLQ.js → progress-BVpSy-uF.js} +1 -1
  72. package/src/web/public/assets/refs-CCZgGPlL.js +2 -0
  73. package/src/web/public/assets/reopen-text-BC9a8KOp.js +13 -0
  74. package/src/web/public/assets/{repo-form-modal-CNLYR12c.js → repo-form-modal-D8WabN0R.js} +1 -1
  75. package/src/web/public/assets/{repos-BGx-yAXd.js → repos-V5xb5Kz-.js} +9 -9
  76. package/src/web/public/assets/settings-CAOSCF3E.js +1 -0
  77. package/src/web/public/assets/task-BwWlNP0i.js +13 -0
  78. package/src/web/public/assets/task-ops-DZgza5eZ.js +2 -0
  79. package/src/web/public/assets/task-utils--WIpAwUx.js +1 -0
  80. package/src/web/public/assets/{templates-Co1Qb1aA.js → templates-6ClSnYJN.js} +3 -3
  81. package/src/web/public/assets/{tool-bar-D5wLBLRl.js → tool-bar-BYdfBQeo.js} +1 -1
  82. package/src/web/public/assets/use-rail-drag-BMXJ48je.js +1 -0
  83. package/src/web/public/index.html +8 -8
  84. package/src/web/frontend/page/dir/landing.tsx +0 -553
  85. package/src/web/public/assets/dir-_M1ciSxM.js +0 -3
  86. package/src/web/public/assets/doc-Iuxssa-b.css +0 -1
  87. package/src/web/public/assets/doc-_iteSM2X.js +0 -6
  88. package/src/web/public/assets/get-loop-modal-DlAfqJMz.js +0 -2
  89. package/src/web/public/assets/group-CH8qe-eg.js +0 -1
  90. package/src/web/public/assets/index-Cui4IuGj.js +0 -3
  91. package/src/web/public/assets/md-history-Bj790fdn.js +0 -46
  92. package/src/web/public/assets/refs-DiIPoqnJ.js +0 -2
  93. package/src/web/public/assets/settings-Pt4YgGdY.js +0 -1
  94. package/src/web/public/assets/task-DOIIpQ4X.js +0 -13
  95. package/src/web/public/assets/task-utils-CJfMODCP.js +0 -13
  96. package/src/web/public/assets/use-rail-drag-CNOHXWng.js +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,61 @@
2
2
 
3
3
  本文件对外可见的变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
4
4
 
5
+ ## [0.66.3] - 2026-11-23 附件挂参考仓库 + 内部资源强制访问 + 移除只解除关联(#183–#189 / #251)
6
+
7
+ ### Added
8
+
9
+ - **附件支持参考仓库(kind=`repo`)**:`localtask attach --repo <key|路径|名称>`、
10
+ 面板「添加附件」新增「关联参考仓库」区块。附件是**登记指针**(不 clone / 不复制),
11
+ 行内 meta 带 `repoKey / name / desc / repoType / localPath / branch / docs[]`,
12
+ 按 repo key 去重(同一仓库重挂不建新行);未登记仓库明确报错,不退化成 folder。
13
+ - **内部资源强制访问**(task / ref / repo):附件段先声明「其中 N 个是系统内部资源——
14
+ 必须被实际访问:任务读正文、文档读全文、仓库读源码;未访问不得直接开始实现或交付」,
15
+ 再逐条给出可执行的 `access`(含 localPath 与命令);参考仓库额外强制
16
+ 「实现必须参考该仓库源码,禁止凭记忆臆测 API / 文件结构」。
17
+ - 模板变量新增 `{{mandatory}}` / `{{access}}` / `{{attach.mandatoryCount}}` /
18
+ `{{attach.hasMandatory}}` 与 `{{repo.localPath}}` / `{{repo.cmd}}` 等,设置页可检索。
19
+ - 组页记住归属项目(#187):按组记录上次选择(localStorage),下次进去直接用。
20
+
21
+ ### Changed
22
+
23
+ - **schema v15**:`attachments.kind` 新增 `repo`(`target_kind` 同步),12-step 重建 + 关系表快照回填。
24
+ - dst:`dir` / `group` 任务页合并为同一份模板组件(#251),组页补批量与行尾菜单;
25
+ 组 / 项目介绍行在无文档时不再整块消失。
26
+ - 附件弹窗「关联任务(本主题)」搜索收口到 `modules/board/task-search`,
27
+ 与 topic 页同一引擎(分词 AND / 剥 frontmatter / 通配 / 编号前缀)。
28
+ - 删除「系统提示词追加方式」选择:系统提示词**固定 XML 区块**,`plain` 直拼模式与
29
+ `--append-mode`、`APPEND_MODES` 全部下线。
30
+ - 侧栏「…还有 N 条」改为**点一次加载 10 条**(默认 8 条),不再一次铺开全部。
31
+ - 内置模板更新可传导:启用的用户副本若与当前内置实质相同(只是复制没改过)→ 跟随内置;
32
+ 组主篇正文内嵌(`{{group.intro}}`),repo / group 主篇独立加载。
33
+
34
+ ### Fixed
35
+
36
+ - 旧提示词模板引用已删除的 `group.note` 导致模板功能整体不可用(读时惰性迁移为
37
+ `group.introDesc` + 装配兜底)。
38
+ - **附件移除只解除关联**(#189):删掉 `purge` 能力(ops / action / 契约 / 前端弹窗 /
39
+ render 文案 / 死代码 `deleteAttachment`)。此前「连资源一起删」实际只对 file 删仓内字节,
40
+ 其余 kind 只删指针行,与文案承诺不一致;清理统一交给库级 GC(`file prune`:
41
+ 只删无引用行,file 只删附件根目录内字节,repo 指针按 key 幂等重建,实体表不碰)。
42
+
43
+ ## [0.66.2] - 2026-11-23 修复旧提示词模板数据不兼容导致模板功能整体不可用
44
+
45
+ ### Fixed
46
+
47
+ - **根因**:`40cb35d`(11-19「移除项目组上下文的组内描述 note」)删掉了 context 段的
48
+ `group.note` / `group.position` / `peers[].note` / `hasNote` 字段与内置模板引用,
49
+ 但**没有升级已落库的用户模板**;`6ac1074`(#153)起每段模板只允许引用 seed ∪
50
+ 自己的 dataSchema,旧模板一被装配就在 `assertPluginList` 抛
51
+ 「context: 模板引用了本段没有的变量 group.note」,预览 / 领取 / 设置页读取全线失败。
52
+ - **读时惰性迁移**(`template-store.migrateLegacyTemplateVars`):读取用户模板时把
53
+ `group.note` / `group.position` 换成合法的 `group.introDesc`,清掉成员行的
54
+ `note` / `hasNote` 引用,并**一次性回写 settings**,之后不再重复处理。
55
+ - **装配兜底**(`factory.buildPlugins`):用户层模板若仍含未声明变量,装配前回退出厂
56
+ 内置模板,绝不让一条旧数据把整条提示词链抛成「读取失败」;开发者显式传入的
57
+ overrides 仍严格校验(#153 契约不变)。
58
+ - 回归测试:旧模板迁移落盘、整链校验通过、用户数据兜底、显式 overrides 仍报错。
59
+
5
60
  ## [0.66.1] - 2026-11-23 工具按钮回归第一行(#182 验收)
6
61
 
7
62
  ### Fixed
@@ -177,7 +177,7 @@ nx-kv docs attach --ref ref:<refId> --path <本机文件> --json # 图片/文
177
177
  nx-kv docs attach --ref ref:<refId> --folder <本机目录> --json # 文件夹(只登记路径指针)
178
178
  nx-kv docs attach --ref ref:<refId> --mdfile <本机 md> --json # 本地 md 指针
179
179
  nx-kv docs attachments --ref ref:<refId> --json # 这篇挂了哪些资源
180
- nx-kv docs detach --ref ref:<refId> --attachment <id> --json # 摘掉一个(--purge 连资源一起删)
180
+ nx-kv docs detach --ref ref:<refId> --attachment <id> --json # 摘掉一个(只解除关联,资源留在孤儿池)
181
181
  ```
182
182
 
183
183
  ## 偏差与陷阱
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.66.1",
3
+ "version": "0.66.3",
4
4
  "description": "nx-kv — 本机任务队列(localtask)+ 文档库 + 仓库登记:serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
@@ -26,6 +26,7 @@ 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
28
  const NXKV_FOLDER_RE = /^nxkv:\/\/folder\/([A-Za-z0-9_-]+)$/i;
29
+ const NXKV_REPO_RE = /^nxkv:\/\/repo\/([A-Za-z0-9_-]+)$/i;
29
30
 
30
31
  const sha1 = (s: unknown): string => createHash('sha1').update(String(s), 'utf8').digest('hex');
31
32
 
@@ -34,7 +35,7 @@ export type AttachmentRole = 'inline' | 'reference' | 'doc' | 'attach';
34
35
 
35
36
  /** 正文里解析出的一条引用;position / role 在入清单时补齐。 */
36
37
  export interface AttachmentRef {
37
- kind: 'file' | 'url' | 'task' | 'ref' | 'mdfile' | 'folder';
38
+ kind: 'file' | 'url' | 'task' | 'ref' | 'mdfile' | 'folder' | 'repo';
38
39
  id?: string;
39
40
  name: string;
40
41
  isImage?: boolean;
@@ -42,6 +43,7 @@ export interface AttachmentRef {
42
43
  targetRefId?: string;
43
44
  targetMdfileId?: string;
44
45
  targetFolderId?: string;
46
+ targetRepoId?: string;
45
47
  url?: string;
46
48
  position?: number;
47
49
  role?: AttachmentRole;
@@ -64,6 +66,14 @@ export function taskAttachmentId(topicKey?: unknown, seq?: unknown): string {
64
66
  return 'att_task_' + sha1(`${String(topicKey || '')}:${Number(seq) || 0}`).slice(0, 16);
65
67
  }
66
68
 
69
+ /**
70
+ * 参考仓库附件的稳定 id:按**仓库 key** 去重(同一仓库重挂不建新行)。
71
+ * 与 folder 的区别是语义:repo 必带 key / type / docs,不能退化成普通目录。
72
+ */
73
+ export function repoAttachmentId(key?: unknown): string {
74
+ return 'att_repo_' + sha1(String(key || '').trim()).slice(0, 16);
75
+ }
76
+
67
77
  export function refAttachmentId(refId?: unknown): string {
68
78
  return 'att_ref_' + sha1(String(refId || '')).slice(0, 16);
69
79
  }
@@ -120,10 +130,12 @@ export function parseAttachmentRefs(text?: unknown): AttachmentRef[] {
120
130
  const doc = target.match(NXKV_REF_RE);
121
131
  const md = target.match(NXKV_MDFILE_RE);
122
132
  const dir = target.match(NXKV_FOLDER_RE);
133
+ const repoRef = target.match(NXKV_REPO_RE);
123
134
  if (task) ref = { kind: 'task', targetTaskId: Number(task[1]), name: name || `任务 ${task[1]}` };
124
135
  else if (doc) ref = { kind: 'ref', targetRefId: doc[1], name: name || (doc[1] ?? '') };
125
136
  else if (md) ref = { kind: 'mdfile', targetMdfileId: md[1], name: name || (md[1] ?? '') };
126
137
  else if (dir) ref = { kind: 'folder', targetFolderId: dir[1], name: name || (dir[1] ?? '') };
138
+ else if (repoRef) ref = { kind: 'repo', targetRepoId: repoRef[1], name: name || (repoRef[1] ?? '') };
127
139
  else if (/^https?:\/\//i.test(target)) ref = { kind: 'url', url: target, name: name || target };
128
140
  }
129
141
  if (!ref) continue;
@@ -132,6 +144,7 @@ export function parseAttachmentRefs(text?: unknown): AttachmentRef[] {
132
144
  || (ref.kind === 'ref' ? `ref:${ref.targetRefId}` : '')
133
145
  || (ref.kind === 'mdfile' ? `mdfile:${ref.targetMdfileId}` : '')
134
146
  || (ref.kind === 'folder' ? `folder:${ref.targetFolderId}` : '')
147
+ || (ref.kind === 'repo' ? `repo:${ref.targetRepoId}` : '')
135
148
  || (ref.kind === 'url' ? `url:${(ref.url ?? '').toLowerCase()}` : '');
136
149
  if (seen.has(key)) continue;
137
150
  seen.add(key);
@@ -138,44 +138,6 @@ function within(root: string | null | undefined, p: string | null | undefined):
138
138
  return b === a || b.startsWith(a.replace(/\/+$/, '') + '/');
139
139
  }
140
140
 
141
- export interface DeleteAttachmentResult {
142
- removed: boolean;
143
- reason?: string;
144
- bytesRemoved?: boolean;
145
- attachment?: AttachmentView | null;
146
- }
147
-
148
- /**
149
- * 删除资源行(可选连字节一起删)。仍被任何任务/文档引用时拒绝——关系表是权威,
150
- * 「解除关系」和「删资源」是两步,不能因为一次 detach --purge 误删别人在用的文件。
151
- * @returns {{removed:boolean, reason?:string, attachment?:object}}
152
- */
153
- export function deleteAttachment(conn: any, id: string | number, {
154
- attachmentsRoot, purgeBytes = true,
155
- }: { attachmentsRoot?: string; purgeBytes?: boolean } = {}): DeleteAttachmentResult {
156
- const row = getAttachment(conn, id);
157
- if (!row) return { removed: false, reason: 'not-found' };
158
- const still = conn.get(
159
- `SELECT 1 AS x FROM task_attach WHERE attachment_id = :id
160
- UNION ALL SELECT 1 FROM ref_attach WHERE attachment_id = :id LIMIT 1`,
161
- { id: row.id }
162
- );
163
- if (still) return { removed: false, reason: 'in-use', attachment: row };
164
- let bytesRemoved = false;
165
- if (purgeBytes && row.kind === 'file' && row.localPath && within(attachmentsRoot, row.localPath)) {
166
- try {
167
- if (existsSync(row.localPath)) {
168
- unlinkSync(row.localPath);
169
- bytesRemoved = true;
170
- }
171
- } catch {
172
- return { removed: false, reason: 'file-locked', attachment: row };
173
- }
174
- }
175
- conn.run('DELETE FROM attachments WHERE id = :id', { id: row.id });
176
- return { removed: true, bytesRemoved, attachment: row };
177
- }
178
-
179
141
  export function pruneOrphans(conn: any, { attachmentsRoot, dryRun = false }: {
180
142
  attachmentsRoot?: string; dryRun?: boolean;
181
143
  } = {}): { removed: AttachmentView[]; skipped: AttachmentView[] } {
@@ -0,0 +1,98 @@
1
+ // 参考仓库附件的登记(#184):附件是**指针**,字节留在原 checkout 里(不 clone / 不复制)。
2
+ //
3
+ // 与 folder 的区别是语义:repo 必须已在本机登记(repo get 能取到 key / type / 文档),
4
+ // 因此这里只认 key,并要求调用方先把仓库元数据查好一起写进 meta —— 交付时模板直接
5
+ // 从 meta 读,不必每次回查仓库表(但 localPath 的 exists 仍按盘上现况判定)。
6
+ import { existsSync } from 'node:fs';
7
+ import { badInput, conflict } from '../errors.js';
8
+ import { repoAttachmentId } from './ids.js';
9
+
10
+ export interface RegisterRepoAttachInput {
11
+ /** 仓库 key(github.com/org/name 或本机登记用的 key) */
12
+ key?: unknown;
13
+ name?: unknown;
14
+ desc?: unknown;
15
+ /** ref / dev */
16
+ repoType?: unknown;
17
+ /** checkout 的本地绝对路径 */
18
+ localPath?: unknown;
19
+ branch?: unknown;
20
+ /** 仓库已绑定的文档 refId 列表 */
21
+ docs?: unknown;
22
+ atMs?: number;
23
+ }
24
+
25
+ /**
26
+ * 登记(或复用)一条仓库附件。按 key 幂等:同一仓库重挂复用同一行,只刷新元数据。
27
+ */
28
+ export function registerRepoAttachment(conn: any, {
29
+ key, name = '', desc = '', repoType = '', localPath = '', branch = '', docs = [], atMs = Date.now(),
30
+ }: RegisterRepoAttachInput = {}): { id: string; name: string; localPath: string } {
31
+ const repoKey = String(key || '').trim();
32
+ if (!repoKey) throw badInput('repo 附件需要仓库 key(先用 nx-kv repo add 登记)');
33
+ const absPath = String(localPath || '');
34
+ const displayName = String(name || '').trim() || repoKey;
35
+ const id = repoAttachmentId(repoKey);
36
+ const cur = conn.get('SELECT id, kind FROM attachments WHERE id = :id', { id });
37
+ if (cur && cur.kind !== 'repo') {
38
+ throw conflict(`附件 id 冲突:${id} 已被 kind=${cur.kind} 占用,无法登记为 repo`);
39
+ }
40
+ const meta = JSON.stringify({
41
+ repoKey,
42
+ name: displayName,
43
+ desc: String(desc || ''),
44
+ repoType: String(repoType || ''),
45
+ localPath: absPath,
46
+ branch: String(branch || ''),
47
+ docs: Array.isArray(docs) ? docs.map((x) => String(x || '')).filter(Boolean) : [],
48
+ });
49
+ const upsert = (targetId: string): void => conn.run(
50
+ `INSERT INTO attachments
51
+ (id, kind, name, local_path, url, mime, size, hash, storage, group_id,
52
+ target_kind, target_key, target_seq, dedupe_key, meta,
53
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at)
54
+ VALUES (:id, 'repo', :name, :absPath, '', '', 0, '', 'external', 0,
55
+ 'repo', :key, NULL, :dedupe, :meta,
56
+ :absPath, :absPath, NULL, :at, NULL, :at, :at)
57
+ ON CONFLICT(id) DO UPDATE SET
58
+ name = excluded.name,
59
+ local_path = excluded.local_path,
60
+ abs_path = excluded.abs_path,
61
+ anchor_dir = excluded.anchor_dir,
62
+ target_key = excluded.target_key,
63
+ dedupe_key = excluded.dedupe_key,
64
+ meta = excluded.meta,
65
+ missing_at = NULL,
66
+ last_seen_at = excluded.last_seen_at,
67
+ deleted_at = NULL,
68
+ updated_at = excluded.updated_at`,
69
+ { id: targetId, name: displayName, key: repoKey, dedupe: `repo:${repoKey}`, meta, absPath, at: atMs },
70
+ );
71
+ upsert(id);
72
+ return { id, name: displayName, localPath: absPath };
73
+ }
74
+
75
+ /** 正文里出现 nxkv://repo/<id> 时:行必须已存在,否则不认这条引用。 */
76
+ export function ensureRepoAttachment(conn: any, { id, name = '', atMs = Date.now() }: {
77
+ id?: string | null; name?: string; atMs?: number;
78
+ } = {}): string | null {
79
+ const attId = String(id || '').trim();
80
+ if (!attId) return null;
81
+ const row = conn.get(
82
+ "SELECT id, name FROM attachments WHERE id = :id AND kind = 'repo' AND deleted_at IS NULL",
83
+ { id: attId },
84
+ );
85
+ if (!row) return null;
86
+ if (name && !row.name) {
87
+ conn.run('UPDATE attachments SET name = :name, updated_at = :at WHERE id = :id', {
88
+ id: attId, name: String(name), at: atMs,
89
+ });
90
+ }
91
+ return attId;
92
+ }
93
+
94
+ /** 盘上是否还有这个 checkout(交付时现判,不用登记时的快照)。 */
95
+ export function repoLocalExists(localPath: unknown): boolean {
96
+ const p = String(localPath || '');
97
+ return !!p && existsSync(p);
98
+ }
@@ -45,6 +45,11 @@ export {
45
45
  normalizeFolderPath,
46
46
  registerFolder,
47
47
  } from './attachmentdb/folder.js';
48
+ export {
49
+ ensureRepoAttachment,
50
+ registerRepoAttachment,
51
+ repoLocalExists,
52
+ } from './attachmentdb/repo.js';
48
53
  export {
49
54
  linkAttachment,
50
55
  syncRefAttachments,
@@ -75,7 +80,6 @@ export {
75
80
  } from './attachmentdb/docs.js';
76
81
  export {
77
82
  archiveAttachmentManifests,
78
- deleteAttachment,
79
83
  getAttachment,
80
84
  listOrphans,
81
85
  listRefAttachments,
@@ -65,6 +65,7 @@ export const DIRECT_EDGES: MigrationStep[] = [
65
65
  { from: 11, to: 12, file: 'v12.sql', title: '去掉分类标签概念(删 ref_bindings.tag)' },
66
66
  { from: 12, to: 13, file: 'v13.sql', title: '去掉关系表上的业务 note(4 张表 drop note 列)' },
67
67
  { from: 13, to: 14, file: 'v14.sql', title: 'task_links.type 扩 fork(任务链四类节点:评论/反馈/重开/分支)' },
68
+ { from: 14, to: 15, file: 'v15.sql', title: "附件新增 repo 类型(参考仓库指针,不复制字节;重建 attachments 扩 CHECK)" },
68
69
  ];
69
70
 
70
71
  // 人读版本说明(docs/decisions 是决策的唯一权威位置,里面对应一份 date 化的 .md)
@@ -83,6 +84,7 @@ export const VERSION_NOTES = {
83
84
  12: 'docs/decisions/versions/2026-11-16-v12.md',
84
85
  13: 'docs/decisions/versions/2026-11-17-v13.md',
85
86
  14: 'docs/decisions/versions/2026-11-22-v14.md',
87
+ 15: 'docs/decisions/versions/2026-11-23-v15.md',
86
88
  };
87
89
 
88
90
  const keyOf = (from: number, to: number): string => `${from}->${to}`;
@@ -0,0 +1,88 @@
1
+ -- schema v15:附件新增 kind='repo'(参考仓库指针,#184)
2
+ --
3
+ -- 口径:参考仓库附件是**登记指针**——字节留在原 checkout(不 clone、不复制、不打包),
4
+ -- 行里带 repo key / type / 文档 refId 列表(meta),交付时模板据此强制「实现必须参考
5
+ -- 该仓库源码」,并给出 localPath 与 `repo get` / `repo doc list` 命令。
6
+ -- 与 folder 的区别是语义:folder 是任意目录;repo 必须已登记(带 key / type / docs)。
7
+ --
8
+ -- SQLite 不能 ALTER 既有 CHECK → 按 v10 的 12-step 模式重建 attachments。
9
+ -- DROP TABLE 会级联删 task_attach / ref_attach 的行,所以先 TEMP 快照、
10
+ -- DROP 前清空、重建后按显式列名回填。
11
+ --
12
+ -- @decision docs/decisions/versions/2026-11-23-v15.md
13
+ PRAGMA defer_foreign_keys = ON;
14
+
15
+ -- v13 已删关系表的业务 note 列,这里只快照现存列
16
+ CREATE TEMP TABLE _v15_task_attach AS
17
+ SELECT task_id, attachment_id, role, position, created_at FROM task_attach;
18
+ CREATE TEMP TABLE _v15_ref_attach AS
19
+ SELECT ref_id, attachment_id, role, position, created_at FROM ref_attach;
20
+
21
+ -- @decision docs/decisions/versions/2026-11-23-v15.md
22
+ CREATE TABLE attachments_new (
23
+ id TEXT PRIMARY KEY,
24
+ kind TEXT NOT NULL CHECK (kind IN ('file', 'url', 'task', 'ref', 'mdfile', 'folder', 'repo')),
25
+ name TEXT NOT NULL DEFAULT '',
26
+ local_path TEXT NOT NULL DEFAULT '',
27
+ url TEXT NOT NULL DEFAULT '',
28
+ mime TEXT NOT NULL DEFAULT '',
29
+ size INTEGER NOT NULL DEFAULT 0 CHECK (size >= 0),
30
+ hash TEXT NOT NULL DEFAULT '',
31
+ storage TEXT NOT NULL DEFAULT '' CHECK (storage IN ('', 'local', 'cloud', 'external')),
32
+ group_id INTEGER NOT NULL DEFAULT 0,
33
+ target_kind TEXT NOT NULL DEFAULT '' CHECK (target_kind IN ('', 'task', 'ref', 'repo')),
34
+ target_key TEXT NOT NULL DEFAULT '',
35
+ target_seq INTEGER,
36
+ dedupe_key TEXT NOT NULL DEFAULT '',
37
+ meta TEXT NOT NULL DEFAULT '{}'
38
+ CHECK (json_valid(meta) AND json_type(meta) = 'object'),
39
+ abs_path TEXT NOT NULL DEFAULT '',
40
+ anchor_dir TEXT NOT NULL DEFAULT '',
41
+ missing_at INTEGER,
42
+ last_seen_at INTEGER,
43
+ deleted_at INTEGER,
44
+ created_at INTEGER NOT NULL,
45
+ updated_at INTEGER NOT NULL
46
+ );
47
+
48
+ INSERT INTO attachments_new (
49
+ id, kind, name, local_path, url, mime, size, hash, storage, group_id,
50
+ target_kind, target_key, target_seq, dedupe_key, meta,
51
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at
52
+ )
53
+ SELECT
54
+ id, kind, name, local_path, url, mime, size, hash, storage, group_id,
55
+ target_kind, target_key, target_seq, dedupe_key, meta,
56
+ abs_path, anchor_dir, missing_at, last_seen_at, deleted_at, created_at, updated_at
57
+ FROM attachments;
58
+
59
+ -- @decision docs/decisions/versions/2026-11-23-v15.md
60
+ DROP TABLE attachments;
61
+
62
+ ALTER TABLE attachments_new RENAME TO attachments;
63
+
64
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_dedupe
65
+ ON attachments (dedupe_key) WHERE dedupe_key <> '' AND deleted_at IS NULL;
66
+ CREATE INDEX IF NOT EXISTS ix_attachments_kind ON attachments (kind, deleted_at);
67
+ CREATE INDEX IF NOT EXISTS ix_attachments_target ON attachments (target_kind, target_key, target_seq);
68
+ CREATE INDEX IF NOT EXISTS ix_attachments_group ON attachments (storage, group_id, deleted_at);
69
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_mdfile_path
70
+ ON attachments (abs_path COLLATE NOCASE)
71
+ WHERE kind = 'mdfile' AND deleted_at IS NULL;
72
+ -- 同一文件夹路径(大小写不敏感)只登记一行
73
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_attachments_folder_path
74
+ ON attachments (abs_path COLLATE NOCASE)
75
+ WHERE kind = 'folder' AND deleted_at IS NULL;
76
+
77
+ -- DROP TABLE 是否级联取决于连接上的 foreign_keys:先清空再回填,两种情形都不重不漏
78
+ DELETE FROM task_attach;
79
+ DELETE FROM ref_attach;
80
+ INSERT OR REPLACE INTO task_attach (task_id, attachment_id, role, position, created_at)
81
+ SELECT task_id, attachment_id, role, position, created_at FROM _v15_task_attach;
82
+ INSERT OR REPLACE INTO ref_attach (ref_id, attachment_id, role, position, created_at)
83
+ SELECT ref_id, attachment_id, role, position, created_at FROM _v15_ref_attach;
84
+
85
+ -- @decision docs/decisions/versions/2026-11-23-v15.md
86
+ DROP TABLE _v15_task_attach;
87
+ -- @decision docs/decisions/versions/2026-11-23-v15.md
88
+ DROP TABLE _v15_ref_attach;
@@ -40,7 +40,10 @@
40
40
  // 关系描述文档的定位不走 tag:desc 就在 ref 上。
41
41
  // v13(2026-11-17):彻底删除「关系表上的业务 note」概念——4 张关系表 drop note 列。
42
42
  // 关系表本身就表达多对多;文档描述走 ref.desc + 正文标题,参考仓库描述走绑定 ref 的文档。
43
- export const CURRENT_SCHEMA_VERSION = 14;
43
+ // v14(2026-11-22):task_links.type 扩 `fork`(任务链四类节点可区分)。
44
+ // v15(2026-11-23):attachments.kind 新增 `repo`(参考仓库指针:#184 附件挂仓库,
45
+ // 字节留在原 checkout,交付时强制参考源码);同样 12-step 重建扩 CHECK。
46
+ export const CURRENT_SCHEMA_VERSION = 15;
44
47
 
45
48
  /**
46
49
  * 运行时最低 Node 版本。
@@ -60,8 +60,6 @@ export interface DeliveryHostData {
60
60
  getLoopWaitMinutes?: number;
61
61
  /** 外部参数(--param k=v 解析产物):{{params.k}} + 平面扩展 {{k}} */
62
62
  params?: Record<string, string>;
63
- /** 设置里的追加模式:'plain' 直拼文本,其余(含缺省)包 XML 标签 */
64
- appendMode?: unknown;
65
63
  /** seed 原样透传的上下文键(保持 unknown:宿主传什么 seed 就是什么) */
66
64
  source?: unknown;
67
65
  summary?: unknown;
@@ -102,7 +100,6 @@ export async function assembleDelivery(host: DeliveryHostData): Promise<Assemble
102
100
  getLoopEnabled = false,
103
101
  getLoopWaitMinutes = 0,
104
102
  params,
105
- appendMode,
106
103
  trace,
107
104
  } = host;
108
105
  const renderWarnings: RenderWarning[] = [];
@@ -119,7 +116,6 @@ export async function assembleDelivery(host: DeliveryHostData): Promise<Assemble
119
116
  ...flat,
120
117
  };
121
118
 
122
- const mode: 'xml' | 'plain' = appendMode === 'plain' ? 'plain' : 'xml';
123
119
  // #152:模板是插件类的内置正文(不再从 settings 解析)。
124
120
  // 宿主取数以 Supply 注入(惰性:不消费就不算)。
125
121
  const plugins = [
@@ -137,7 +133,6 @@ export async function assembleDelivery(host: DeliveryHostData): Promise<Assemble
137
133
  plugins,
138
134
  groups: ['get', 'check', 'done'],
139
135
  seed: seedCtx,
140
- mode,
141
136
  trace,
142
137
  segments: DELIVERY_SEGMENTS,
143
138
  });
@@ -19,7 +19,7 @@
19
19
  // 「这段是哪来的」。真实领取不传 trace,行为与改造前逐字节一致。
20
20
  import { formatDuration, formatGoalTiming } from '../../core/instruction-template.js';
21
21
  import { parseFrontmatter } from '../../shared/frontmatter.js';
22
- import { getSettings, isGlobalKey, pendingQueueInfo } from '../localtask/service.js';
22
+ import { isGlobalKey, pendingQueueInfo } from '../localtask/service.js';
23
23
  import { assembleDelivery, type AssembledDelivery } from './assemble.js';
24
24
  import { annotateTaskDelivery, attachTemplateCtx } from '../localtask/ops/attach.js';
25
25
  import { readGroupContext } from './groupctx.js';
@@ -163,7 +163,6 @@ export async function buildTaskDelivery(
163
163
  // 提交的纯项目任务只带项目介绍,不把所属组的材料挂进来。
164
164
  const boardMark = String(parseFrontmatter(String((task && task.text) || '')).board || '').trim();
165
165
  const groupCtx = await readGroupContext(cwd as string, { board: boardMark });
166
- const settings: any = (await getSettings().catch(() => null)) || {};
167
166
 
168
167
  // ── 插件化组装(promptplug):宿主完成领域取数,插件 data() 做同步变换 ──
169
168
  // 任务级 goal → 完整 check 指令;目录级 goal → 状态行(二者都进 timecheck 段)。
@@ -207,7 +206,6 @@ export async function buildTaskDelivery(
207
206
  getLoopEnabled,
208
207
  getLoopWaitMinutes,
209
208
  params,
210
- appendMode: settings.appendMode,
211
209
  source: source || '',
212
210
  summary,
213
211
  cwd,
@@ -88,7 +88,6 @@ export async function previewTaskDelivery({ task, cwd, key, summary, params }: P
88
88
  // 两个旧开关保留:模板已全部内置,custom 恒为 false
89
89
  deliveryTemplate: builtinBlock('context'),
90
90
  attachTemplate: builtinBlock('attachment'),
91
- appendMode: settings.appendMode || 'xml',
92
91
  // 每个区块当前生效的模板(全部内置)
93
92
  blockTemplates: Object.fromEntries(PLUGIN_IDS.map((id) => [id, builtinBlock(id)])),
94
93
  // 时机链(#152):get / check / done 各自的插件顺序
@@ -13,7 +13,6 @@ const renderDetach: any = _renderDetach;
13
13
  const input = z.object({
14
14
  ref: z.string(),
15
15
  attachment: z.string().describe("资源 id(见 docs attachments)"),
16
- purge: z.boolean().optional().describe("连资源与字节一起删(仍被引用时拒绝)"),
17
16
  });
18
17
 
19
18
  export class DocsDetachAction extends ActionBase<typeof input> {
@@ -21,7 +20,7 @@ export class DocsDetachAction extends ActionBase<typeof input> {
21
20
  id: 'docs.detach',
22
21
  cli: ['docs', 'detach'],
23
22
  http: ['DELETE', '/api/docs/attach'],
24
- summary: '解除文档与附件的关系(默认只解除关系);--purge 无人引用时连资源行与本机字节一起删',
23
+ summary: '解除文档与附件的关系(#189:只解除关联;清理走库级 GC,不在这里删资源)',
25
24
  args: ['ref'],
26
25
  input,
27
26
  render: renderDetach,
@@ -5,7 +5,6 @@ import { badInput } from '../../core/errors.js';
5
5
  import { getDb } from '../../core/db/index.js';
6
6
  import { tx } from '../../core/db/tx.js';
7
7
  import {
8
- deleteAttachment,
9
8
  ensureDocRef,
10
9
  ensureRefAttachment,
11
10
  ensureTaskAttachment,
@@ -18,10 +17,8 @@ import {
18
17
  upsertFileAttachment,
19
18
  } from '../../core/attachmentdb.js';
20
19
  import type { LinkedAttachmentView } from '../../core/attachmentdb/query.js';
21
- import type { DeleteAttachmentResult } from '../../core/attachmentdb/query.js';
22
20
  import { localUpload } from '../../core/localatt.js';
23
21
  import { contentTypeOf, isImageName } from '../../core/filekind.js';
24
- import { attachmentsRootFromEnv } from '../../core/paths.js';
25
22
  import { readFile } from 'node:fs/promises';
26
23
  import { basename, resolve as resolvePath } from 'node:path';
27
24
 
@@ -232,7 +229,6 @@ export async function attachToDoc(ctx: AttachToDocCtx): Promise<AttachToDocResul
232
229
  export interface DetachFromDocInput {
233
230
  ref?: unknown;
234
231
  attachment?: unknown;
235
- purge?: unknown;
236
232
  }
237
233
 
238
234
  /** docs detach 的出参。 */
@@ -241,36 +237,26 @@ export interface DetachFromDocResult {
241
237
  ref: string;
242
238
  attachment: string;
243
239
  unlinked: number;
244
- purged: boolean;
245
- purgeReason: string;
246
- bytesRemoved: boolean;
247
240
  }
248
241
 
249
- /** 解除文档与资源的关系;--purge 在无人引用时连资源行与本机字节一起删。 */
250
- export async function detachFromDoc({ ref, attachment, purge }: DetachFromDocInput = {}): Promise<DetachFromDocResult> {
242
+ /** 解除文档与资源的关系(#189:**只解除关联**,资源行与字节不动,清理走库级 GC)。 */
243
+ export async function detachFromDoc({ ref, attachment }: DetachFromDocInput = {}): Promise<DetachFromDocResult> {
251
244
  const { refId } = await docRefOf(ref);
252
245
  const attId = String(attachment || '').trim();
253
246
  if (!attId) throw badInput('需要 --attachment <资源 id>(见 docs attachments 输出)');
254
247
  const db = getDb();
255
248
  let unlinked = 0;
256
- const purgeHolder: { result: DeleteAttachmentResult | null } = { result: null };
257
249
  tx(
258
250
  (conn) => {
251
+ // #189:只解除关联——资源行与字节不动,清理由库级 GC 负责
259
252
  unlinked = unlinkAttachment(conn, { host: 'ref', hostId: refId, attachmentId: attId });
260
- if (purge && unlinked) {
261
- purgeHolder.result = deleteAttachment(conn, attId, { attachmentsRoot: attachmentsRootFromEnv() });
262
- }
263
253
  },
264
254
  { db, mode: 'IMMEDIATE' }
265
255
  );
266
- const purgeResult = purgeHolder.result;
267
256
  return {
268
257
  status: 'ok',
269
258
  ref: refId,
270
259
  attachment: attId,
271
260
  unlinked,
272
- purged: !!(purgeResult && purgeResult.removed),
273
- purgeReason: purgeResult ? purgeResult.reason || '' : '',
274
- bytesRemoved: !!(purgeResult && purgeResult.bytesRemoved),
275
261
  };
276
262
  }
@@ -82,16 +82,7 @@ export const renderAttachments = (d: any): string => {
82
82
  export const renderAttach = (d: any): string =>
83
83
  `已附加 ${d.attachmentId}(${d.kind})到「${d.ref}」· ${d.area === 'area' ? '附件区(未写正文)' : '正文内嵌'}${d.markdown ? `\n嵌入: ${d.markdown}` : ''}`;
84
84
 
85
- export const renderDetach = (d: any): string => {
86
- const head = d.unlinked
87
- ? `已解除「${d.ref}」与附件 ${d.attachment} 的关系`
88
- : `「${d.ref}」本来就没有引用附件 ${d.attachment}`;
89
- const tail = d.purged
90
- ? ';资源已删除(含本机字节)'
91
- : d.purgeReason === 'in-use'
92
- ? ';资源仍被其他任务/文档引用,未删字节'
93
- : d.purgeReason === 'file-locked'
94
- ? ';文件被占用,未删字节'
95
- : '';
96
- return head + tail;
97
- };
85
+ export const renderDetach = (d: any): string => (d.unlinked
86
+ // #189:只解除关联——不删资源行与字节(清理走库级 GC)
87
+ ? `已解除「${d.ref}」与附件 ${d.attachment} 的关系(资源留在孤儿池)`
88
+ : `「${d.ref}」本来就没有引用附件 ${d.attachment}`);
@@ -17,6 +17,7 @@ const input = z.object({
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
19
  folder: z.string().optional().describe("本地文件夹路径(kind=folder:只登记目录路径,不复制目录内容;交付给 agent 的是绝对路径)"),
20
+ repo: z.string().optional().describe("#184 参考仓库(kind=repo):已登记仓库的 key / 本地 checkout 路径 / 名称——只登记指针,交付时强制 agent 参考源码"),
20
21
  inline: z.boolean().optional().describe("文档进原文:交付时附全文(截断 2 万字)而不是只给路径;仅 --ref 有效"),
21
22
  name: z.string().optional().describe("显示名 / 本地文件名(默认取原名)"),
22
23
  kind: z.string().optional().describe("image | file(仅 --path/--fileId 用;不给按扩展名判)"),
@@ -30,10 +31,10 @@ export class LocaltaskAttachAction extends ActionBase<typeof input> {
30
31
  id: 'localtask.attach',
31
32
  cli: ['localtask', 'attach'],
32
33
  http: ['POST', '/api/localtasks/attach'],
33
- summary: '给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档)/ --mdfile(本地 md 指针)/ --folder(本地文件夹路径);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文)',
34
+ summary: '给任务挂附件:--path 存本机附件仓 / --fileId 引用已有附件 / --url / --task(同主题任务)/ --ref(文档)/ --mdfile(本地 md 指针)/ --folder(本地文件夹路径)/ --repo(已登记仓库);默认嵌进正文,--no-embed 只挂到附件区(不写正文),--ref 加 --inline 文档进原文(交付带全文)',
34
35
  input,
35
36
  render: (d: any) =>
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}` : ''}`,
37
+ `已附加 ${d.fileId}(${d.kind === 'image' ? '图片' : d.kind === 'url' ? '链接' : d.kind === 'task' ? '任务' : d.kind === 'ref' ? '文档' : d.kind === 'mdfile' ? 'md' : d.kind === 'folder' ? '文件夹' : d.kind === 'repo' ? '仓库' : '文件'})到主题「${d.name}」#${d.task.id} · ${d.role === 'doc' ? '文档资料(交付进原文)' : d.area === 'area' ? '附件区(未写正文)' : '正文内嵌'}${d.markdown ? `\n嵌入: ${d.markdown}` : ''}`,
37
38
  })
38
39
  override async run(ctx: ActionInput<this['_input']>) {
39
40
 
@@ -49,6 +50,7 @@ export class LocaltaskAttachAction extends ActionBase<typeof input> {
49
50
  ref: ctx.ref,
50
51
  mdfile: ctx.mdfile,
51
52
  folder: ctx.folder,
53
+ repo: ctx.repo,
52
54
  inline: ctx.inline,
53
55
  name: ctx.name,
54
56
  kind: ctx.kind,