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
@@ -0,0 +1,261 @@
1
+ // schema v5 → v6 的数据迁移(在 v6.sql 的同一个事务里执行)。
2
+ //
3
+ // 口径(2026-11-12 二轮确认,docs/decisions/2026-11-12-refs-body-in-db.md §11):
4
+ // 1. 存量 refs 归位:相对 locator → rel=locator(origin=import);
5
+ // 空 locator → rel=legacy/<id>;绝对路径 / URL → rel=external/<sha1(规范化)>;
6
+ // 2. 盘上 docs 树 31 篇正文 → ref_bodies,逐篇 sha256 回读比对(硬门禁);
7
+ // 3. 外部绝对路径且文件仍在 → 登记 attachments(kind='mdfile') + ref_attach(role='source');
8
+ // 文件不在 → 只留空壳;
9
+ // 4. 盘上无文件的 102 行保持空壳:不软删、不删行、body_bytes=0;
10
+ // 5. 存量 id 一律保留,不按新公式反推(方案 A)。
11
+ //
12
+ // 幂等:归位是 UPDATE、正文是 UPSERT;重复执行不产生新行。
13
+ // 失败:由 migrator 的 step 事务整体回滚,user_version 停在 5。
14
+ import { createHash } from 'node:crypto';
15
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
16
+ import type { Dirent } from 'node:fs';
17
+ import { basename, isAbsolute, join, resolve } from 'node:path';
18
+ import { refIdFor } from '../../attachmentdb/ids.js';
19
+ import { registerMdfile } from '../../attachmentdb/mdfile.js';
20
+ import type { DbApi } from '../driver.js';
21
+
22
+ /** 迁移上下文(bootstrap 传入,与 v2 同一份)。 */
23
+ export interface V6Context {
24
+ docsDir?: string;
25
+ atMs?: number;
26
+ }
27
+
28
+ /** step 006 的结果(落 meta.refs_v6,供迁移后核对与面板诊断)。 */
29
+ export interface RefsBodiesMigrationResult {
30
+ files: number;
31
+ bodies: number;
32
+ legacy: number;
33
+ external: number;
34
+ emptyBody: number;
35
+ relEmpty: number;
36
+ mdfiles: number;
37
+ sources: number;
38
+ warnings: string[];
39
+ }
40
+
41
+ const MD_RE = /\.(md|markdown)$/i;
42
+ const HTTP_RE = /^https?:\/\//i;
43
+
44
+ const sha1 = (s: unknown): string => createHash('sha1').update(String(s), 'utf8').digest('hex');
45
+ const sha256 = (buf: Buffer): string => createHash('sha256').update(buf).digest('hex');
46
+
47
+ /** 地址统一 POSIX(库里的 rel 永远是正斜杠)。 */
48
+ function toPosix(p: string): string {
49
+ return p.replace(/\\/g, '/');
50
+ }
51
+
52
+ /** 绝对路径规范化:解析 `.`/`..`,Windows 盘符小写(大小写不敏感)。 */
53
+ function normAbs(p: string): string {
54
+ let v = toPosix(resolve(p));
55
+ if (/^[A-Z]:/.test(v)) v = v.charAt(0).toLowerCase() + v.slice(1);
56
+ return v;
57
+ }
58
+
59
+ /** p 是否落在 root 内(Windows 大小写不敏感)。 */
60
+ function within(root: string, p: string): boolean {
61
+ if (!root) return false;
62
+ const norm = (v: string): string => toPosix(resolve(v)).replace(/\/+$/, '').toLowerCase();
63
+ const a = norm(root);
64
+ const b = norm(p);
65
+ return b === a || b.startsWith(a + '/');
66
+ }
67
+
68
+ /** docs 树里的 .md(POSIX 相对路径,排序保证可复现)。 */
69
+ function listMd(root: string): string[] {
70
+ const out: string[] = [];
71
+ if (!root || !existsSync(root)) return out;
72
+ const walk = (dir: string, prefix: string): void => {
73
+ let entries: Dirent[] = [];
74
+ try {
75
+ entries = readdirSync(dir, { withFileTypes: true });
76
+ } catch {
77
+ return;
78
+ }
79
+ for (const e of entries) {
80
+ const p = join(dir, e.name);
81
+ if (e.isDirectory()) walk(p, prefix ? `${prefix}/${e.name}` : e.name);
82
+ else if (MD_RE.test(e.name)) out.push(prefix ? `${prefix}/${e.name}` : e.name);
83
+ }
84
+ };
85
+ walk(root, '');
86
+ return out.map(toPosix).sort();
87
+ }
88
+
89
+ /**
90
+ * step 005 → 006 的 apply。`ctx` 由 bootstrap 传入:{ docsDir, atMs }。
91
+ * @throws 归位失败 / 正文回读 sha256 不符 / 计数不一致 → 整步回滚
92
+ */
93
+ export function migrateRefsBodies(conn: DbApi, { docsDir = '', atMs = Date.now() }: V6Context = {}): RefsBodiesMigrationResult {
94
+ const root = String(docsDir || '');
95
+ const warnings: string[] = [];
96
+ const relOwner = new Map<string, string>();
97
+
98
+ /** 给一条 ref 分配唯一 rel(重复时加序号后缀;绝不覆盖别人的 rel)。 */
99
+ const claim = (base: string, id: string): string => {
100
+ const owner = relOwner.get(base);
101
+ if (!owner || owner === id) {
102
+ relOwner.set(base, id);
103
+ return base;
104
+ }
105
+ for (let n = 2; n < 500; n++) {
106
+ const cand = `${base}-${n}`;
107
+ const cur = relOwner.get(cand);
108
+ if (!cur || cur === id) {
109
+ relOwner.set(cand, id);
110
+ return cand;
111
+ }
112
+ }
113
+ const cand = `${base}-${sha1(id).slice(0, 8)}`;
114
+ relOwner.set(cand, id);
115
+ return cand;
116
+ };
117
+
118
+ // ── 1. 存量 refs 归位 ────────────────────────────────────────────────
119
+ const rows: any[] = conn.all('SELECT id, locator FROM refs ORDER BY id');
120
+ for (const row of rows) {
121
+ const id = String(row.id);
122
+ const raw = String(row.locator ?? '').trim();
123
+ const loc = toPosix(raw);
124
+ let rel: string;
125
+ let origin: string;
126
+ let externalAbs = '';
127
+
128
+ if (!loc) {
129
+ rel = claim(`legacy/${id}`, id);
130
+ origin = 'import';
131
+ } else if (HTTP_RE.test(loc)) {
132
+ rel = claim(`external/${sha1(loc).slice(0, 16)}`, id);
133
+ origin = 'external';
134
+ } else if (isAbsolute(raw) || /^[A-Za-z]:[\\/]/.test(raw) || loc.startsWith('//')) {
135
+ const abs = normAbs(raw);
136
+ if (within(root, abs)) {
137
+ // 绝对路径落在文档树内:文件本身由下面的扫盘统一入库,这一行只留空壳,
138
+ // 避免同一文件出现两条正文。
139
+ rel = claim(`legacy/${id}`, id);
140
+ origin = 'import';
141
+ } else {
142
+ rel = claim(`external/${sha1(abs).slice(0, 16)}`, id);
143
+ origin = 'external';
144
+ externalAbs = abs;
145
+ }
146
+ } else {
147
+ rel = claim(loc, id);
148
+ origin = 'import';
149
+ }
150
+
151
+ conn.run('UPDATE refs SET rel = :rel, origin = :origin WHERE id = :id', { rel, origin, id });
152
+
153
+ if (!externalAbs) continue;
154
+ // 外部文件:仍在 → mdfile 指针 + source 边;不在 → 只留空壳
155
+ if (!MD_RE.test(externalAbs) || !existsSync(externalAbs)) {
156
+ warnings.push(`外部文件不在,只留空壳: ${id} -> ${externalAbs}`);
157
+ continue;
158
+ }
159
+ try {
160
+ const rec = registerMdfile(conn, {
161
+ path: externalAbs,
162
+ name: basename(externalAbs),
163
+ atMs,
164
+ });
165
+ conn.run(
166
+ `INSERT OR IGNORE INTO ref_attach (ref_id, attachment_id, role, position, note, created_at)
167
+ VALUES (:ref, :att, 'source', 0, '', :at)`,
168
+ { ref: id, att: rec.id, at: atMs }
169
+ );
170
+ } catch (e: any) {
171
+ // 登记冲突不阻断迁移:refs 行保留为空壳,原因进 meta 供人工核对。
172
+ warnings.push(`mdfile 登记失败(只留空壳): ${id} -> ${externalAbs}: ${e?.message || e}`);
173
+ }
174
+ }
175
+
176
+ // ── 2. 盘上正文入库 + 硬门禁 ─────────────────────────────────────────
177
+ // 口径(2026-11 收口):这些盘上文件入库后**磁盘那份保留、但不再被读取**——
178
+ // 它们不再是文档来源,只是历史残留(CSV 清单标注「已入库、盘上副本仅留档」)。
179
+ // 不要删它们(迁移不回滚用户文件),也不要再从这里读正文。
180
+ const files = listMd(root);
181
+ let bodies = 0;
182
+ for (const rel of files) {
183
+ const abs = join(root, ...rel.split('/'));
184
+ const buf = readFileSync(abs);
185
+ const body = buf.toString('utf8');
186
+ const hash = sha256(buf);
187
+ const id = relOwner.get(rel) || refIdFor(rel);
188
+
189
+ conn.run(
190
+ `INSERT INTO refs (id, type, rel, locator, origin, state, version, deleted_at, created_at, updated_at)
191
+ VALUES (:id, 'md', :rel, :rel, 'import', 'orphan', 0, NULL, :at, :at)
192
+ ON CONFLICT(id) DO UPDATE SET
193
+ rel = CASE WHEN refs.rel = '' THEN excluded.rel ELSE refs.rel END,
194
+ origin = CASE WHEN refs.origin = 'external' THEN refs.origin ELSE 'import' END`,
195
+ { id, rel, at: atMs }
196
+ );
197
+ relOwner.set(rel, id);
198
+
199
+ conn.run(
200
+ `INSERT INTO ref_bodies (ref_id, body, body_bytes, body_hash, updated_at)
201
+ VALUES (:id, :body, :n, :hash, :at)
202
+ ON CONFLICT(ref_id) DO UPDATE SET
203
+ body = excluded.body,
204
+ body_bytes = excluded.body_bytes,
205
+ body_hash = excluded.body_hash,
206
+ updated_at = excluded.updated_at`,
207
+ { id, body, n: buf.length, hash, at: atMs }
208
+ );
209
+
210
+ // 硬门禁:从库里回读正文,重算 sha256,与盘上文件逐篇比对。
211
+ const saved = conn.get('SELECT body FROM ref_bodies WHERE ref_id = :id', { id });
212
+ const reHash = sha256(Buffer.from(String(saved?.body ?? ''), 'utf8'));
213
+ if (!saved || reHash !== hash) {
214
+ throw new Error(
215
+ `v6 正文校验失败(整步回滚):${rel} 盘上 sha256=${hash} 库内=${reHash}`
216
+ );
217
+ }
218
+
219
+ conn.run('UPDATE refs SET rel = :rel, body_bytes = :n WHERE id = :id', {
220
+ rel,
221
+ n: buf.length,
222
+ id,
223
+ });
224
+ bodies += 1;
225
+ }
226
+
227
+ const count = (sql: string): number => Number(conn.get(sql)?.c || 0);
228
+
229
+ // ── 3. 计数校验(归位不许留空;正文数必须等于盘上文件数) ────────────
230
+ const relEmpty = count("SELECT count(*) AS c FROM refs WHERE rel = '' AND deleted_at IS NULL");
231
+ if (relEmpty > 0) {
232
+ throw new Error(`v6 归位失败(整步回滚):仍有 ${relEmpty} 行 rel 为空`);
233
+ }
234
+ if (bodies !== files.length) {
235
+ throw new Error(`v6 正文入库不完整(整步回滚):盘上 ${files.length} 篇,入库 ${bodies} 篇`);
236
+ }
237
+
238
+ const result: RefsBodiesMigrationResult = {
239
+ files: files.length,
240
+ bodies,
241
+ legacy: count("SELECT count(*) AS c FROM refs WHERE rel LIKE 'legacy/%'"),
242
+ external: count("SELECT count(*) AS c FROM refs WHERE origin = 'external'"),
243
+ emptyBody: count(
244
+ `SELECT count(*) AS c FROM refs r
245
+ LEFT JOIN ref_bodies b ON b.ref_id = r.id
246
+ WHERE r.deleted_at IS NULL AND b.ref_id IS NULL`
247
+ ),
248
+ relEmpty,
249
+ mdfiles: count("SELECT count(*) AS c FROM attachments WHERE kind = 'mdfile' AND deleted_at IS NULL"),
250
+ sources: count("SELECT count(*) AS c FROM ref_attach WHERE role = 'source'"),
251
+ warnings,
252
+ };
253
+
254
+ conn.run(
255
+ `INSERT INTO meta (key, value, updated_at) VALUES ('refs_v6', :v, :at)
256
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`,
257
+ { v: JSON.stringify(result), at: atMs }
258
+ );
259
+
260
+ return result;
261
+ }
@@ -0,0 +1,67 @@
1
+ -- schema v6:refs 从「文档索引」升级为「文档本体」
2
+ --
3
+ -- 设计口径(2026-11-12 二轮确认,docs/decisions/2026-11-12-refs-body-in-db.md §11):
4
+ -- · 正文进 ref_bodies(1:1 挂 refs.id),refs 只留身份与元数据;
5
+ -- · refs 新增 rel(逻辑名,唯一)/ origin / body_bytes;locator 冻结为历史取证列;
6
+ -- · ref_attach 的 role 增 'source':这条 ref 的正文来自某个 mdfile 附件;
7
+ -- · 存量 133 行 id 全部保留(方案 A:ref_<sha1(rel)> 只用于新行)。
8
+ --
9
+ -- refs 用 ALTER 加列、不重建:重建父表会在 DROP 时立刻触发子表
10
+ -- ref_bindings / ref_attach 的 ON DELETE CASCADE(v5 已实测)。
11
+ --
12
+ -- ref_attach 的 CHECK 必须重建表(SQLite 不能 ALTER CHECK)。它没有子表,
13
+ -- 但按同一口径先快照、重建后回填,避免 DROP 期间的外键动作留下空洞。
14
+ --
15
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
16
+ PRAGMA defer_foreign_keys = ON;
17
+
18
+ -- ── refs:身份 + 元数据(正文在 ref_bodies) ────────────────────────────
19
+ ALTER TABLE refs ADD COLUMN rel TEXT NOT NULL DEFAULT '';
20
+ ALTER TABLE refs ADD COLUMN origin TEXT NOT NULL DEFAULT 'own'; -- own | import | external
21
+ ALTER TABLE refs ADD COLUMN body_bytes INTEGER NOT NULL DEFAULT 0;
22
+
23
+ -- rel 是逻辑名,不是路径;空串表示尚未归位(迁移后活动行不再有)
24
+ CREATE UNIQUE INDEX IF NOT EXISTS ux_refs_rel
25
+ ON refs (rel)
26
+ WHERE rel <> '' AND deleted_at IS NULL;
27
+
28
+ -- ── ref_bodies:正文唯一真相 ───────────────────────────────────────────
29
+ CREATE TABLE IF NOT EXISTS ref_bodies (
30
+ ref_id TEXT PRIMARY KEY REFERENCES refs(id) ON DELETE CASCADE,
31
+ body TEXT NOT NULL,
32
+ body_bytes INTEGER NOT NULL CHECK (body_bytes >= 0),
33
+ body_hash TEXT NOT NULL DEFAULT '', -- sha256(body),导入去重与漂移检测
34
+ updated_at INTEGER NOT NULL
35
+ );
36
+
37
+ -- ── ref_attach:role CHECK 增 'source'(关系表快照 → 重建 → 回填) ──────
38
+ CREATE TEMP TABLE _v6_ref_attach AS
39
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM ref_attach;
40
+
41
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
42
+ CREATE TABLE ref_attach_new (
43
+ ref_id TEXT NOT NULL REFERENCES refs(id) ON DELETE CASCADE,
44
+ attachment_id TEXT NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
45
+ role TEXT NOT NULL DEFAULT 'inline'
46
+ CHECK (role IN ('inline', 'attach', 'reference', 'source')),
47
+ position INTEGER NOT NULL DEFAULT 0,
48
+ note TEXT NOT NULL DEFAULT '',
49
+ created_at INTEGER NOT NULL,
50
+ PRIMARY KEY (ref_id, attachment_id)
51
+ );
52
+
53
+ INSERT INTO ref_attach_new (ref_id, attachment_id, role, position, note, created_at)
54
+ SELECT ref_id, attachment_id, role, position, note, created_at FROM _v6_ref_attach;
55
+
56
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
57
+ -- 删除决策:ref_attach 的 role CHECK 需要扩 'source',SQLite 无法 ALTER CHECK,
58
+ -- 只能按快照重建;旧表在回填完成后立即删除,索引随后重建。
59
+ DROP TABLE ref_attach;
60
+ ALTER TABLE ref_attach_new RENAME TO ref_attach;
61
+
62
+ -- v2 的索引原样重建(DROP TABLE 时随表消失)
63
+ CREATE INDEX IF NOT EXISTS ix_ref_attach_att ON ref_attach (attachment_id);
64
+
65
+ -- @decision docs/decisions/2026-11-12-refs-body-in-db.md
66
+ -- 删除决策:TEMP 快照只服务本次重建,回填完成即删(随连接生命周期回收)。
67
+ DROP TABLE _v6_ref_attach;
@@ -14,8 +14,16 @@
14
14
  *
15
15
  * v4(2026-11-09):参考仓库绑定从仓库级升到**组级**(group_refs);组的成员仓库
16
16
  * 共享组上的参考仓库,不做继承/覆盖。旧 ext_linked 绑定由 v4-data.js 搬运。
17
+ *
18
+ * v5(2026-11-12):attachments 重建,新增 kind='mdfile'(本地 md 文件指针)与
19
+ * storage='external';新增 abs_path / anchor_dir / missing_at / last_seen_at 四列
20
+ * 与路径部分唯一索引。纯 DDL 迁移,无数据搬运。
21
+ *
22
+ * v6(2026-11-12):refs 升级为「文档本体」——新增 rel(逻辑名,唯一)/ origin /
23
+ * body_bytes;正文进 ref_bodies(1:1,CASCADE);ref_attach 的 role 增 'source'
24
+ * (外部 md 文件同步来源)。盘上 docs 树正文一次性入库,逐篇 sha256 回读比对。
17
25
  */
18
- export const CURRENT_SCHEMA_VERSION = 4;
26
+ export const CURRENT_SCHEMA_VERSION = 6;
19
27
 
20
28
  /**
21
29
  * 运行时最低 Node 版本。
package/src/core/paths.ts CHANGED
@@ -65,6 +65,16 @@ export function attachmentsRootFromEnv(): string {
65
65
  return process.env.NX_KV_ATTACHMENTS || ATTACHMENTS_DIR;
66
66
  }
67
67
 
68
+ // mdfile 的默认附件目录。
69
+ //
70
+ // **语义(2026-11 硬约束)**:这个目录只用来存放 mdfile 的默认附件,
71
+ // 只能通过 attach 访问;文档正文的唯一真相在 `ref_bodies`,这里不再承载文档。
72
+ // 除 attachment 层与迁移脚本外,任何模块不得直接用 fs 打开这个目录下的文件。
73
+ // 环境变量名 `NX_KV_DOCS_DIR` 保留(用户的既有配置不能因为改名作废)。
74
+ export function mdfileDirFromEnv(appDir: string = APP_DIR): string {
75
+ return process.env.NX_KV_DOCS_DIR || join(appDir, 'docs');
76
+ }
77
+
68
78
  // 名称安全校验:拒绝路径穿越(保留中文等合法命名)。
69
79
  //
70
80
  // 用于「这个字符串会被用作**目录名**」的场景:skill 名、内置包名、适配器 id。
@@ -12,7 +12,10 @@ import { DocAttachAction } from './doc-attach.js';
12
12
  import { DocAttachmentsAction } from './doc-attachments.js';
13
13
  import { DocDetachAction } from './doc-detach.js';
14
14
  import { DocGetAction } from './doc-get.js';
15
+ import { DocLinkFileAction } from './doc-link-file.js';
15
16
  import { DocListAction } from './doc-list.js';
17
+ import { DocMdfileAction } from './doc-mdfile.js';
18
+ import { DocMdfilesAction } from './doc-mdfiles.js';
16
19
  import { DocRemoveAction } from './doc-remove.js';
17
20
  import { DocUpdateAction } from './doc-update.js';
18
21
  import { DocsBindAction } from './docs-bind.js';
@@ -29,7 +32,10 @@ export const ACTIONS: readonly (new (deps: Container) => ActionBase)[] = [
29
32
  DocAttachmentsAction,
30
33
  DocDetachAction,
31
34
  DocGetAction,
35
+ DocLinkFileAction,
32
36
  DocListAction,
37
+ DocMdfileAction,
38
+ DocMdfilesAction,
33
39
  DocRemoveAction,
34
40
  DocUpdateAction,
35
41
  DocsBindAction,
@@ -46,7 +52,10 @@ export { DocAttachAction };
46
52
  export { DocAttachmentsAction };
47
53
  export { DocDetachAction };
48
54
  export { DocGetAction };
55
+ export { DocLinkFileAction };
49
56
  export { DocListAction };
57
+ export { DocMdfileAction };
58
+ export { DocMdfilesAction };
50
59
  export { DocRemoveAction };
51
60
  export { DocUpdateAction };
52
61
  export { DocsBindAction };
@@ -17,6 +17,7 @@ const input = z.object({
17
17
  url: z.string().optional().describe("外部链接(http/https)"),
18
18
  task: z.string().optional().describe("任务全局 id(kind=task)"),
19
19
  doc: z.string().optional().describe("另一篇文档的 ref/path(kind=ref)"),
20
+ mdfile: z.string().optional().describe("本地 .md 文件路径(kind=mdfile:只登记指针,不复制正文)"),
20
21
  name: z.string().optional().describe("显示名(默认取文件名/原名)"),
21
22
  note: z.string().optional().describe("附件区备注"),
22
23
  noEmbed: z.boolean().optional().describe("只写 ref_attach(role=attach),不改正文"),
@@ -28,7 +29,7 @@ export class DocAttachAction extends ActionBase<typeof input> {
28
29
  id: 'doc.attach',
29
30
  cli: ['docs', 'attach'],
30
31
  http: ['POST', '/api/docs/attach'],
31
- summary: '给文档挂资源:--path / --fileId / --url / --task / --doc 之一;默认追加进正文,--no-embed 只挂附件区(不写正文)',
32
+ summary: '给文档挂资源:--path / --fileId / --url / --task / --doc / --mdfile 之一;默认追加进正文,--no-embed 只挂附件区(不写正文)',
32
33
  args: ['ref'],
33
34
  input,
34
35
  render: renderAttach,
@@ -0,0 +1,28 @@
1
+ // doc.link-file —— 登记一个本地 md 文件并挂到文档附件区(不复制正文)。
2
+ import { action } from '../../../runtime/action-decorator.js';
3
+ import { z } from 'zod';
4
+ import { ActionBase, type ActionInput } from '../../../runtime/action-base.js';
5
+ import { attachToDoc } from '../attach.js';
6
+
7
+ const input = z.object({
8
+ ref: z.string(),
9
+ path: z.string().describe('本地 .md 文件的绝对路径(相对路径按当前目录解析)'),
10
+ name: z.string().optional().describe('显示名(默认取文件名)'),
11
+ note: z.string().optional().describe('附件区备注'),
12
+ });
13
+
14
+ export class DocLinkFileAction extends ActionBase<typeof input> {
15
+ @action({
16
+ id: 'doc.link-file',
17
+ cli: ['docs', 'link-file'],
18
+ http: ['POST', '/api/docs/link-file'],
19
+ summary: '把本地 md 文件登记为 mdfile 附件并挂到文档附件区:只存路径指针,不复制正文,不改文档正文',
20
+ args: ['ref'],
21
+ input,
22
+ render: (d: { ref: string; attachmentId: string; name?: string }) =>
23
+ `已登记 mdfile ${d.attachmentId}(${d.name || d.ref})→ 文档 ${d.ref} 的附件区`,
24
+ })
25
+ override async run(ctx: ActionInput<this['_input']>) {
26
+ return attachToDoc({ ref: ctx.ref, mdfile: ctx.path, name: ctx.name, note: ctx.note, noEmbed: true });
27
+ }
28
+ }
@@ -0,0 +1,28 @@
1
+ // doc.mdfile —— 读一个本地 md 文件的正文(读时校验指纹)。
2
+ import { action } from '../../../runtime/action-decorator.js';
3
+ import { z } from 'zod';
4
+ import { ActionBase, type ActionInput } from '../../../runtime/action-base.js';
5
+ import { readDocMdfile } from '../mdfile.js';
6
+
7
+ const input = z.object({
8
+ attachment: z.string().describe('mdfile 的附件 id(见 docs mdfiles)'),
9
+ });
10
+
11
+ export class DocMdfileAction extends ActionBase<typeof input> {
12
+ @action({
13
+ id: 'doc.mdfile',
14
+ cli: ['docs', 'mdfile'],
15
+ http: ['GET', '/api/docs/mdfile'],
16
+ summary: '读本地 md 文件的正文(只读原文件,核对指纹;文件缺失时返回空正文并标 missing)',
17
+ args: ['attachment'],
18
+ input,
19
+ render: (d: { body: string; missing: boolean; stale: boolean; absPath: string }) => {
20
+ if (d.missing) return `(文件不存在: ${d.absPath})`;
21
+ const head = d.stale ? `(内容已变化,以下为磁盘当前内容: ${d.absPath})\n\n` : '';
22
+ return head + (d.body || '(空)');
23
+ },
24
+ })
25
+ override async run(ctx: ActionInput<this['_input']>) {
26
+ return readDocMdfile(ctx);
27
+ }
28
+ }
@@ -0,0 +1,29 @@
1
+ // doc.mdfiles —— 列出已登记的本地 md 文件(kind=mdfile)。
2
+ import { action } from '../../../runtime/action-decorator.js';
3
+ import { z } from 'zod';
4
+ import { ActionBase, type ActionInput } from '../../../runtime/action-base.js';
5
+ import { listDocMdfiles } from '../mdfile.js';
6
+
7
+ const input = z.object({
8
+ missing: z.boolean().optional().describe('只看已失效(missing_at 非空)的行'),
9
+ });
10
+
11
+ export class DocMdfilesAction extends ActionBase<typeof input> {
12
+ @action({
13
+ id: 'doc.mdfiles',
14
+ cli: ['docs', 'mdfiles'],
15
+ http: ['GET', '/api/docs/mdfiles'],
16
+ summary: '列出已登记的本地 md 文件(mdfile 附件;--missing 只看失效行)',
17
+ input,
18
+ render: (rows: Array<{ id: string; name: string; absPath: string; missing: boolean; missingAt: number | null }>) => {
19
+ if (!rows.length) return '没有 mdfile 附件';
20
+ return rows
21
+ .map((r) => `${r.missing ? '!' : '·'} ${r.id} ${r.name} ${r.absPath}` +
22
+ (r.missingAt ? ` (missing since ${new Date(r.missingAt).toISOString()})` : ''))
23
+ .join('\n');
24
+ },
25
+ })
26
+ override async run(ctx: ActionInput<this['_input']>) {
27
+ return listDocMdfiles(ctx);
28
+ }
29
+ }
@@ -13,6 +13,7 @@ import {
13
13
  linkAttachment,
14
14
  listRefAttachments,
15
15
  refIdFor,
16
+ registerMdfile,
16
17
  resolveRefId,
17
18
  unlinkAttachment,
18
19
  updateAttachmentNote,
@@ -86,6 +87,8 @@ export interface AttachToDocCtx {
86
87
  url?: unknown;
87
88
  task?: unknown;
88
89
  doc?: unknown;
90
+ /** 本地 md 文件(登记为 kind=mdfile,不复制正文) */
91
+ mdfile?: unknown;
89
92
  noEmbed?: unknown;
90
93
  note?: unknown;
91
94
  [key: string]: unknown;
@@ -179,10 +182,20 @@ export async function attachToDoc(ctx: AttachToDocCtx): Promise<AttachToDocResul
179
182
  if (!attachmentId) throw badInput(`找不到文档: ${ctx.doc}`);
180
183
  kind = 'ref';
181
184
  markdown = `[${displayName || (target.locator.split('/').pop() ?? '')}](nxkv://ref/${refId})`;
185
+ } else if (ctx.mdfile) {
186
+ // 外部 md 文件:只登记指针(kind=mdfile, storage=external),正文仍在磁盘原地
187
+ const rec = tx(
188
+ (conn) => registerMdfile(conn, { path: ctx.mdfile, name: displayName }),
189
+ { db, mode: 'IMMEDIATE' }
190
+ );
191
+ attachmentId = rec.id;
192
+ displayName = displayName || rec.name;
193
+ kind = 'mdfile';
194
+ markdown = `[${displayName}](nxkv://mdfile/${rec.id})`;
182
195
  }
183
196
 
184
197
  if (!attachmentId) {
185
- throw badInput('需要 --path / --fileId / --url / --task / --doc 之一');
198
+ throw badInput('需要 --path / --fileId / --url / --task / --doc / --mdfile 之一');
186
199
  }
187
200
 
188
201
  const noEmbed = !!(ctx.noEmbed ?? ctx['no-embed']);
@@ -38,6 +38,18 @@ export function assertOwnedRel(rel: unknown, label = '文档路径'): string {
38
38
  return norm;
39
39
  }
40
40
 
41
+ /**
42
+ * 读路径用的 rel 校验:在自有 rel 的基础上,额外放行 v6 的壳行命名空间
43
+ * `legacy/<id>` / `external/<hash>`——它们不是磁盘路径,也不以 .md 结尾,
44
+ * 但必须能被 `docs get` 命中并返回 missing 语义(而不是抛「必须是 .md」)。
45
+ * 写入口仍然用 assertOwnedRel,避免把壳行写成正常文档。
46
+ */
47
+ export function assertDocRel(rel: unknown, label = '文档路径'): string {
48
+ const norm = assertSafeRelPath(rel, { label });
49
+ if (/^(legacy|external)\//.test(norm)) return norm;
50
+ return assertOwnedRel(norm, label);
51
+ }
52
+
41
53
  // ─── DocRef ────────────────────────────────────────────────────────────
42
54
 
43
55
  /** 严格版:形状非法抛 badInput(bind 入口用) */
@@ -105,5 +117,5 @@ export function parseDocId(docId: unknown): ParsedDocId {
105
117
  return { kind: 'external', path: p };
106
118
  }
107
119
  const rel = s.startsWith('rel:') ? s.slice(4).trim() : s;
108
- return { kind: 'own', rel: assertOwnedRel(rel) };
120
+ return { kind: 'own', rel: assertDocRel(rel) };
109
121
  }
@@ -1,14 +1,10 @@
1
- // 复合知识查询:一个仓库的完整上下文,一次取齐。
1
+ // 复合知识查询:一个仓库的完整上下文,一次取齐(agent 领取任务后的供料口)。
2
+ // `repo knowledge --md` 给出项目介绍 + 组介绍 + 组内描述 + 组绑定文档 + 参考仓库文本;
3
+ // 自有文档正文来自库内 `ref_bodies`,不读盘。
2
4
  //
3
- // 这是「get 时封装上下文」的供料口:agent 领到某个仓库的任务后,
4
- // `nx-kv repo knowledge --md` 给出项目介绍 + 所属组介绍 + 组内描述 + 组绑定文档 +
5
- // 参考仓库的单篇文本——文档全是磁盘真实路径,agent 拿到就能直接读盘。
6
- //
7
- // 读取规则:
8
- // - 绑定优先(DocRef),缺省走约定路径;约定路径缺失时惰性播种(字符串字段非空)
9
- // - 外部目录绑定只列文件清单,不进全文(agent 自己读盘——目录全文没有边界)
10
- // - 单文件 256KB 截断:知识是给人/模型读的,不是备份通道
11
- import { join, sep } from 'node:path';
5
+ // 读取规则:绑定优先(DocRef),缺省走约定路径并惰性播种;外部目录只列清单;
6
+ // 单文件 256KB 截断:知识是给人/模型读的,不是备份通道。
7
+ import { sep } from 'node:path';
12
8
  import * as paths from './paths.js';
13
9
  import * as store from './store.js';
14
10
  import { ensureSeedForRel } from './seed.js';
@@ -456,7 +452,7 @@ export interface GroupContextResult {
456
452
  *
457
453
  * 每篇都带两套坐标:
458
454
  * docId 面板导航用('rel:…' 自有树 / 'path:…' 外部绝对路径)
459
- * abs **磁盘绝对路径**——agent 拿到就能直接读盘(交付层用这个)
455
+ * abs 仅外部文档有:磁盘绝对路径(自有文档正文在 DB,没有磁盘副本)
460
456
  *
461
457
  * 为什么描述是「列表」而不是一篇:介绍往往不止主篇——还有架构、问答、规范等补充
462
458
  * 说明。只给一篇,等于让 agent 拿着半张地图干活(#58)。
@@ -482,7 +478,7 @@ export async function readIntroSet({
482
478
  const one = await readOwn(ref.rel, { warnings, label });
483
479
  if (one.missing) return emptyIntroSet();
484
480
  return {
485
- main: { docId: paths.ownDocId(ref.rel), title: one.title, body: one.body, abs: join(paths.docsRoot(), ref.rel) },
481
+ main: { docId: paths.ownDocId(ref.rel), title: one.title, body: one.body },
486
482
  extras: [],
487
483
  count: 1,
488
484
  };
@@ -537,14 +533,13 @@ export async function readIntroSet({
537
533
  docId: paths.ownDocId(d.rel),
538
534
  name: d.name,
539
535
  rel: d.rel,
540
- abs: d.abs || join(paths.docsRoot(), d.rel),
541
536
  isReference: String(d.name || '').toLowerCase().startsWith(paths.DOC_REFERENCE_DIR + '/'),
542
537
  }));
543
538
  if (mainRel && (await store.ownDocExists(mainRel))) {
544
539
  const one = await readOwn(mainRel, { warnings, label });
545
540
  const extras = extrasOf(mainRel);
546
541
  return {
547
- main: { docId: paths.ownDocId(mainRel), title: one.title, body: one.body, abs: join(paths.docsRoot(), mainRel) },
542
+ main: { docId: paths.ownDocId(mainRel), title: one.title, body: one.body },
548
543
  extras,
549
544
  count: 1 + extras.length,
550
545
  };
@@ -554,7 +549,7 @@ export async function readIntroSet({
554
549
  if (!one.missing) {
555
550
  const extras = extrasOf(legacyRel);
556
551
  return {
557
- main: { docId: paths.ownDocId(legacyRel), title: one.title, body: one.body, abs: join(paths.docsRoot(), legacyRel) },
552
+ main: { docId: paths.ownDocId(legacyRel), title: one.title, body: one.body },
558
553
  extras,
559
554
  count: 1 + extras.length,
560
555
  };
@@ -568,7 +563,7 @@ export async function readIntroSet({
568
563
  return {
569
564
  main: first.missing
570
565
  ? null
571
- : { docId: paths.ownDocId(head.rel), title: first.title, body: first.body, abs: head.abs || join(paths.docsRoot(), head.rel) },
566
+ : { docId: paths.ownDocId(head.rel), title: first.title, body: first.body },
572
567
  extras,
573
568
  count: 1 + extras.length,
574
569
  };
@@ -587,7 +582,7 @@ function linkEntries(links: unknown, closure: readonly store.ClosureEntry[]): Kn
587
582
  const out: KnowledgeDoc[] = [];
588
583
  for (const l of Array.isArray(links) ? (links as Array<DocRef & { note?: string; tag?: string }>) : []) {
589
584
  if (l.rel) {
590
- out.push({ rel: l.rel, abs: join(paths.docsRoot(), l.rel), note: l.note || '', ...(l.tag ? { tag: l.tag } : {}) });
585
+ out.push({ rel: l.rel, note: l.note || '', ...(l.tag ? { tag: l.tag } : {}) });
591
586
  continue;
592
587
  }
593
588
  const abs = l.path && store.resolveExternal(l.path, closure);
@@ -604,8 +599,11 @@ function introMdLines(set: IntroSet | null | undefined, fallback: KnowledgeDoc |
604
599
  if (main && main.body) out.push(String(main.body).trim());
605
600
  const extras = (set && set.extras) || [];
606
601
  if (extras.length) {
607
- out.push('', '其余介绍文档(可直接读取):');
608
- for (const d of extras) out.push(`- ${d.abs || d.docId || d.rel || ''}`);
602
+ out.push('', '其余介绍文档(可用命令读取):');
603
+ for (const d of extras) {
604
+ // 自有文档正文在 DB,没有磁盘副本:给可直接执行的读取命令,别给假路径。
605
+ out.push(`- ${d.rel ? `nx-kv docs get rel:${d.rel}` : d.abs || d.docId || ''}`);
606
+ }
609
607
  }
610
608
  return out;
611
609
  }