nx-kv 0.58.0 → 0.60.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 (65) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/assets/nx-kv/references/A03-/346/226/207/346/241/243/344/270/216/345/275/222/345/261/236.md +3 -2
  3. package/assets/nx-kv/references/A04-/344/273/223/345/272/223/344/270/216/351/241/271/347/233/256/347/273/204.md +2 -1
  4. package/assets/nx-kv/references/B02-CLI/351/200/237/346/237/245.md +3 -3
  5. package/package.json +1 -1
  6. package/src/core/attachmentdb/docs.ts +36 -13
  7. package/src/core/config.ts +20 -0
  8. package/src/core/db/import-json/refs.ts +2 -2
  9. package/src/core/db/migrations/index.ts +5 -0
  10. package/src/core/db/migrations/v11-data.ts +36 -0
  11. package/src/core/db/migrations/v11.sql +28 -0
  12. package/src/core/db/migrations/v12.sql +14 -0
  13. package/src/core/db/migrations/v8-data.ts +20 -4
  14. package/src/core/db/version.ts +5 -1
  15. package/src/modules/docs/actions/_manifest.generated.ts +6 -0
  16. package/src/modules/docs/actions/docs-bindings.ts +2 -3
  17. package/src/modules/docs/actions/docs-link.ts +1 -2
  18. package/src/modules/docs/actions/docs-orphans-purge.ts +28 -0
  19. package/src/modules/docs/actions/docs-orphans.ts +27 -0
  20. package/src/modules/docs/brief.ts +0 -2
  21. package/src/modules/docs/docref.ts +8 -7
  22. package/src/modules/docs/knowledge.ts +1 -4
  23. package/src/modules/docs/orphan.ts +389 -0
  24. package/src/modules/docs/ref-sync.ts +1 -5
  25. package/src/modules/docs/refs.ts +66 -8
  26. package/src/modules/docs/render.ts +1 -1
  27. package/src/modules/docs/service.ts +1 -3
  28. package/src/modules/repos/actions/repo-doc-add.ts +1 -2
  29. package/src/modules/repos/actions/repo-doc-list.ts +1 -1
  30. package/src/modules/repos/actions/repo-knowledge.ts +1 -1
  31. package/src/modules/repos/actions/repo-ref-note.ts +4 -4
  32. package/src/modules/repos/boards/core.ts +0 -3
  33. package/src/modules/repos/{link-note.ts → ref-note-doc.ts} +53 -29
  34. package/src/modules/repos/ref.ts +8 -36
  35. package/src/modules/repos/transfer/export.ts +3 -3
  36. package/src/modules/repos/transfer/layout.ts +3 -3
  37. package/src/modules/setting/actions/setting-set.ts +1 -0
  38. package/src/modules/setting/service.ts +13 -1
  39. package/src/modules/tasktool/delivery-template.ts +3 -4
  40. package/src/runtime/cli.ts +9 -0
  41. package/src/web/frontend/api/cli-tree.json +34 -2
  42. package/src/web/frontend/api/client.generated.ts +30 -7
  43. package/src/web/frontend/components/Introduction/use-intro.ts +2 -4
  44. package/src/web/frontend/modules/refs/api.ts +0 -1
  45. package/src/web/frontend/page/repos/index.tsx +1 -1
  46. package/src/web/frontend/page/settings/api.ts +10 -0
  47. package/src/web/frontend/page/settings/index.tsx +163 -1
  48. package/src/web/frontend/page/settings/style.css +26 -0
  49. package/src/web/frontend/refs/api.ts +0 -1
  50. package/src/web/public/assets/{composer-panel-D73-SjHP.js → composer-panel-BhT_eFic.js} +1 -1
  51. package/src/web/public/assets/{dir-DOlFdrrg.js → dir-1w7D_lg7.js} +1 -1
  52. package/src/web/public/assets/{doc-CKkCGsZ4.js → doc-Dn4-viog.js} +1 -1
  53. package/src/web/public/assets/{group-C3N5tBVQ.js → group-BsvhgO5r.js} +1 -1
  54. package/src/web/public/assets/{index-Ca-l9oTn.js → index-CBVkXanT.js} +2 -2
  55. package/src/web/public/assets/{refs-DvvwZmdl.js → refs-BHzLZnJn.js} +1 -1
  56. package/src/web/public/assets/{repo-form-modal-pyqiC7pB.js → repo-form-modal-BafSPVlv.js} +1 -1
  57. package/src/web/public/assets/{repos-CeyrjSQ_.js → repos-CmlsSN0h.js} +2 -2
  58. package/src/web/public/assets/settings-C_Dkc9gQ.js +8 -0
  59. package/src/web/public/assets/settings-ZgyeQVU1.css +1 -0
  60. package/src/web/public/assets/{task-Czd6vy99.js → task-Ci94al50.js} +1 -1
  61. package/src/web/public/assets/{templates-bCiyBvPJ.js → templates-Dc5Pln-Q.js} +1 -1
  62. package/src/web/public/index.html +3 -3
  63. package/src/modules/docs/link-note.ts +0 -171
  64. package/src/web/public/assets/settings-Bopc08A2.css +0 -1
  65. package/src/web/public/assets/settings-Bt1Uzf7g.js +0 -8
@@ -9,12 +9,15 @@
9
9
  // 实际位置在 refs.locator;宿主只认 refId。
10
10
  import { badInput } from '../../core/errors.js';
11
11
 
12
- /** DocRef:{ ref } 指向文档库条目;note/tag 是列表条目的注解(docLinks 用)。 */
12
+ /**
13
+ * DocRef:{ ref } 指向文档库条目;note 是列表条目的注解(docLinks 用)。
14
+ *
15
+ * #137 之前还有 `tag`(分类标签)——面板没有入口、无处可用,已在 v12 整个删掉。
16
+ */
13
17
  export interface DocRef {
14
18
  ref?: string;
15
- /** 链接级注解(note/tag,docLinks 条目用) */
19
+ /** 链接级注解(note,docLinks 条目用) */
16
20
  note?: string;
17
- tag?: string;
18
21
  }
19
22
 
20
23
  /** DocRef + 链接级注解(withLinkMeta 的产出形状)。 */
@@ -50,18 +53,16 @@ export function sanitizeDocRef(raw: unknown): DocRef | null {
50
53
  }
51
54
 
52
55
  /**
53
- * DocRef + 链接级注解(note/tag)合成列表条目。
56
+ * DocRef + 链接级注解(note)合成列表条目。
54
57
  *
55
58
  * 注解要过三道关(写入口合并 / 读归一化回贴 / 导出保留),三处口径必须一致——
56
59
  * 实现只此一份,docs/refs 与 repos/service、transfer 都从这里拿。
57
60
  * 空串/缺省 = 不落字段(对已有条目即「清掉」)。
58
61
  */
59
- export function withLinkMeta(ref: DocRef, raw: { note?: unknown; tag?: unknown } = {}): DocRefWithMeta {
62
+ export function withLinkMeta(ref: DocRef, raw: { note?: unknown } = {}): DocRefWithMeta {
60
63
  const note = typeof raw.note === 'string' ? raw.note.trim() : '';
61
- const tag = typeof raw.tag === 'string' ? raw.tag.trim() : '';
62
64
  const entry: DocRefWithMeta = { ...ref };
63
65
  if (note) entry.note = note;
64
- if (tag) entry.tag = tag;
65
66
  return entry;
66
67
  }
67
68
 
@@ -23,7 +23,6 @@ export interface KnowledgeDoc {
23
23
  name?: string;
24
24
  path?: string;
25
25
  note?: string;
26
- tag?: string;
27
26
  missing?: boolean;
28
27
  dir?: boolean;
29
28
  files?: string[];
@@ -146,7 +145,7 @@ async function readRefDocs(raw: DocRef | null | undefined, opts: ReadOpts): Prom
146
145
  }
147
146
  return docs;
148
147
  }
149
- return [{ ...one, refId, note: String((raw && raw.note) || ''), tag: String((raw && raw.tag) || '') }];
148
+ return [{ ...one, refId, note: String((raw && raw.note) || '') }];
150
149
  }
151
150
  if (!row.hasBody) {
152
151
  return [{
@@ -155,14 +154,12 @@ async function readRefDocs(raw: DocRef | null | undefined, opts: ReadOpts): Prom
155
154
  docId: 'ref:' + refId,
156
155
  title: row.desc,
157
156
  note: String((raw && raw.note) || ''),
158
- tag: String((raw && raw.tag) || ''),
159
157
  }];
160
158
  }
161
159
  return [{
162
160
  ...docOut('ref:' + refId, row.body ?? '', opts),
163
161
  refId,
164
162
  note: String((raw && raw.note) || ''),
165
- tag: String((raw && raw.tag) || ''),
166
163
  }];
167
164
  }
168
165
 
@@ -0,0 +1,389 @@
1
+ // 孤儿文档(无任何 ref_bindings 归属的 ref)的判定、预演与到期清理。
2
+ //
3
+ // 口径(2026-11-15 用户拍板):
4
+ // · 孤儿 = `deleted_at IS NULL` 且 ref_bindings 里没有任何一行的 ref;
5
+ // · 失绑起算时间落 refs.orphan_since(0 = 未计时);由绑变无绑时写入,
6
+ // 已在计时中的孤儿在重建索引时不刷新(否则倒计时永远重置);
7
+ // · 到期清理**只软删** refs 行(deleted_at),ref_bodies 保留;
8
+ // · **只清空正文孤儿**。有正文的到期孤儿只进清单(skippedWithBody),
9
+ // 不静默删——正文是用户资产,人工处置走 `docs delete`;
10
+ // · 每次清理在 ref_gc_log 留一条不可变记录,删除后可按 ref / 时间回查。
11
+ import { getDb } from '../../core/db/index.js';
12
+ import { tx } from '../../core/db/tx.js';
13
+ import { nowMs } from '../../core/db/time.js';
14
+ import { loadConfig, DEFAULT_ORPHAN_TTL_DAYS } from '../../core/config.js';
15
+
16
+ export const DAY_MS = 24 * 60 * 60 * 1000;
17
+ /** 「即将到期」窗口:剩余不超过 1 天。 */
18
+ export const DUE_SOON_MS = DAY_MS;
19
+ const TTL_MIN_DAYS = 1;
20
+ const TTL_MAX_DAYS = 3650;
21
+
22
+ /** 一条孤儿 ref 的展示 / 判定行。 */
23
+ export interface OrphanRefRow {
24
+ refId: string;
25
+ desc: string;
26
+ origin: string;
27
+ locator: string;
28
+ /** 失绑起算时刻;null = 未计时(下次例行维护起算) */
29
+ unboundAt: number | null;
30
+ ageMs: number;
31
+ remainingMs: number;
32
+ /** 剩余天数(保留 1 位小数;已到期为负数) */
33
+ remainingDays: number;
34
+ due: boolean;
35
+ hasBody: boolean;
36
+ bodyBytes: number;
37
+ }
38
+
39
+ /** ref_gc_log 的一行(删除留痕)。 */
40
+ export interface RefGcLogRow {
41
+ refId: string;
42
+ desc: string;
43
+ origin: string;
44
+ bodyBytes: number;
45
+ unboundAt: number;
46
+ deletedAt: number;
47
+ ttlDays: number;
48
+ reason: string;
49
+ source: string;
50
+ }
51
+
52
+ /** 只读清单。 */
53
+ export interface OrphanListResult {
54
+ status: string;
55
+ ttlDays: number;
56
+ now: number;
57
+ total: number;
58
+ /** 到期总数(含只列清单、不自动删的有正文孤儿) */
59
+ due: number;
60
+ /** 到期且空正文:会被/已被清理 */
61
+ dueEmpty: number;
62
+ /** 到期但有正文:只列清单,需人工处置 */
63
+ dueWithBody: number;
64
+ /** 24 小时内到期(尚未到期) */
65
+ dueSoon: number;
66
+ /** 尚未起算的孤儿(orphan_since = 0) */
67
+ untimed: number;
68
+ orphans: OrphanRefRow[];
69
+ recentDeletions: RefGcLogRow[];
70
+ }
71
+
72
+ /** 预演 / 执行结果。 */
73
+ export interface OrphanSweepResult extends OrphanListResult {
74
+ dryRun: boolean;
75
+ /** 本次会被软删 / 已软删的 refId(只含空正文到期孤儿) */
76
+ eligible: string[];
77
+ deleted: RefGcLogRow[];
78
+ skippedWithBody: OrphanRefRow[];
79
+ }
80
+
81
+ function resolveTtlDays(raw: unknown, fallback?: number): number {
82
+ const n = Math.trunc(Number(raw));
83
+ if (Number.isFinite(n) && n >= TTL_MIN_DAYS && n <= TTL_MAX_DAYS) return n;
84
+ const f = Math.trunc(Number(fallback));
85
+ if (Number.isFinite(f) && f >= TTL_MIN_DAYS && f <= TTL_MAX_DAYS) return f;
86
+ return DEFAULT_ORPHAN_TTL_DAYS;
87
+ }
88
+
89
+ async function ttlDaysOf(raw?: unknown): Promise<number> {
90
+ if (raw !== undefined && raw !== null && String(raw).trim() !== '') return resolveTtlDays(raw);
91
+ const cfg = await loadConfig();
92
+ return resolveTtlDays(cfg.orphanTtlDays, DEFAULT_ORPHAN_TTL_DAYS);
93
+ }
94
+
95
+ /** 把失绑 / 复绑漂移修回(写;只在清理动作里调用)。 */
96
+ function normalizeOrphanClocks(conn: any, at: number): void {
97
+ // 有归属却还留着计时 → 清掉
98
+ conn.run(
99
+ `UPDATE refs SET state = '', orphan_since = 0, updated_at = :at
100
+ WHERE deleted_at IS NULL AND orphan_since <> 0
101
+ AND id IN (SELECT ref_id FROM ref_bindings)`,
102
+ { at }
103
+ );
104
+ // 无归属、未计时 → 从当前时刻起算(不刷新已在计时中的孤儿)
105
+ conn.run(
106
+ `UPDATE refs SET state = 'orphan', orphan_since = :at, updated_at = :at
107
+ WHERE deleted_at IS NULL AND orphan_since = 0
108
+ AND id NOT IN (SELECT ref_id FROM ref_bindings)`,
109
+ { at }
110
+ );
111
+ // 无归属但 state 残留 → 归位(不动计时)
112
+ conn.run(
113
+ `UPDATE refs SET state = 'orphan', updated_at = :at
114
+ WHERE deleted_at IS NULL AND state <> 'orphan'
115
+ AND id NOT IN (SELECT ref_id FROM ref_bindings)`,
116
+ { at }
117
+ );
118
+ }
119
+
120
+ function readOrphanRows(conn: any, ttlDays: number, at: number): OrphanRefRow[] {
121
+ const rows: any[] = conn.all(
122
+ `SELECT r.id, r."desc" AS desc, r.origin, r.locator, r.orphan_since,
123
+ CASE WHEN rb.ref_id IS NOT NULL AND trim(COALESCE(rb.body, '')) <> '' THEN 1 ELSE 0 END AS has_body,
124
+ CASE WHEN rb.ref_id IS NULL THEN 0 ELSE COALESCE(rb.body_bytes, 0) END AS body_bytes
125
+ FROM refs r
126
+ LEFT JOIN ref_bodies rb ON rb.ref_id = r.id
127
+ WHERE r.deleted_at IS NULL
128
+ AND NOT EXISTS (SELECT 1 FROM ref_bindings b WHERE b.ref_id = r.id)
129
+ ORDER BY (r.orphan_since = 0), r.orphan_since, r.id`
130
+ );
131
+ const ttlMs = ttlDays * DAY_MS;
132
+ return rows.map((r) => {
133
+ const since = Number(r.orphan_since) || 0;
134
+ const unboundAt = since > 0 ? since : null;
135
+ const ageMs = unboundAt === null ? 0 : Math.max(0, at - unboundAt);
136
+ const remainingMs = unboundAt === null ? ttlMs : ttlMs - ageMs;
137
+ return {
138
+ refId: String(r.id),
139
+ desc: String(r.desc || ''),
140
+ origin: String(r.origin || ''),
141
+ locator: String(r.locator || ''),
142
+ unboundAt,
143
+ ageMs,
144
+ remainingMs,
145
+ remainingDays: Math.round((remainingMs / DAY_MS) * 10) / 10,
146
+ due: unboundAt !== null && remainingMs <= 0,
147
+ hasBody: Number(r.has_body) === 1,
148
+ bodyBytes: Number(r.body_bytes) || 0,
149
+ };
150
+ });
151
+ }
152
+
153
+ function readRecentDeletions(conn: any, limit = 20): RefGcLogRow[] {
154
+ const rows: any[] = conn.all(
155
+ `SELECT ref_id, ref_desc, origin, body_bytes, unbound_at, deleted_at, ttl_days, reason, source
156
+ FROM ref_gc_log ORDER BY deleted_at DESC, id DESC LIMIT :limit`,
157
+ { limit }
158
+ );
159
+ return rows.map((r) => ({
160
+ refId: String(r.ref_id || ''),
161
+ desc: String(r.ref_desc || ''),
162
+ origin: String(r.origin || ''),
163
+ bodyBytes: Number(r.body_bytes) || 0,
164
+ unboundAt: Number(r.unbound_at) || 0,
165
+ deletedAt: Number(r.deleted_at) || 0,
166
+ ttlDays: Number(r.ttl_days) || 0,
167
+ reason: String(r.reason || ''),
168
+ source: String(r.source || ''),
169
+ }));
170
+ }
171
+
172
+ function summarize(rows: OrphanRefRow[], ttlDays: number, at: number, recent: RefGcLogRow[]): OrphanListResult {
173
+ const dueRows = rows.filter((r) => r.due);
174
+ return {
175
+ status: 'ok',
176
+ ttlDays,
177
+ now: at,
178
+ total: rows.length,
179
+ due: dueRows.length,
180
+ dueEmpty: dueRows.filter((r) => !r.hasBody).length,
181
+ dueWithBody: dueRows.filter((r) => r.hasBody).length,
182
+ dueSoon: rows.filter((r) => !r.due && r.unboundAt !== null && r.remainingMs <= DUE_SOON_MS).length,
183
+ untimed: rows.filter((r) => r.unboundAt === null).length,
184
+ orphans: rows,
185
+ recentDeletions: recent,
186
+ };
187
+ }
188
+
189
+ /** 只读:孤儿清单(失绑时间 / 剩余天数 / 是否到期 / 是否有正文)+ 最近清理留痕。 */
190
+ export async function listOrphans({
191
+ ttlDays,
192
+ now = nowMs(),
193
+ }: { ttlDays?: unknown; now?: number } = {}): Promise<OrphanListResult> {
194
+ const days = await ttlDaysOf(ttlDays);
195
+ const conn = getDb();
196
+ const rows = readOrphanRows(conn, days, now);
197
+ return summarize(rows, days, now, readRecentDeletions(conn));
198
+ }
199
+
200
+ /**
201
+ * 预演 / 执行到期清理。
202
+ * 默认只预演;`apply=true` 才软删空正文且到期的孤儿。
203
+ */
204
+ export async function sweepOrphans({
205
+ apply = false,
206
+ ttlDays,
207
+ now = nowMs(),
208
+ source = 'cli',
209
+ }: {
210
+ apply?: boolean;
211
+ ttlDays?: unknown;
212
+ now?: number;
213
+ source?: 'cli' | 'serve';
214
+ } = {}): Promise<OrphanSweepResult> {
215
+ const days = await ttlDaysOf(ttlDays);
216
+ const db = getDb();
217
+
218
+ if (apply) {
219
+ tx((conn) => normalizeOrphanClocks(conn, now), { db, mode: 'IMMEDIATE' });
220
+ }
221
+
222
+ const rows = readOrphanRows(db, days, now);
223
+ const base = summarize(rows, days, now, readRecentDeletions(db));
224
+ const skippedWithBody = rows.filter((r) => r.due && r.hasBody);
225
+ const candidates = rows.filter((r) => r.due && !r.hasBody);
226
+ const eligible = candidates.map((r) => r.refId);
227
+
228
+ if (!apply) {
229
+ return { ...base, dryRun: true, eligible, deleted: [], skippedWithBody };
230
+ }
231
+
232
+ const deleted: RefGcLogRow[] = [];
233
+ if (candidates.length) {
234
+ tx(
235
+ (conn) => {
236
+ for (const c of candidates) {
237
+ // 事务内复核:仍无归属、仍空正文、仍到期才删(并发复绑时跳过)
238
+ const cur: any = conn.get(
239
+ `SELECT r.id, r."desc" AS desc, r.origin, r.locator, r.orphan_since,
240
+ CASE WHEN rb.ref_id IS NOT NULL AND trim(COALESCE(rb.body, '')) <> '' THEN 1 ELSE 0 END AS has_body,
241
+ CASE WHEN rb.ref_id IS NULL THEN 0 ELSE COALESCE(rb.body_bytes, 0) END AS body_bytes
242
+ FROM refs r
243
+ LEFT JOIN ref_bodies rb ON rb.ref_id = r.id
244
+ WHERE r.id = :id AND r.deleted_at IS NULL
245
+ AND NOT EXISTS (SELECT 1 FROM ref_bindings b WHERE b.ref_id = r.id)`,
246
+ { id: c.refId }
247
+ );
248
+ if (!cur || Number(cur.has_body) === 1) continue;
249
+ const since = Number(cur.orphan_since) || 0;
250
+ if (!since || now - since < days * DAY_MS) continue;
251
+
252
+ const row: RefGcLogRow = {
253
+ refId: String(cur.id),
254
+ desc: String(cur.desc || ''),
255
+ origin: String(cur.origin || ''),
256
+ bodyBytes: Number(cur.body_bytes) || 0,
257
+ unboundAt: since,
258
+ deletedAt: now,
259
+ ttlDays: days,
260
+ reason: 'orphan-ttl-expired',
261
+ source,
262
+ };
263
+ conn.run(
264
+ `INSERT INTO ref_gc_log
265
+ (ref_id, ref_desc, origin, body_bytes, unbound_at, deleted_at, ttl_days, reason, source, snapshot, created_at)
266
+ VALUES
267
+ (:ref, :desc, :origin, :bytes, :unbound, :deleted, :ttl, :reason, :source, :snapshot, :at)`,
268
+ {
269
+ ref: row.refId,
270
+ desc: row.desc,
271
+ origin: row.origin,
272
+ bytes: row.bodyBytes,
273
+ unbound: row.unboundAt,
274
+ deleted: row.deletedAt,
275
+ ttl: row.ttlDays,
276
+ reason: row.reason,
277
+ source: row.source,
278
+ snapshot: JSON.stringify({ ...row, locator: String(cur.locator || '') }),
279
+ at: now,
280
+ }
281
+ );
282
+ const r = conn.run(
283
+ `UPDATE refs SET deleted_at = :at, updated_at = :at
284
+ WHERE id = :id AND deleted_at IS NULL`,
285
+ { at: now, id: row.refId }
286
+ );
287
+ if (Number(r.changes) > 0) deleted.push(row);
288
+ }
289
+ },
290
+ { db, mode: 'IMMEDIATE' }
291
+ );
292
+ }
293
+
294
+ const after = readOrphanRows(db, days, now);
295
+ return {
296
+ ...summarize(after, days, now, readRecentDeletions(db)),
297
+ dryRun: false,
298
+ eligible,
299
+ deleted,
300
+ skippedWithBody,
301
+ };
302
+ }
303
+
304
+ /**
305
+ * serve 的例行维护:启动后延迟跑一次,此后每 intervalMs 一次。
306
+ * 定时器 `unref()`,不阻塞进程退出;上一轮未结束时跳过本轮。
307
+ */
308
+ export function startOrphanGcTimer({
309
+ intervalMs = 60 * 60 * 1000,
310
+ initialDelayMs = 10 * 1000,
311
+ }: { intervalMs?: number; initialDelayMs?: number } = {}): () => void {
312
+ let stopped = false;
313
+ let running = false;
314
+ const tick = async (): Promise<void> => {
315
+ if (stopped || running) return;
316
+ running = true;
317
+ try {
318
+ const r = await sweepOrphans({ apply: true, source: 'serve' });
319
+ if (r.deleted.length) {
320
+ console.log(
321
+ `[孤儿文档] 已清理 ${r.deleted.length} 篇空壳(TTL ${r.ttlDays} 天)` +
322
+ (r.skippedWithBody.length ? `;跳过有正文 ${r.skippedWithBody.length} 篇,待人工处置` : '')
323
+ );
324
+ }
325
+ } catch (e) {
326
+ console.error('[孤儿文档] 例行维护失败: ' + String((e as Error)?.message || e));
327
+ } finally {
328
+ running = false;
329
+ }
330
+ };
331
+ const first = setTimeout(() => void tick(), initialDelayMs);
332
+ const timer = setInterval(() => void tick(), intervalMs);
333
+ first.unref?.();
334
+ timer.unref?.();
335
+ return () => {
336
+ stopped = true;
337
+ clearTimeout(first);
338
+ clearInterval(timer);
339
+ };
340
+ }
341
+
342
+ /** 人读时间(本地时区,精确到分钟)。 */
343
+ export function formatAt(ms: number | null): string {
344
+ if (!ms) return '—';
345
+ const d = new Date(ms);
346
+ const p = (n: number): string => String(n).padStart(2, '0');
347
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
348
+ }
349
+
350
+ /** CLI 渲染:清单 / 预演 / 执行共用。 */
351
+ export function renderOrphans(d: OrphanListResult | OrphanSweepResult): string {
352
+ const dryRun = 'dryRun' in d ? d.dryRun : true;
353
+ const lines: string[] = [
354
+ `孤儿文档(无归属 ref):${d.total} 篇 · TTL ${d.ttlDays} 天` +
355
+ ` · 到期 ${d.due}(空壳 ${d.dueEmpty} / 有正文 ${d.dueWithBody})` +
356
+ (d.dueSoon ? ` · 24h 内到期 ${d.dueSoon}` : '') +
357
+ (d.untimed ? ` · 未计时 ${d.untimed}` : ''),
358
+ ];
359
+ for (const o of d.orphans) {
360
+ const state = o.due ? '已到期' : o.unboundAt === null ? '未计时' : `剩 ${o.remainingDays} 天`;
361
+ lines.push(
362
+ ` ${o.refId} ${state} 失绑 ${formatAt(o.unboundAt)} ` +
363
+ (o.hasBody ? `有正文 ${o.bodyBytes}B` : '空壳') +
364
+ (o.desc ? ` ${o.desc}` : '') +
365
+ (o.origin === 'external' && o.locator ? ` ${o.locator}` : '')
366
+ );
367
+ }
368
+ const skippedWithBody = 'skippedWithBody' in d ? d.skippedWithBody : [];
369
+ if (skippedWithBody.length) {
370
+ lines.push(`跳过(有正文,不自动删;人工处置走 docs delete <refId>):`);
371
+ for (const o of skippedWithBody) {
372
+ lines.push(` ${o.refId} ${formatAt(o.unboundAt)} ${o.bodyBytes}B ${o.desc}`.trimEnd());
373
+ }
374
+ }
375
+ if ('deleted' in d) {
376
+ lines.push(
377
+ dryRun
378
+ ? `预演:将软删 ${d.eligible.length} 篇空壳(未落盘;加 --apply 执行)`
379
+ : `已软删 ${d.deleted.length} 篇空壳(ref_bodies 保留,可在 ref_gc_log 回查)`
380
+ );
381
+ }
382
+ if (d.recentDeletions.length) {
383
+ lines.push('最近清理:');
384
+ for (const r of d.recentDeletions) {
385
+ lines.push(` ${formatAt(r.deletedAt)} ${r.refId} ${r.reason} TTL ${r.ttlDays} 天 ${r.desc}`.trimEnd());
386
+ }
387
+ }
388
+ return lines.join('\n');
389
+ }
@@ -22,7 +22,6 @@ interface DesiredBinding {
22
22
  refId: string;
23
23
  position: number;
24
24
  note: string;
25
- tag: string;
26
25
  }
27
26
 
28
27
  export interface SyncRefIndexInput {
@@ -45,8 +44,7 @@ export function desiredBindings(s: any): DesiredBinding[] {
45
44
  type: DesiredBinding['type'],
46
45
  raw: any,
47
46
  position: number,
48
- note = '',
49
- tag = ''
47
+ note = ''
50
48
  ): void => {
51
49
  const refId = String((raw && raw.ref) || '').trim();
52
50
  if (!refId) return;
@@ -57,7 +55,6 @@ export function desiredBindings(s: any): DesiredBinding[] {
57
55
  refId,
58
56
  position: Number(position) || 0,
59
57
  note: String((raw && raw.note) ?? note ?? ''),
60
- tag: String((raw && raw.tag) ?? tag ?? ''),
61
58
  });
62
59
  };
63
60
 
@@ -115,7 +112,6 @@ export async function syncRefIndex({ store: s }: SyncRefIndexInput = {}): Promis
115
112
  type: b.type,
116
113
  position: b.position,
117
114
  note: b.note,
118
- tag: b.tag,
119
115
  });
120
116
  markRefBound(conn, b.refId);
121
117
  n += 1;
@@ -139,7 +139,6 @@ export interface SetDocLinkInput {
139
139
  ref?: string;
140
140
  path?: string;
141
141
  note?: string;
142
- tag?: string;
143
142
  remove?: number;
144
143
  before?: number;
145
144
  }
@@ -147,13 +146,13 @@ export interface SetDocLinkInput {
147
146
  /**
148
147
  * 维护组的 docLinks。
149
148
  * --ref <refId> 或 --path <绝对路径>(外部只读)
150
- * note / tag 条目注解
149
+ * note 条目注解
151
150
  * remove --remove <序号>(1 起)
152
151
  * before --before <序号>(插到该条之前;缺省追加)
153
152
  *
154
- * 同 ref 重复添加 = 更新该条(note/tag 以本次为准)。
153
+ * 同 ref 重复添加 = 更新该条(note 以本次为准)。
155
154
  */
156
- export async function setDocLink({ board, ref, path, note, tag, remove, before }: SetDocLinkInput = {}): Promise<any> {
155
+ export async function setDocLink({ board, ref, path, note, remove, before }: SetDocLinkInput = {}): Promise<any> {
157
156
  if (!board) throw badInput('缺少看板(id / key / 名称)');
158
157
  const { mutateStore, boardKeyOf } = await reposBridge();
159
158
  const docRef = remove === undefined ? await docRefOf({ ref, path }) : null;
@@ -175,8 +174,8 @@ export async function setDocLink({ board, ref, path, note, tag, remove, before }
175
174
  return { boardName: b.name, removed: describeLink(gone), count: b.docLinks.length };
176
175
  }
177
176
 
178
- // 条目 = DocRef + 注解(note/tag);合成逻辑收在 docref.withLinkMeta
179
- const entry = withLinkMeta(docRef!, { note, tag });
177
+ // 条目 = DocRef + 注解(note);合成逻辑收在 docref.withLinkMeta
178
+ const entry = withLinkMeta(docRef!, { note });
180
179
  const at = b.docLinks.findIndex((x: any) => (x && x.ref) === entry.ref);
181
180
  if (at >= 0) b.docLinks.splice(at, 1);
182
181
  const want = before !== undefined ? idxOf(before) : -1;
@@ -222,7 +221,6 @@ export interface AddRepoDocInput {
222
221
  ref?: string;
223
222
  path?: string;
224
223
  note?: string;
225
- tag?: string;
226
224
  }
227
225
 
228
226
  /** 往项目的介绍文档集里加一篇(同 ref 重复添加 = 更新注解)。 */
@@ -231,7 +229,7 @@ export async function addRepoDoc(locator: string, raw: unknown): Promise<any> {
231
229
  const repo = await getRepo(locator);
232
230
  const input = (raw && typeof raw === 'object' ? raw : {}) as AddRepoDocInput;
233
231
  const docRef = await docRefOf({ ref: input.ref, path: input.path });
234
- const entry = withLinkMeta(docRef, { note: input.note, tag: input.tag });
232
+ const entry = withLinkMeta(docRef, { note: input.note });
235
233
  const res = await mutateStore((s: any) => {
236
234
  const r = s.repos.find((x: any) => deriveKey(x) === deriveKey(repo));
237
235
  if (!r) throw notFound('repo 不存在: ' + locator);
@@ -246,6 +244,66 @@ export async function addRepoDoc(locator: string, raw: unknown): Promise<any> {
246
244
  return res;
247
245
  }
248
246
 
247
+ /**
248
+ * 「建一篇文档并挂到某个仓库上」——关系描述的落点(#137)。
249
+ *
250
+ * 定位口径:**desc 就在 ref 上**——同一个 desc 的那篇就是它;
251
+ * 找到了就改(正文 + desc),没找到就新建一篇并挂到该仓库的文档列表。
252
+ */
253
+ export async function setDocLinkDoc({ repoKey, desc, body }: {
254
+ repoKey: string;
255
+ desc: string;
256
+ body?: string;
257
+ }): Promise<{ refId: string; desc: string; created: boolean }> {
258
+ const { getRepo, deriveKey, mutateStore } = await reposBridge();
259
+ const repo = await getRepo(repoKey);
260
+ const key = deriveKey(repo);
261
+ const label = String(desc || '').trim();
262
+ const text = String(body ?? '');
263
+
264
+ // ① 找同 desc 的那篇(该仓库的文档集里)
265
+ const s = await (await reposBridge()).loadStore();
266
+ const r = s.repos.find((x: any) => deriveKey(x) === key);
267
+ const ids: string[] = [];
268
+ if (r && r.doc && r.doc.ref) ids.push(String(r.doc.ref));
269
+ for (const l of (r && Array.isArray(r.docLinks) ? r.docLinks : [])) {
270
+ if (l && l.ref) ids.push(String(l.ref));
271
+ }
272
+ let hit = '';
273
+ for (const id of ids) {
274
+ const row = getDb().get(`SELECT "desc" AS desc FROM refs WHERE id = :id AND deleted_at IS NULL`, { id });
275
+ if (row && String(row.desc || '') === label) { hit = id; break; }
276
+ }
277
+
278
+ if (hit) {
279
+ // ② 改:正文 + desc(同一篇,不新增)
280
+ const { writeOwnDoc, setOwnDocDesc } = await import('./store.js');
281
+ await writeOwnDoc(hit, text);
282
+ await setOwnDocDesc(hit, label);
283
+ return { refId: hit, desc: label, created: false };
284
+ }
285
+
286
+ // ③ 建:新建一篇自有文档(空正文也落行)+ 挂到仓库文档集
287
+ const { createRef } = await import('./service.js');
288
+ const made = await createRef({ desc: label, owner: 'repo', repo: key });
289
+ const { writeOwnDoc } = await import('./store.js');
290
+ await writeOwnDoc(made.refId, text);
291
+ // createRef 会把它挂成**主篇**(仓库没有主篇时);关系描述是「又一篇」,
292
+ // 应当是附加篇 —— 把主篇位还回去(本来就是空的),改挂 docLinks。
293
+ await mutateStore((draft: any) => {
294
+ const dr = draft.repos.find((x: any) => deriveKey(x) === key);
295
+ if (!dr) return;
296
+ if (dr.doc && dr.doc.ref === made.refId) {
297
+ delete dr.doc;
298
+ if (!Array.isArray(dr.docLinks)) dr.docLinks = [];
299
+ dr.docLinks.push({ ref: made.refId });
300
+ }
301
+ dr.updatedAt = new Date().toISOString();
302
+ });
303
+ await syncRefIndex();
304
+ return { refId: made.refId, desc: label, created: true };
305
+ }
306
+
249
307
  /** 从项目的介绍文档集里摘掉一篇(--index 从 1 起;1 = 主篇) */
250
308
  export async function removeRepoDoc(locator: string, index: unknown): Promise<any> {
251
309
  const { getRepo, deriveKey, mutateStore } = await reposBridge();
@@ -60,7 +60,7 @@ export const renderLink = (d: any): string => {
60
60
  if (d.removed !== undefined) return `已移除组绑定: ${d.removed}(剩 ${d.count} 条)`;
61
61
  const lines = [`「${d.boardName}」的组绑定(${d.count} 条):`];
62
62
  for (const l of d.links) {
63
- lines.push(` ref:${l.ref}${l.tag ? ` [${l.tag}]` : ''}${l.note ? ` · ${l.note}` : ''}`);
63
+ lines.push(` ref:${l.ref}${l.note ? ` · ${l.note}` : ''}`);
64
64
  }
65
65
  return lines.join('\n');
66
66
  };
@@ -82,7 +82,6 @@ export interface RefBindingView {
82
82
  groupKey: string | null;
83
83
  position: number;
84
84
  note: string;
85
- tag: string;
86
85
  main: boolean;
87
86
  }
88
87
 
@@ -198,7 +197,7 @@ function bindingsOfRef(refId: string): RefBindingView[] {
198
197
  if (!clean(refId)) return [];
199
198
  return getDb()
200
199
  .all(
201
- `SELECT type, repo_key AS repoKey, group_key AS groupKey, position, note, tag
200
+ `SELECT type, repo_key AS repoKey, group_key AS groupKey, position, note
202
201
  FROM ref_bindings WHERE ref_id = :id ORDER BY type, position`,
203
202
  { id: refId }
204
203
  )
@@ -208,7 +207,6 @@ function bindingsOfRef(refId: string): RefBindingView[] {
208
207
  groupKey: r.groupKey == null ? null : String(r.groupKey),
209
208
  position: Number(r.position) || 0,
210
209
  note: String(r.note || ''),
211
- tag: String(r.tag || ''),
212
210
  main: (Number(r.position) || 0) === 0,
213
211
  }));
214
212
  }
@@ -13,7 +13,6 @@ const input = z.object({
13
13
  ref: z.string().optional().describe("文档 refId(ref_<16hex>)"),
14
14
  path: z.string().optional().describe("外部绝对路径(登记成 origin=external 的 ref)"),
15
15
  note: z.string().optional().describe("这篇的说明"),
16
- tag: z.string().optional().describe("分类标签(如 qa;简介行渲染成小 chip;空串 = 清掉)"),
17
16
  });
18
17
 
19
18
  export class RepoDocAddAction extends ActionBase<typeof input> {
@@ -28,7 +27,7 @@ export class RepoDocAddAction extends ActionBase<typeof input> {
28
27
  })
29
28
  override async run(ctx: ActionInput<this['_input']>) {
30
29
 
31
- return addRepoDoc(ctx.id, { ref: ctx.ref, path: ctx.path, note: ctx.note, tag: ctx.tag });
30
+ return addRepoDoc(ctx.id, { ref: ctx.ref, path: ctx.path, note: ctx.note });
32
31
 
33
32
  }
34
33
  }
@@ -21,7 +21,7 @@ export class RepoDocListAction extends ActionBase<typeof input> {
21
21
  args: ['id'],
22
22
  input,
23
23
  render: (d: any) => {
24
- const one: any = (x: any, i: any) => ` ${i}. ${x.title || x.desc || x.ref}${x.tag ? ` [${x.tag}]` : ''}${x.note ? ` # ${x.note}` : ''}${x.missing ? ' (缺正文)' : ''}`;
24
+ const one: any = (x: any, i: any) => ` ${i}. ${x.title || x.desc || x.ref}${x.note ? ` # ${x.note}` : ''}${x.missing ? ' (缺正文)' : ''}`;
25
25
  const lines: any = [`【${d.repo.name}】介绍文档 ${d.count} 篇`];
26
26
  // 描述是**列表**:主篇 + 登记的补充(#58)
27
27
  let n: any = 0;
@@ -30,7 +30,7 @@ export class RepoKnowledgeAction extends ActionBase<typeof input> {
30
30
  lines.push(` ◇ 组「${b.name}」`);
31
31
  if (b.intro && !b.intro.missing) lines.push(` 组介绍: ${b.intro.docId}`);
32
32
  if (b.note && !b.note.missing) lines.push(` 组内描述: ${b.note.docId}`);
33
- for (const l of b.docLinks) lines.push(` 绑定: ${l.docId}${l.tag ? ` [${l.tag}]` : ''}${l.note ? ` · ${l.note}` : ''}${l.missing ? '(缺失)' : ''}`);
33
+ for (const l of b.docLinks) lines.push(` 绑定: ${l.docId}${l.note ? ` · ${l.note}` : ''}${l.missing ? '(缺失)' : ''}`);
34
34
  for (const x of b.externalDirs) lines.push(` 外部目录: ${x.path}(${x.files.length} 个文档,按需读盘)`);
35
35
  }
36
36
  if (d.refRepos.length) {