nx-kv 0.57.2 → 0.59.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.
- package/CHANGELOG.md +54 -0
- package/assets/nx-kv/references/A03-/346/226/207/346/241/243/344/270/216/345/275/222/345/261/236.md +22 -0
- package/package.json +1 -1
- package/src/core/attachmentdb/docs.ts +33 -8
- package/src/core/config.ts +20 -0
- package/src/core/db/migrations/index.ts +3 -0
- package/src/core/db/migrations/v11-data.ts +36 -0
- package/src/core/db/migrations/v11.sql +28 -0
- package/src/core/db/seed-templates.ts +89 -149
- package/src/core/db/version.ts +3 -1
- package/src/modules/docs/actions/_manifest.generated.ts +6 -0
- package/src/modules/docs/actions/docs-orphans-purge.ts +28 -0
- package/src/modules/docs/actions/docs-orphans.ts +27 -0
- package/src/modules/docs/orphan.ts +389 -0
- package/src/modules/setting/actions/setting-set.ts +1 -0
- package/src/modules/setting/service.ts +13 -1
- package/src/modules/templates/service.ts +10 -6
- package/src/runtime/cli.ts +9 -0
- package/src/web/frontend/api/cli-tree.json +32 -0
- package/src/web/frontend/api/client.generated.ts +26 -3
- package/src/web/frontend/modules/md/md-parse.ts +4 -24
- package/src/web/frontend/modules/md/use-templates.ts +3 -4
- package/src/web/frontend/page/dir/index.tsx +1 -2
- package/src/web/frontend/page/group/index.tsx +2 -2
- package/src/web/frontend/page/settings/api.ts +10 -0
- package/src/web/frontend/page/settings/index.tsx +163 -1
- package/src/web/frontend/page/settings/style.css +26 -0
- package/src/web/public/assets/{composer-panel-qX7uVyLW.js → composer-panel-MB_2m-jI.js} +1 -1
- package/src/web/public/assets/{dag-BzD3ZlnO.js → dag-ChYvtJCy.js} +1 -1
- package/src/web/public/assets/dir-BQZAPk92.js +3 -0
- package/src/web/public/assets/group-CXDiKp4X.js +1 -0
- package/src/web/public/assets/index-Dmlh01et.js +2 -0
- package/src/web/public/assets/md-parse-BE6EWfZ1.js +2 -0
- package/src/web/public/assets/{overview-DfrlYtyR.js → overview-DwCaowBF.js} +1 -1
- package/src/web/public/assets/{progress-BsodHm4N.js → progress-C7BIqnCG.js} +1 -1
- package/src/web/public/assets/settings-KNodW2wX.js +8 -0
- package/src/web/public/assets/settings-ZgyeQVU1.css +1 -0
- package/src/web/public/assets/{task-XXG4USTn.js → task-DJF54sKp.js} +1 -1
- package/src/web/public/assets/{templates-C9a5CUFd.js → templates-BaX3bQsl.js} +1 -1
- package/src/web/public/index.html +1 -2
- package/src/web/public/assets/dir-B360Miyq.js +0 -3
- package/src/web/public/assets/group-CCcRCEjR.js +0 -1
- package/src/web/public/assets/index-BLrw-ZQc.js +0 -2
- package/src/web/public/assets/md-parse-uaOFbIcA.js +0 -13
- package/src/web/public/assets/settings-Bopc08A2.css +0 -1
- package/src/web/public/assets/settings-DhX_fRMm.js +0 -8
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// docs.orphans —— 只读列出「没有任何归属(ref_bindings)」的孤儿文档。
|
|
2
|
+
//
|
|
3
|
+
// 给「谁要到期、还差多久」一个可核对的窗口:失绑时间、剩余天数、是否到期、
|
|
4
|
+
// 是否有正文(有正文的到期孤儿不会自动清,必须能单独看见)。
|
|
5
|
+
import { action } from '../../../runtime/action-decorator.js';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { ActionBase, type ActionInput } from '../../../runtime/action-base.js';
|
|
8
|
+
import { listOrphans, renderOrphans } from '../orphan.js';
|
|
9
|
+
|
|
10
|
+
/** docs.orphans 的入参契约(CLI 与 HTTP 共用)。 */
|
|
11
|
+
const input = z.object({
|
|
12
|
+
ttlDays: z.number().int().min(1).max(3650).optional().describe('按指定保留天数额外算一遍(不落库;缺省读设置)'),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export class DocsOrphansAction extends ActionBase<typeof input> {
|
|
16
|
+
@action({
|
|
17
|
+
id: 'docs.orphans',
|
|
18
|
+
cli: ['docs', 'orphans'],
|
|
19
|
+
http: ['GET', '/api/docs/orphans'],
|
|
20
|
+
summary: '列出无归属的孤儿文档(失绑时间 / 剩余天数 / 是否有正文;只读)',
|
|
21
|
+
input,
|
|
22
|
+
render: renderOrphans,
|
|
23
|
+
})
|
|
24
|
+
override async run(ctx: ActionInput<this['_input']>) {
|
|
25
|
+
return listOrphans({ ttlDays: ctx.ttlDays });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -11,6 +11,7 @@ const service: any = serviceNs;
|
|
|
11
11
|
const input = z.object({
|
|
12
12
|
gitRepoRoot: z.string().optional().describe("参考仓库存储根目录(非 C 盘;空 = clone 参考仓库被拒绝)"),
|
|
13
13
|
gitDevRoot: z.string().optional().describe("导入布局时开发仓库的默认克隆根(空 = 只登记不克隆)"),
|
|
14
|
+
orphanTtlDays: z.number().int().min(1).max(3650).optional().describe("无归属 ref 的保留天数(默认 3;到期由例行维护软删空壳)"),
|
|
14
15
|
});
|
|
15
16
|
|
|
16
17
|
export class SettingSetAction extends ActionBase<typeof input> {
|
|
@@ -16,6 +16,8 @@ export interface SettingsView {
|
|
|
16
16
|
resolvedDir: string;
|
|
17
17
|
gitRepoRoot: string;
|
|
18
18
|
gitDevRoot: string;
|
|
19
|
+
/** 无归属 ref 的保留天数(到期清理;默认 3) */
|
|
20
|
+
orphanTtlDays: number;
|
|
19
21
|
}
|
|
20
22
|
|
|
21
23
|
export async function getSettings(): Promise<SettingsView> {
|
|
@@ -27,19 +29,28 @@ export async function getSettings(): Promise<SettingsView> {
|
|
|
27
29
|
// 参考仓库(type=ref)的存储根;空 = clone 会被拒绝,直到用户显式设置
|
|
28
30
|
gitRepoRoot: cfg.gitRepoRoot,
|
|
29
31
|
gitDevRoot: cfg.gitDevRoot,
|
|
32
|
+
orphanTtlDays: cfg.orphanTtlDays,
|
|
30
33
|
};
|
|
31
34
|
}
|
|
32
35
|
|
|
33
36
|
export async function setSettings(patch: {
|
|
34
37
|
gitRepoRoot?: unknown;
|
|
35
38
|
gitDevRoot?: unknown;
|
|
39
|
+
orphanTtlDays?: unknown;
|
|
36
40
|
} = {}): Promise<SettingsView> {
|
|
37
41
|
const body: Record<string, unknown> = {};
|
|
38
42
|
if (patch.gitRepoRoot !== undefined) body.gitRepoRoot = String(patch.gitRepoRoot || '').trim();
|
|
39
43
|
if (patch.gitDevRoot !== undefined) body.gitDevRoot = String(patch.gitDevRoot || '').trim();
|
|
44
|
+
if (patch.orphanTtlDays !== undefined) {
|
|
45
|
+
const n = Math.trunc(Number(patch.orphanTtlDays));
|
|
46
|
+
if (!Number.isFinite(n) || n < 1 || n > 3650) {
|
|
47
|
+
throw badInput('孤儿文档保留天数必须是 1–3650 的整数');
|
|
48
|
+
}
|
|
49
|
+
body.orphanTtlDays = n;
|
|
50
|
+
}
|
|
40
51
|
if (!Object.keys(body).length) {
|
|
41
52
|
throw badInput(
|
|
42
|
-
'没有要改的设置:--gitRepoRoot <参考仓库根目录> / --gitDevRoot <开发仓库克隆根>'
|
|
53
|
+
'没有要改的设置:--gitRepoRoot <参考仓库根目录> / --gitDevRoot <开发仓库克隆根> / --orphanTtlDays <天数>'
|
|
43
54
|
);
|
|
44
55
|
}
|
|
45
56
|
await saveConfig({ ...(await loadConfig()), ...body });
|
|
@@ -52,5 +63,6 @@ export function renderSettings(d: SettingsView): string {
|
|
|
52
63
|
`(附件根目录 ${d.attachmentsRoot})`,
|
|
53
64
|
`参考仓库存储根: ${d.gitRepoRoot || '(未设置 —— clone 参考仓库前先 nx-kv setting set --gitRepoRoot <非C盘目录>)'}`,
|
|
54
65
|
`开发仓库克隆根: ${d.gitDevRoot || '(未设置 —— 导入布局时开发仓库只登记不克隆)'}`,
|
|
66
|
+
`孤儿文档保留: ${d.orphanTtlDays} 天(无归属 ref 到期后软删;有正文的不自动删)`,
|
|
55
67
|
].filter(Boolean).join('\n');
|
|
56
68
|
}
|
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
// 内置模板(`builtin=1`,由 core/db/seed-templates 在开库时 INSERT OR IGNORE
|
|
8
8
|
// seed,永远在场):**不可删,可编辑**。T06 起骨架也可改 —— 用户改了
|
|
9
9
|
// builtin 的 body / 槽位后重启原样保留(seed 是 OR IGNORE,绝不覆盖用户编辑)。
|
|
10
|
-
//
|
|
11
|
-
//
|
|
10
|
+
// #137:出厂正文只有**一份**(core/db/seed-templates 的 NEWTASK_REF_BODY,
|
|
11
|
+
// 即新建任务模板「ref 生成」);前端不再自带第二份副本(漂移的根源)。
|
|
12
12
|
//
|
|
13
13
|
// ── 与 schema 列的映射 ────────────────────────────────────────────────
|
|
14
14
|
// 旧 JSON 字段 → 列
|
|
@@ -31,7 +31,7 @@ import fsp from 'node:fs/promises'; // 仅用于读用户 --body-file(存储
|
|
|
31
31
|
import { readFileSync } from 'node:fs';
|
|
32
32
|
import { badInput, notFound } from '../../core/errors.js';
|
|
33
33
|
import { nowMs } from '../../core/db/time.js';
|
|
34
|
-
import {
|
|
34
|
+
import { NEWTASK_REF_BODY } from '../../core/db/seed-templates.js';
|
|
35
35
|
import { normalizeScope, topicCtx, canUse, canEdit } from './scope.js';
|
|
36
36
|
import repoLayer from './repo/index.js';
|
|
37
37
|
|
|
@@ -59,13 +59,17 @@ export interface TemplateListResult {
|
|
|
59
59
|
repo?: string;
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
// #137:新建任务的内置模板只剩一条「ref 生成」(id=newtask.ref)。
|
|
63
|
+
// 旧的 'default'(默认模板)已下线(软删),不再作为内置默认的落点。
|
|
64
|
+
export const BUILTIN_ID = 'newtask.ref';
|
|
63
65
|
const NEWTASK_CATEGORY = 'newtask';
|
|
64
66
|
|
|
65
67
|
const repo = repoLayer;
|
|
66
68
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
+
// #137:内置只有一份出厂文本(新建任务模板「ref 生成」)。空正文兜底用它,
|
|
70
|
+
// 槽位默认值不再需要(出厂文本里没有 {{槽位}} 标记)。
|
|
71
|
+
export const BUILTIN_BODY = NEWTASK_REF_BODY;
|
|
72
|
+
export const BUILTIN_VALUES: Record<string, string> = {};
|
|
69
73
|
|
|
70
74
|
// ─── 视图:行 ⇄ 旧 JSON 形状(调用方消费的是 values/builtin 这些旧字段)──
|
|
71
75
|
|
package/src/runtime/cli.ts
CHANGED
|
@@ -431,6 +431,15 @@ async function cmdServe(ctx: ServeCtx): Promise<void> {
|
|
|
431
431
|
};
|
|
432
432
|
process.on('exit', unregister);
|
|
433
433
|
|
|
434
|
+
// 孤儿文档例行维护:启动后延迟跑一次,此后每小时一次。
|
|
435
|
+
// 只软删空正文且到期的孤儿;有正文的只列清单(不静默删)。失败不影响面板。
|
|
436
|
+
try {
|
|
437
|
+
const { startOrphanGcTimer } = await import('../modules/docs/orphan.js');
|
|
438
|
+
startOrphanGcTimer();
|
|
439
|
+
} catch {
|
|
440
|
+
/* 计时器启动失败不影响 serve 本体 */
|
|
441
|
+
}
|
|
442
|
+
|
|
434
443
|
console.log('nx-kv · nx-kv v' + VERSION);
|
|
435
444
|
console.log(`面板: ${addr}`);
|
|
436
445
|
console.log('CLI: nx-kv help(每个按钮都有对应命令,agent 可加 --json)');
|
|
@@ -1112,6 +1112,38 @@
|
|
|
1112
1112
|
"http": null
|
|
1113
1113
|
},
|
|
1114
1114
|
"children": []
|
|
1115
|
+
},
|
|
1116
|
+
{
|
|
1117
|
+
"name": "orphans",
|
|
1118
|
+
"path": [
|
|
1119
|
+
"docs",
|
|
1120
|
+
"orphans"
|
|
1121
|
+
],
|
|
1122
|
+
"action": {
|
|
1123
|
+
"id": "docs.orphans",
|
|
1124
|
+
"module": "docs",
|
|
1125
|
+
"summary": "列出无归属的孤儿文档(失绑时间 / 剩余天数 / 是否有正文;只读)",
|
|
1126
|
+
"usage": "docs orphans",
|
|
1127
|
+
"http": "GET /api/docs/orphans"
|
|
1128
|
+
},
|
|
1129
|
+
"children": [
|
|
1130
|
+
{
|
|
1131
|
+
"name": "purge",
|
|
1132
|
+
"path": [
|
|
1133
|
+
"docs",
|
|
1134
|
+
"orphans",
|
|
1135
|
+
"purge"
|
|
1136
|
+
],
|
|
1137
|
+
"action": {
|
|
1138
|
+
"id": "docs.orphans.purge",
|
|
1139
|
+
"module": "docs",
|
|
1140
|
+
"summary": "孤儿到期清理(默认只预演;--apply 软删空正文到期孤儿,有正文的只列清单)",
|
|
1141
|
+
"usage": "docs orphans purge",
|
|
1142
|
+
"http": "POST /api/docs/orphans/purge"
|
|
1143
|
+
},
|
|
1144
|
+
"children": []
|
|
1145
|
+
}
|
|
1146
|
+
]
|
|
1115
1147
|
}
|
|
1116
1148
|
]
|
|
1117
1149
|
},
|
|
@@ -30,6 +30,8 @@ import type {
|
|
|
30
30
|
DocsGcAction,
|
|
31
31
|
DocsIndexAction,
|
|
32
32
|
DocsLinkAction,
|
|
33
|
+
DocsOrphansAction,
|
|
34
|
+
DocsOrphansPurgeAction,
|
|
33
35
|
} from '../../../modules/docs/actions/_manifest.generated.js';
|
|
34
36
|
import type {
|
|
35
37
|
FileContentAction,
|
|
@@ -281,6 +283,10 @@ export interface ApiClient {
|
|
|
281
283
|
index(): Promise<Awaited<ReturnType<InstanceType<typeof DocsIndexAction>['run']>>>;
|
|
282
284
|
/** 维护组的附加文档列表(--ref <refId> | --path <外部路径> + --note/--tag;--remove <序号> 移除;--before <序号> 插位;同 ref 重复添加 = 更新) */
|
|
283
285
|
link(input: z.input<InstanceType<typeof DocsLinkAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocsLinkAction>['run']>>>;
|
|
286
|
+
/** 孤儿到期清理(默认只预演;--apply 软删空正文到期孤儿,有正文的只列清单) */
|
|
287
|
+
purge(input?: z.input<InstanceType<typeof DocsOrphansPurgeAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocsOrphansPurgeAction>['run']>>>;
|
|
288
|
+
/** 列出无归属的孤儿文档(失绑时间 / 剩余天数 / 是否有正文;只读) */
|
|
289
|
+
orphans(input?: z.input<InstanceType<typeof DocsOrphansAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof DocsOrphansAction>['run']>>>;
|
|
284
290
|
/** 向某主题(工作目录)的队列回填一条任务(正文可多行;--file <文件|-> 从文件/标准输入读,长文本不必靠引号硬拼;有 wait 在等则即时投递,否则排队);--global 推到全局共享池;--duration 给任务带时间目标(领取即计时,完成前必须 check);--board/--project 让任务带工作组语义(正文 frontmatter:board + project + 双方介绍引用),并落进该项目的队列;正文自带 frontmatter 时同样认归属——补介绍引用,落点跟到项目队列(显式给过 --cwd 时不挪窝) */
|
|
285
291
|
localtaskAdd(input?: z.input<InstanceType<typeof LocaltaskAddAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof LocaltaskAddAction>['run']>>>;
|
|
286
292
|
/** 改一条附件绑定的说明(desc):--attachment <资源 id> --note <说明>(只动说明,角色/位置不变) */
|
|
@@ -378,7 +384,7 @@ export interface ApiClient {
|
|
|
378
384
|
/** 查单个附件的元数据与本机路径 */
|
|
379
385
|
fileGet(input: z.input<InstanceType<typeof FileGetAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof FileGetAction>['run']>>>;
|
|
380
386
|
/** 列出无主资源(没有任何任务/文档关系边;删任务、删文档、删正文行之后用) */
|
|
381
|
-
|
|
387
|
+
fileOrphans(): Promise<Awaited<ReturnType<InstanceType<typeof FileOrphansAction>['run']>>>;
|
|
382
388
|
/** 回收无主资源(DB 行 + 附件根目录内的本机/镜像字节;仍被引用的不删) */
|
|
383
389
|
filePrune(input?: z.input<InstanceType<typeof FilePruneAction>['_input']>): Promise<Awaited<ReturnType<InstanceType<typeof FilePruneAction>['run']>>>;
|
|
384
390
|
/** 上传附件到本机附件仓(不碰网;本地任务/文档贴图用) */
|
|
@@ -419,7 +425,7 @@ export function createApiClient(transport: Transport): ApiClient {
|
|
|
419
425
|
async set(input?: z.input<InstanceType<typeof SettingSetAction>['_input']>) {
|
|
420
426
|
const inp = input ?? ({} as z.input<InstanceType<typeof SettingSetAction>['_input']>);
|
|
421
427
|
const path = `/api/setting`;
|
|
422
|
-
const body = { "gitRepoRoot": inp["gitRepoRoot"], "gitDevRoot": inp["gitDevRoot"] };
|
|
428
|
+
const body = { "gitRepoRoot": inp["gitRepoRoot"], "gitDevRoot": inp["gitDevRoot"], "orphanTtlDays": inp["orphanTtlDays"] };
|
|
423
429
|
return (await transport.request("POST", path, body)) as Awaited<ReturnType<InstanceType<typeof SettingSetAction>['run']>>;
|
|
424
430
|
},
|
|
425
431
|
// action: board.add
|
|
@@ -877,6 +883,23 @@ export function createApiClient(transport: Transport): ApiClient {
|
|
|
877
883
|
const body = { "board": inp["board"], "ref": inp["ref"], "path": inp["path"], "note": inp["note"], "tag": inp["tag"], "remove": inp["remove"], "before": inp["before"] };
|
|
878
884
|
return (await transport.request("POST", path, body)) as Awaited<ReturnType<InstanceType<typeof DocsLinkAction>['run']>>;
|
|
879
885
|
},
|
|
886
|
+
// action: docs.orphans.purge
|
|
887
|
+
async purge(input?: z.input<InstanceType<typeof DocsOrphansPurgeAction>['_input']>) {
|
|
888
|
+
const inp = input ?? ({} as z.input<InstanceType<typeof DocsOrphansPurgeAction>['_input']>);
|
|
889
|
+
const path = `/api/docs/orphans/purge`;
|
|
890
|
+
const body = { "apply": inp["apply"], "ttlDays": inp["ttlDays"] };
|
|
891
|
+
return (await transport.request("POST", path, body)) as Awaited<ReturnType<InstanceType<typeof DocsOrphansPurgeAction>['run']>>;
|
|
892
|
+
},
|
|
893
|
+
// action: docs.orphans
|
|
894
|
+
async orphans(input?: z.input<InstanceType<typeof DocsOrphansAction>['_input']>) {
|
|
895
|
+
const inp = input ?? ({} as z.input<InstanceType<typeof DocsOrphansAction>['_input']>);
|
|
896
|
+
let path = `/api/docs/orphans`;
|
|
897
|
+
const q = new URLSearchParams();
|
|
898
|
+
if (inp["ttlDays"] !== undefined) q.set("ttlDays", String(inp["ttlDays"]));
|
|
899
|
+
const query = q.toString();
|
|
900
|
+
if (query) path += path.includes('?') ? '&' + query : '?' + query;
|
|
901
|
+
return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof DocsOrphansAction>['run']>>;
|
|
902
|
+
},
|
|
880
903
|
// action: localtask.add
|
|
881
904
|
async localtaskAdd(input?: z.input<InstanceType<typeof LocaltaskAddAction>['_input']>) {
|
|
882
905
|
const inp = input ?? ({} as z.input<InstanceType<typeof LocaltaskAddAction>['_input']>);
|
|
@@ -1258,7 +1281,7 @@ export function createApiClient(transport: Transport): ApiClient {
|
|
|
1258
1281
|
return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof FileGetAction>['run']>>;
|
|
1259
1282
|
},
|
|
1260
1283
|
// action: file.orphans
|
|
1261
|
-
async
|
|
1284
|
+
async fileOrphans() {
|
|
1262
1285
|
const path = `/api/file/orphans`;
|
|
1263
1286
|
return (await transport.request("GET", path)) as Awaited<ReturnType<InstanceType<typeof FileOrphansAction>['run']>>;
|
|
1264
1287
|
},
|