dsh-plugin-tool-management 0.22.5 → 0.22.7
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 +1652 -1415
- package/README.md +192 -177
- package/README_EN.md +192 -177
- package/docs/ARCHITECTURE.md +137 -134
- package/docs/COMPATIBILITY.md +112 -107
- package/docs/TROUBLESHOOTING.md +287 -285
- package/lib/client.js +15176 -12341
- package/lib/compat/capability-specs.js +66 -16
- package/lib/compat/host-contracts.js +11 -2
- package/lib/compat/host-roots.js +1 -1
- package/lib/compat/manual-review.js +1 -1
- package/lib/compat/preset-reach.js +1 -1
- package/lib/compat/probe.js +107 -22
- package/lib/confirm-gate.js +40 -6
- package/lib/context-inject-contract.js +31 -14
- package/lib/context-inject-delta.js +146 -0
- package/lib/context-inject-frame.js +41 -20
- package/lib/context-inject-select.js +33 -4
- package/lib/context-inject-surface.js +30 -10
- package/lib/context-inject.js +106 -14
- package/lib/evolution/cold.js +389 -0
- package/lib/evolution/config.js +498 -0
- package/lib/evolution/digest.js +48 -0
- package/lib/evolution/episodes.js +287 -0
- package/lib/evolution/evidence.js +167 -0
- package/lib/evolution/gates.js +883 -0
- package/lib/evolution/limits.js +21 -0
- package/lib/evolution/maintenance.js +544 -0
- package/lib/evolution/notes.js +328 -0
- package/lib/evolution/organize.js +118 -0
- package/lib/evolution/review.js +524 -0
- package/lib/evolution/route.js +91 -0
- package/lib/evolution/runtime.js +178 -0
- package/lib/evolution/scope-card.js +144 -0
- package/lib/evolution/state.js +540 -0
- package/lib/evolution/write.js +1855 -0
- package/lib/index.js +1437 -57
- package/lib/legacy-tool-names.js +19 -4
- package/lib/mcp/tool-visibility.js +127 -10
- package/lib/memories/catalog.js +226 -0
- package/lib/memories/constants.js +137 -8
- package/lib/memories/discovery.js +59 -25
- package/lib/memories/projection.js +116 -31
- package/lib/memories/render-auto.js +199 -0
- package/lib/memories/search.js +3 -5
- package/lib/memories/service.js +168 -17
- package/lib/memories/snapshot.js +176 -24
- package/lib/op-registry.js +59 -0
- package/lib/ops/compat.js +6 -2
- package/lib/ops/evolution.js +896 -0
- package/lib/ops/memory.js +95 -72
- package/lib/ops/trash.js +14 -2
- package/lib/prompts/service.js +4 -1
- package/lib/scenes/candidates.js +5 -1
- package/lib/scope/workspace-key.js +39 -0
- package/lib/settings-sidecars.js +2 -2
- package/lib/skills/official.js +180 -36
- package/lib/subagents/run-provider.js +35 -22
- package/lib/text-width.js +65 -0
- package/lib/tool-table-switch.js +119 -19
- package/lib/tools/control.js +45 -12
- package/lib/tools/deps.js +2 -2
- package/lib/tools/mcp.js +6 -4
- package/lib/tools/memory.js +1098 -267
- package/lib/tools/note-ref.js +20 -0
- package/lib/tools/remove.js +1 -1
- package/lib/tools/scene.js +3 -3
- package/lib/tools/table.js +103 -24
- package/package.json +155 -156
- package/docs/UPDATE.md +0 -50
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
// 自主记忆的**真源状态**(`evolution/state.json`):证据链、计数器、状态迁移、墓碑、水位。
|
|
2
|
+
//
|
|
3
|
+
// 为什么它与 `catalog.json` 分开:catalog 全部可由「磁盘文件 + 本文件」重建,坏了重建即可;
|
|
4
|
+
// 本文件里的证据与墓碑**不可重建** —— 它们是"为什么记这条"和"用户已经删过这条"的唯一记录。
|
|
5
|
+
// 两者混在一个文件里,一次 catalog 重建就会把墓碑一起冲掉,于是用户删掉的事实会复活。
|
|
6
|
+
//
|
|
7
|
+
// 为什么证据不放 frontmatter:`parseSkillDoc` 只识别顶层扁平标量(见 skills/frontmatter.ts 的
|
|
8
|
+
// 注释),数组与嵌套结构进不了 map。硬塞只能序列化成一行 JSON,那既不可读、也会让
|
|
9
|
+
// `description` 这类字段被 500 字符上限截断。所以:frontmatter 只放标量(给发现层与界面读),
|
|
10
|
+
// 证据与计数器放这里(给写入管线与维护扫描读)。
|
|
11
|
+
//
|
|
12
|
+
// 读的纪律(与 `settings-sidecars` 相反,这是有意的):
|
|
13
|
+
// - 侧车读坏 → 回默认值,因为界面必须能打开;
|
|
14
|
+
// - 本文件读坏 → **拒绝写入并报错**。用默认值覆盖它等于把用户所有的证据链和墓碑一次性清零,
|
|
15
|
+
// 之后被删的记忆会静默复活、被纠正过的错误会重新变成"高置信"。宁可停摆,不可静默。
|
|
16
|
+
// 坏的原文会先备份到 `evolution/state.json.corrupt-<ts>`,正文文件一个不动。
|
|
17
|
+
import { copyFile, mkdir, readFile, rm } from 'node:fs/promises';
|
|
18
|
+
import { hubPath } from '../hub.js';
|
|
19
|
+
import { writeFileAtomically } from '../memories/index-io.js';
|
|
20
|
+
export const EVOLUTION_STATE_FILE = 'evolution/state.json';
|
|
21
|
+
export const STATE_VERSION = 1;
|
|
22
|
+
export const EVIDENCE_SOURCES = ['user_explicit', 'user_correction', 'tool_verified', 'model_inference', 'user_approved'];
|
|
23
|
+
/** 可被新写入产生的来源。旧数据里的另外两个只读不写。 */
|
|
24
|
+
export const WRITABLE_EVIDENCE_SOURCES = ['user_explicit', 'model_inference', 'user_approved'];
|
|
25
|
+
export const EVIDENCE_TIERS = ['confirmed', 'quoted', 'inferred'];
|
|
26
|
+
/** 来源 → 档位。旧数据的两档自报来源归入最弱一档,见 `EvidenceSource` 的说明。 */
|
|
27
|
+
export function tierOfSource(source) {
|
|
28
|
+
if (source === 'user_approved')
|
|
29
|
+
return 'confirmed';
|
|
30
|
+
if (source === 'user_explicit')
|
|
31
|
+
return 'quoted';
|
|
32
|
+
return 'inferred';
|
|
33
|
+
}
|
|
34
|
+
/** 一组证据里最强的档位。没有证据 = 最弱(`inferred`),不是"没有档位"。 */
|
|
35
|
+
export function tierOf(evidence) {
|
|
36
|
+
let best = 'inferred';
|
|
37
|
+
for (const e of evidence) {
|
|
38
|
+
const t = tierOfSource(e.source);
|
|
39
|
+
if (t === 'confirmed')
|
|
40
|
+
return 'confirmed';
|
|
41
|
+
if (t === 'quoted')
|
|
42
|
+
best = 'quoted';
|
|
43
|
+
}
|
|
44
|
+
return best;
|
|
45
|
+
}
|
|
46
|
+
/** 宽松读 `procedure`:结构不对就当没有,别让一条脏记录拖垮整个 state。 */
|
|
47
|
+
export function normalizeProcedure(raw) {
|
|
48
|
+
if (!raw || typeof raw !== 'object' || !Array.isArray(raw.steps))
|
|
49
|
+
return undefined;
|
|
50
|
+
const steps = raw.steps
|
|
51
|
+
.filter((x) => typeof x === 'string')
|
|
52
|
+
.map((x) => x.trim().slice(0, 240))
|
|
53
|
+
.filter((x) => x !== '')
|
|
54
|
+
.slice(0, 12);
|
|
55
|
+
if (steps.length === 0)
|
|
56
|
+
return undefined;
|
|
57
|
+
return {
|
|
58
|
+
steps,
|
|
59
|
+
successes: Math.max(0, Math.floor(Number(raw.successes) || 0)),
|
|
60
|
+
failures: Math.max(0, Math.floor(Number(raw.failures) || 0)),
|
|
61
|
+
...(typeof raw.lastSucceededAt === 'string' ? { lastSucceededAt: raw.lastSucceededAt } : {}),
|
|
62
|
+
...(typeof raw.lastFailedAt === 'string' ? { lastFailedAt: raw.lastFailedAt } : {}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** 墓碑有效期:30 天。过期的墓碑在下次写盘时清掉(不是读时清 —— 读要无副作用)。 */
|
|
66
|
+
export const TOMBSTONE_DAYS = 30;
|
|
67
|
+
export const emptyState = () => ({ version: STATE_VERSION, entries: {}, tombstones: [], watermarks: {} });
|
|
68
|
+
export const emptyCounters = () => ({ injected: 0, read: 0 });
|
|
69
|
+
const str = (v, fallback = '') => (typeof v === 'string' ? v : fallback);
|
|
70
|
+
const num = (v, fallback = 0) => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
|
|
71
|
+
const bool = (v) => (typeof v === 'boolean' ? v : undefined);
|
|
72
|
+
function normalizeEvidence(raw) {
|
|
73
|
+
if (!Array.isArray(raw))
|
|
74
|
+
return [];
|
|
75
|
+
const out = [];
|
|
76
|
+
for (const item of raw) {
|
|
77
|
+
if (!item || typeof item !== 'object')
|
|
78
|
+
continue;
|
|
79
|
+
const source = EVIDENCE_SOURCES.includes(item.source) ? item.source : 'model_inference';
|
|
80
|
+
const quote = str(item.quote).slice(0, 2000);
|
|
81
|
+
// 无引句的证据没有价值:它既不能过证据门,也不能在界面里解释"为什么记这条"。
|
|
82
|
+
if (quote === '')
|
|
83
|
+
continue;
|
|
84
|
+
out.push({
|
|
85
|
+
session: str(item.session),
|
|
86
|
+
turn: num(item.turn),
|
|
87
|
+
seq: num(item.seq, -1),
|
|
88
|
+
source,
|
|
89
|
+
quote,
|
|
90
|
+
at: str(item.at),
|
|
91
|
+
});
|
|
92
|
+
// 一个条目的证据超过 50 条时只留**最近的**:再多也不改变档位(档位只看最强的来源)。
|
|
93
|
+
// 这里 `break` 留的是数组最前面那 50 条 —— 那是最旧的。写入侧 `applyOutcome` 已经用
|
|
94
|
+
// `.slice(-50)` 兜住了,所以只有手工编辑 / 旧数据会走到这条;但它必须与注释一致,
|
|
95
|
+
// 否则"留最近的"变成"留最旧的",证据链会停在最早那几条上。
|
|
96
|
+
if (out.length >= 50)
|
|
97
|
+
out.shift();
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 旧 `needsReview` → 两个新字段。
|
|
103
|
+
*
|
|
104
|
+
* 迁移判据只有状态:候选的理由是"等你裁决"(不该注入),其余(生效中 / 已归档)的理由
|
|
105
|
+
* 只能是 TTL 复核提醒(该继续注入)。旧数据里没有别的原因会挂在非候选条目上 ——
|
|
106
|
+
* 冲突与歧义都会把条目压成候选。
|
|
107
|
+
*
|
|
108
|
+
* ⚠️ 状态只能从 state 条目自己的 `auto_status` 读:`normalizeEntry` 拿不到笔记文件。
|
|
109
|
+
* 而**历史 state.json 并不写这个键**,于是实际效果是「旧 `needsReview` 一律归待裁决」。
|
|
110
|
+
* 这与当时的真实数据一致(带旧字段的条目都是候选),但方向上偏保守:把一条生效中的
|
|
111
|
+
* 记忆误判成待裁决会让它不再注入,而反向误判只是多一条复核提醒。真要区分,得让调用方
|
|
112
|
+
* 把笔记状态传进来 —— 那时改这里。
|
|
113
|
+
*/
|
|
114
|
+
function splitReviewFields(raw) {
|
|
115
|
+
const legacy = typeof raw.needsReview === 'string' && raw.needsReview !== '' ? raw.needsReview : '';
|
|
116
|
+
const pending = typeof raw.pendingReason === 'string' && raw.pendingReason !== '' ? raw.pendingReason : '';
|
|
117
|
+
const due = typeof raw.reviewDue === 'string' && raw.reviewDue !== '' ? raw.reviewDue : '';
|
|
118
|
+
if (pending !== '' || due !== '') {
|
|
119
|
+
return { ...(pending !== '' ? { pendingReason: pending } : {}), ...(due !== '' ? { reviewDue: due } : {}) };
|
|
120
|
+
}
|
|
121
|
+
if (legacy === '')
|
|
122
|
+
return {};
|
|
123
|
+
// 状态在 `...raw` 里还没归一化,这里直接看原值:`candidate` 才是待裁决。
|
|
124
|
+
return raw.auto_status === undefined || raw.auto_status === 'candidate'
|
|
125
|
+
? { pendingReason: legacy }
|
|
126
|
+
: { reviewDue: legacy };
|
|
127
|
+
}
|
|
128
|
+
function normalizeEntry(raw) {
|
|
129
|
+
if (!raw || typeof raw !== 'object')
|
|
130
|
+
return null;
|
|
131
|
+
const counters = raw.counters && typeof raw.counters === 'object' ? raw.counters : {};
|
|
132
|
+
const transitions = [];
|
|
133
|
+
if (Array.isArray(raw.transitions)) {
|
|
134
|
+
for (const t of raw.transitions.slice(-50)) {
|
|
135
|
+
if (!t || typeof t !== 'object')
|
|
136
|
+
continue;
|
|
137
|
+
transitions.push({
|
|
138
|
+
at: str(t.at),
|
|
139
|
+
from: str(t.from),
|
|
140
|
+
to: str(t.to),
|
|
141
|
+
actor: ['learn', 'curator', 'user', 'sweep', 'dream', 'system'].includes(t.actor) ? t.actor : 'system',
|
|
142
|
+
reason: str(t.reason),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
// 保留未知字段:未来版本加的键不该被旧版本静默丢掉。
|
|
148
|
+
...raw,
|
|
149
|
+
evidence: normalizeEvidence(raw.evidence),
|
|
150
|
+
counters: {
|
|
151
|
+
injected: Math.max(0, num(counters.injected)),
|
|
152
|
+
read: Math.max(0, num(counters.read)),
|
|
153
|
+
...(typeof counters.lastInjectedAt === 'string' ? { lastInjectedAt: counters.lastInjectedAt } : {}),
|
|
154
|
+
...(typeof counters.lastUsedAt === 'string' ? { lastUsedAt: counters.lastUsedAt } : {}),
|
|
155
|
+
},
|
|
156
|
+
transitions,
|
|
157
|
+
...(typeof raw.degraded === 'string' && raw.degraded !== '' ? { degraded: raw.degraded } : {}),
|
|
158
|
+
...(bool(raw.locked) === true ? { locked: true } : {}),
|
|
159
|
+
...splitReviewFields(raw),
|
|
160
|
+
// 显式归一化:上面的 `...raw` 会把脏的 procedure 原样带进来,界面拿去渲染就会炸。
|
|
161
|
+
...(normalizeProcedure(raw.procedure) !== undefined ? { procedure: normalizeProcedure(raw.procedure) } : {}),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* 原型链上的名字不能当条目 id:`entries['__proto__'] = e` 改的是原型,不是落一个
|
|
166
|
+
* 自有属性 —— 写进 state 的条目会凭空消失,读侧还可能在别的对象上看见它。
|
|
167
|
+
*/
|
|
168
|
+
const UNSAFE_ENTRY_IDS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
169
|
+
/** 宽松读:结构不对的**单个条目**丢掉,整体结构不对才报坏。理由见文件头。 */
|
|
170
|
+
export function normalizeState(raw) {
|
|
171
|
+
if (raw === null || raw === undefined)
|
|
172
|
+
return { ok: true, state: emptyState() };
|
|
173
|
+
if (typeof raw !== 'object' || Array.isArray(raw))
|
|
174
|
+
return { ok: false, error: 'state.json 的顶层不是对象' };
|
|
175
|
+
const r = raw;
|
|
176
|
+
// 版本高于本进程 → 是更新的插件写的。此时"看不懂就覆盖"会丢掉新版本的字段与语义,
|
|
177
|
+
// 所以直接拒绝:让用户先升级插件,而不是悄悄降级他的状态。
|
|
178
|
+
if (typeof r.version === 'number' && r.version > STATE_VERSION) {
|
|
179
|
+
return { ok: false, error: `state.json 版本 ${r.version} 高于本插件支持的 ${STATE_VERSION}(是不是装过更新的版本?)` };
|
|
180
|
+
}
|
|
181
|
+
const entries = {};
|
|
182
|
+
if (r.entries && typeof r.entries === 'object') {
|
|
183
|
+
for (const [id, value] of Object.entries(r.entries)) {
|
|
184
|
+
if (UNSAFE_ENTRY_IDS.has(id))
|
|
185
|
+
continue;
|
|
186
|
+
const e = normalizeEntry(value);
|
|
187
|
+
if (e)
|
|
188
|
+
entries[id] = e;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const tombstones = [];
|
|
192
|
+
if (Array.isArray(r.tombstones)) {
|
|
193
|
+
for (const t of r.tombstones) {
|
|
194
|
+
if (!t || typeof t !== 'object')
|
|
195
|
+
continue;
|
|
196
|
+
const key = str(t.key);
|
|
197
|
+
const textHash = str(t.textHash);
|
|
198
|
+
if (key === '' && textHash === '')
|
|
199
|
+
continue;
|
|
200
|
+
tombstones.push({
|
|
201
|
+
key,
|
|
202
|
+
textHash,
|
|
203
|
+
text: str(t.text).slice(0, 400),
|
|
204
|
+
at: str(t.at),
|
|
205
|
+
until: str(t.until),
|
|
206
|
+
actor: str(t.actor, 'unknown'),
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const w = r.watermarks && typeof r.watermarks === 'object' ? r.watermarks : {};
|
|
211
|
+
return {
|
|
212
|
+
ok: true,
|
|
213
|
+
state: {
|
|
214
|
+
version: STATE_VERSION,
|
|
215
|
+
entries,
|
|
216
|
+
tombstones,
|
|
217
|
+
watermarks: {
|
|
218
|
+
...(typeof w.lastReviewedTurn === 'number' ? { lastReviewedTurn: w.lastReviewedTurn } : {}),
|
|
219
|
+
...(typeof w.lastReviewAt === 'string' ? { lastReviewAt: w.lastReviewAt } : {}),
|
|
220
|
+
...(typeof w.lastDreamAt === 'string' ? { lastDreamAt: w.lastDreamAt } : {}),
|
|
221
|
+
...(typeof w.lastDreamTryAt === 'string' ? { lastDreamTryAt: w.lastDreamTryAt } : {}),
|
|
222
|
+
...(typeof w.lastSweepAt === 'string' ? { lastSweepAt: w.lastSweepAt } : {}),
|
|
223
|
+
...(typeof w.autoRevision === 'number' && Number.isFinite(w.autoRevision) ? { autoRevision: w.autoRevision } : {}),
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
// ── 档位与排序 ─────────────────────────────────────────────────────────────
|
|
229
|
+
/** 独立证据数 = 不同 session 的条数(同一会话里说两遍不算两次独立验证)。 */
|
|
230
|
+
export function independentEvidenceOf(evidence) {
|
|
231
|
+
return new Set(evidence.map((e) => e.session || '?')).size;
|
|
232
|
+
}
|
|
233
|
+
/** 档位 → 排序权重。只用于先后,不对外展示成数字。 */
|
|
234
|
+
const TIER_RANK = { confirmed: 3, quoted: 2, inferred: 1 };
|
|
235
|
+
/** 展示用的档位名(界面与工具回执共用一份,避免两处措辞不同)。 */
|
|
236
|
+
export const TIER_LABEL = {
|
|
237
|
+
confirmed: 'confirmed',
|
|
238
|
+
quoted: 'quoted from the user',
|
|
239
|
+
inferred: 'inferred',
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* 一条自动记忆的排序分。**只用可观测的事实**,按优先级分层:
|
|
243
|
+
*
|
|
244
|
+
* ① 证据档位 —— 用户确认过 > 有核对过的原话 > 纯推断;
|
|
245
|
+
* ② 命中率 `read / injected` —— 进了上下文之后模型有没有真去拉全文。这是唯一能回答
|
|
246
|
+
* "这条占着位置到底有没有用"的信号,而且是系统计数,模型伪造不了;
|
|
247
|
+
* ③ 新鲜度 —— 同档同命中率时,近的优先。
|
|
248
|
+
*
|
|
249
|
+
* 为什么不用模型自报的 confidence:那是把"写的人"和"裁判"合成一个人。为什么不用
|
|
250
|
+
* helpful / harmful:它们没有写入路径,恒为 0 —— 留着只会让公式看起来在权衡。
|
|
251
|
+
*
|
|
252
|
+
* 命中率用 Laplace 平滑(`(read+1)/(injected+2)`):只注入过一次又没被读,不该被判成
|
|
253
|
+
* 0 分;注入 50 次读 0 次才该沉下去。
|
|
254
|
+
*/
|
|
255
|
+
export function scoreOf(entry, counters, now = Date.now()) {
|
|
256
|
+
const tier = TIER_RANK[entry.tier] ?? 1;
|
|
257
|
+
const injected = Math.max(0, counters.injected);
|
|
258
|
+
const read = Math.max(0, counters.read);
|
|
259
|
+
const hit = (read + 1) / (injected + 2);
|
|
260
|
+
const updatedAt = entry.updatedAt ? Date.parse(entry.updatedAt) : Number.NaN;
|
|
261
|
+
const ageDays = Number.isFinite(updatedAt) ? Math.max(0, (now - updatedAt) / 86400_000) : 0;
|
|
262
|
+
// 新鲜度衰减 60 天半衰,权重压到 0.2 —— 它是打破平局用的,不该盖过"有没有被用过"。
|
|
263
|
+
const fresh = 0.2 * Math.exp(-ageDays / 60);
|
|
264
|
+
return tier * 10 + hit + fresh;
|
|
265
|
+
}
|
|
266
|
+
/** 归一化正文 → 墓碑用的指纹。 */
|
|
267
|
+
export function textHashOf(text) {
|
|
268
|
+
// 不引入新依赖:这里只需要"稳定且足够短",用 djb2 变体足够(碰撞只影响墓碑拦截的精度,
|
|
269
|
+
// 而墓碑还有 key 那一道)。真正需要抗碰撞的是工作区目录名,那里用的 sha256。
|
|
270
|
+
let h = 5381;
|
|
271
|
+
const norm = String(text ?? '').toLowerCase().replaceAll(/\s+/g, ' ').trim();
|
|
272
|
+
for (let i = 0; i < norm.length; i++)
|
|
273
|
+
h = ((h << 5) + h + norm.charCodeAt(i)) | 0;
|
|
274
|
+
return 'djb2:' + (h >>> 0).toString(16);
|
|
275
|
+
}
|
|
276
|
+
/** 墓碑是否仍然有效(`until` 为空 = 永久)。 */
|
|
277
|
+
export function tombstoneActive(t, now = Date.now()) {
|
|
278
|
+
if (t.until === '')
|
|
279
|
+
return true;
|
|
280
|
+
const at = Date.parse(t.until);
|
|
281
|
+
return Number.isFinite(at) ? at > now : true;
|
|
282
|
+
}
|
|
283
|
+
/** 这条(key / 文本)是否被墓碑拦住。任一匹配即拦 —— key 命中比文本命中更可靠,但两者都要判。 */
|
|
284
|
+
export function tombstonedBy(state, key, textHash, now = Date.now()) {
|
|
285
|
+
return state.tombstones.find((t) => tombstoneActive(t, now) && ((key !== '' && t.key === key) || (textHash !== '' && t.textHash === textHash)));
|
|
286
|
+
}
|
|
287
|
+
export function makeTombstone(key, textHash, actor, now = Date.now(), text = '') {
|
|
288
|
+
const at = new Date(now);
|
|
289
|
+
const until = new Date(now + TOMBSTONE_DAYS * 86400_000);
|
|
290
|
+
return { key, textHash, text: text.slice(0, 400), at: at.toISOString(), until: until.toISOString(), actor };
|
|
291
|
+
}
|
|
292
|
+
/** 用户动作版本号 +1。写入方在确认 / 停用 / 恢复 / 删除 / 提升之后调用。 */
|
|
293
|
+
export function bumpRevision(state) {
|
|
294
|
+
state.watermarks.autoRevision = (state.watermarks.autoRevision ?? 0) + 1;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* 清掉过期墓碑、合并同引用重复项;返回是否有变化(调用方据此决定要不要写盘)。
|
|
298
|
+
*
|
|
299
|
+
* 去重是必须的:写入侧已经做到「同 key 只留一条」,但**存量**是历史上反复 forget 同一
|
|
300
|
+
* 个 key 攒下来的 —— 每组只差几十毫秒、`until` 几乎相同,留着纯属让 `state.json` 白白
|
|
301
|
+
* 变大(实测墓碑能占到整份文件的八成以上)。合并时保留**最后一条**:它的 `until` 最晚,
|
|
302
|
+
* 拦截窗口与原来等价。
|
|
303
|
+
*/
|
|
304
|
+
export function pruneTombstones(state, now = Date.now()) {
|
|
305
|
+
const kept = [];
|
|
306
|
+
const at = new Map();
|
|
307
|
+
for (const t of state.tombstones) {
|
|
308
|
+
if (!tombstoneActive(t, now))
|
|
309
|
+
continue;
|
|
310
|
+
// 没有 key 的墓碑按正文哈希去重;两者都没有的(不该存在)各自独立,不合并。
|
|
311
|
+
const slot = t.key !== '' ? 'k:' + t.key : t.textHash !== '' ? 'h:' + t.textHash : '';
|
|
312
|
+
if (slot === '') {
|
|
313
|
+
kept.push(t);
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
const seen = at.get(slot);
|
|
317
|
+
if (seen === undefined) {
|
|
318
|
+
at.set(slot, kept.length);
|
|
319
|
+
kept.push(t);
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
// 保留 `until` 更晚的那条;`until` 为空 = 永久,优先级最高。
|
|
323
|
+
const prev = kept[seen];
|
|
324
|
+
const prevForever = prev.until === '';
|
|
325
|
+
const nextForever = t.until === '';
|
|
326
|
+
if (nextForever || (!prevForever && t.until > prev.until))
|
|
327
|
+
kept[seen] = t;
|
|
328
|
+
}
|
|
329
|
+
if (kept.length === state.tombstones.length) {
|
|
330
|
+
// 长度没变也可能是同组换了保留项:逐项比一次引用,避免把「合并了但条数相同」漏掉。
|
|
331
|
+
let same = true;
|
|
332
|
+
for (let i = 0; i < kept.length; i++)
|
|
333
|
+
if (kept[i] !== state.tombstones[i]) {
|
|
334
|
+
same = false;
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
if (same)
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
state.tombstones = kept;
|
|
341
|
+
return true;
|
|
342
|
+
}
|
|
343
|
+
const CACHE_TTL_MS = 1000;
|
|
344
|
+
/**
|
|
345
|
+
* 隔离标记:坏掉的 `state.json` 被留存后写下它,**在此后的所有写路径上 fail-closed**。
|
|
346
|
+
*
|
|
347
|
+
* 为什么必须有这个持久闸门:只在"读坏的那一次"返回错误是不够的。文件被搬走后,
|
|
348
|
+
* 下一次读得到 `missing`,而 `missing` 是全新用户的正常状态 —— 于是任意一次写
|
|
349
|
+
* (编辑一条笔记、每日维护扫描)都会把一份空状态整份写回,`entries` 与 `tombstones`
|
|
350
|
+
* 一起清零。墓碑丢了,用户删过的内容会被自动路径重新学回来;证据链丢了,已确认的
|
|
351
|
+
* 记忆失去"凭什么记"。两者都不可重建。
|
|
352
|
+
*
|
|
353
|
+
* 标记只能被显式修复动作清掉(用户处理完原文件后删掉它),不随读成功自动消失。
|
|
354
|
+
*/
|
|
355
|
+
export const STATE_QUARANTINE_FILE = 'evolution/state.quarantine.json';
|
|
356
|
+
export function createEvolutionState(deps) {
|
|
357
|
+
let cache = null;
|
|
358
|
+
/** 进程内缓存:持久标记读不到时(磁盘只读等)仍要挡住写入。 */
|
|
359
|
+
let quarantined = null;
|
|
360
|
+
let quarantineChecked = false;
|
|
361
|
+
const absState = () => hubPath(EVOLUTION_STATE_FILE);
|
|
362
|
+
function quarantinePath() {
|
|
363
|
+
return hubPath(STATE_QUARANTINE_FILE);
|
|
364
|
+
}
|
|
365
|
+
async function readQuarantine() {
|
|
366
|
+
if (quarantineChecked)
|
|
367
|
+
return quarantined;
|
|
368
|
+
quarantineChecked = true;
|
|
369
|
+
try {
|
|
370
|
+
const raw = JSON.parse(await readFile(quarantinePath(), 'utf8'));
|
|
371
|
+
if (raw && typeof raw === 'object' && typeof raw.keptFile === 'string') {
|
|
372
|
+
quarantined = {
|
|
373
|
+
at: Number.isFinite(raw.at) ? Number(raw.at) : 0,
|
|
374
|
+
keptFile: raw.keptFile,
|
|
375
|
+
reason: typeof raw.reason === 'string' ? raw.reason : '',
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
catch {
|
|
380
|
+
// 没有标记 / 读不出来:当作没隔离(标记是保护,不是数据源)。
|
|
381
|
+
}
|
|
382
|
+
return quarantined;
|
|
383
|
+
}
|
|
384
|
+
async function writeQuarantine(info) {
|
|
385
|
+
quarantined = info;
|
|
386
|
+
quarantineChecked = true;
|
|
387
|
+
try {
|
|
388
|
+
await mkdir(hubPath('evolution'), { recursive: true });
|
|
389
|
+
await writeFileAtomically(quarantinePath(), JSON.stringify({ v: 1, ...info }, null, 2) + '\n', { mode: 0o600 });
|
|
390
|
+
}
|
|
391
|
+
catch (e) {
|
|
392
|
+
// 写标记失败是"保护降级"(进程内仍挡住),不是本次操作失败。
|
|
393
|
+
console.warn(`[dsh-plugin-tool-management] state 隔离标记写入失败:${deps.message(e)}`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
/** 隔离态的报错文案:必须带上留存路径,否则用户无从找回。 */
|
|
397
|
+
function quarantineError(q) {
|
|
398
|
+
return `state.json 已被隔离,自动写入已停止,以免用空状态覆盖证据链与墓碑。`
|
|
399
|
+
+ `原因:${q.reason || '未知'}。原文件留存在 ${q.keptFile} —— 处理完它并删除 ${STATE_QUARANTINE_FILE} 后重启即可恢复写入。`;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* 读当前状态。
|
|
403
|
+
*
|
|
404
|
+
* @param opts.quarantine 解析失败时是否留存副本并落隔离标记,默认 `true`。**写路径不许关**:
|
|
405
|
+
* 不留存就等于拿一份空状态去覆盖证据链与墓碑。只有只读 op(`evolution-status` /
|
|
406
|
+
* `evolution-health` / `evolution-preview`)给 `false` —— 它们声称不写盘,就不能因为
|
|
407
|
+
* 撞上一份坏文件而在 `evolution/` 里留下副本。
|
|
408
|
+
*/
|
|
409
|
+
async function readFresh(opts = {}) {
|
|
410
|
+
const quarantine = opts.quarantine !== false;
|
|
411
|
+
// 只读访问不建目录:目录本身就是一次写盘。
|
|
412
|
+
if (quarantine)
|
|
413
|
+
await deps.ensurePaths();
|
|
414
|
+
// 隔离标记是**权威闸门**:它存在时连读都不必给成功结果,否则调用方会拿着空状态
|
|
415
|
+
// 去改、再走 write(),而 write() 的 fail-closed 只是最后一道。
|
|
416
|
+
const q = await readQuarantine();
|
|
417
|
+
if (q)
|
|
418
|
+
return { ok: false, error: quarantineError(q) };
|
|
419
|
+
const read = await deps.readJsonFileStrict(absState());
|
|
420
|
+
if (read.status === 'missing')
|
|
421
|
+
return { ok: true, state: emptyState() };
|
|
422
|
+
if (read.status === 'unreadable') {
|
|
423
|
+
// **绝不隔离、绝不改名**:读失败可能是杀软 / 索引器瞬时占用,重试就能好。
|
|
424
|
+
// 把"重试即可恢复"升级成"数据被搬走",正是这条链最早的错误。
|
|
425
|
+
return {
|
|
426
|
+
ok: false,
|
|
427
|
+
error: `state.json 暂时读不出来:${read.error}。已停止自动写入;稍后重试或检查文件权限。`,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
if (read.status === 'corrupt') {
|
|
431
|
+
if (!quarantine)
|
|
432
|
+
return { ok: false, error: corruptReadOnlyError(read.error) };
|
|
433
|
+
const kept = await keepCorruptCopy(read.error);
|
|
434
|
+
return { ok: false, error: kept };
|
|
435
|
+
}
|
|
436
|
+
const normalized = normalizeState(read.value);
|
|
437
|
+
if (!normalized.ok) {
|
|
438
|
+
if (!quarantine)
|
|
439
|
+
return { ok: false, error: corruptReadOnlyError(normalized.error) };
|
|
440
|
+
const kept = await keepCorruptCopy(normalized.error);
|
|
441
|
+
return { ok: false, error: kept };
|
|
442
|
+
}
|
|
443
|
+
return normalized;
|
|
444
|
+
}
|
|
445
|
+
/** 只读访问撞上坏文件:如实报错,并说清"副本要等写路径来留"。 */
|
|
446
|
+
function corruptReadOnlyError(reason) {
|
|
447
|
+
return `state.json 解析失败:${reason}。本次是只读访问,未改动任何文件;下一次写入前的读取会留存副本并停止自动写入。`;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* 解析失败:**复制**一份留存(原文件留在原位),写下隔离标记,返回给用户看的文案。
|
|
451
|
+
*
|
|
452
|
+
* 用复制而不是改名:改名之后"原文件在哪"取决于备份是否成功,而复制失败时原文件仍在,
|
|
453
|
+
* 用户至少还能自己看到它。两种情况下正文文件一个都不动。
|
|
454
|
+
*/
|
|
455
|
+
async function keepCorruptCopy(reason) {
|
|
456
|
+
const dest = corruptBackupPath();
|
|
457
|
+
// 留存副本的**绝对路径**。`corruptBackupPath()` 给的是 hub 相对路径(它同时被界面当
|
|
458
|
+
// 相对标识用),这里必须换成绝对的再记进隔离记录 —— `keptFile` 唯一的用途是写进
|
|
459
|
+
// 给用户看的那句话(「原文件留存在 …」),存相对路径等于让人拿到一个没法直接用的路径。
|
|
460
|
+
const destAbs = hubPath(dest);
|
|
461
|
+
let keptFile = absState();
|
|
462
|
+
try {
|
|
463
|
+
await copyFile(absState(), destAbs);
|
|
464
|
+
keptFile = destAbs;
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
// 复制不了就指着原文件:绝不 rm,那是用户唯一的证据链。
|
|
468
|
+
}
|
|
469
|
+
const info = { at: Date.now(), keptFile, reason };
|
|
470
|
+
await writeQuarantine(info);
|
|
471
|
+
return quarantineError(info);
|
|
472
|
+
}
|
|
473
|
+
async function read() {
|
|
474
|
+
if (cache && Date.now() - cache.at < CACHE_TTL_MS)
|
|
475
|
+
return { ok: true, state: cache.value };
|
|
476
|
+
const r = await readFresh({ quarantine: false });
|
|
477
|
+
if (r.ok)
|
|
478
|
+
cache = { at: Date.now(), value: r.state };
|
|
479
|
+
return r;
|
|
480
|
+
}
|
|
481
|
+
function cachedSync() {
|
|
482
|
+
if (cache)
|
|
483
|
+
return cache.value;
|
|
484
|
+
void read().catch(() => { });
|
|
485
|
+
return emptyState();
|
|
486
|
+
}
|
|
487
|
+
function corruptBackupPath() {
|
|
488
|
+
return `evolution/state.json.corrupt-${Date.now()}`;
|
|
489
|
+
}
|
|
490
|
+
async function write(state) {
|
|
491
|
+
// 最后一道闸:即便调用方绕过 readFresh 拿到了一份空状态,隔离期间也不许落盘。
|
|
492
|
+
const q = await readQuarantine();
|
|
493
|
+
if (q)
|
|
494
|
+
return { ok: false, error: quarantineError(q) };
|
|
495
|
+
try {
|
|
496
|
+
await deps.ensurePaths();
|
|
497
|
+
await mkdir(hubPath('evolution'), { recursive: true });
|
|
498
|
+
pruneTombstones(state);
|
|
499
|
+
await writeFileAtomically(absState(), JSON.stringify(state, null, 2) + '\n', { mode: 0o600 });
|
|
500
|
+
cache = { at: Date.now(), value: state };
|
|
501
|
+
return { ok: true };
|
|
502
|
+
}
|
|
503
|
+
catch (e) {
|
|
504
|
+
return { ok: false, error: `写 state.json 失败:${deps.message(e)}` };
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async function update(fn) {
|
|
508
|
+
const r = await readFresh();
|
|
509
|
+
if (!r.ok)
|
|
510
|
+
return r;
|
|
511
|
+
const result = await fn(r.state);
|
|
512
|
+
const written = await write(r.state);
|
|
513
|
+
if (!written.ok)
|
|
514
|
+
return written;
|
|
515
|
+
return { ok: true, result };
|
|
516
|
+
}
|
|
517
|
+
return {
|
|
518
|
+
read,
|
|
519
|
+
readFresh,
|
|
520
|
+
cachedSync,
|
|
521
|
+
update,
|
|
522
|
+
write,
|
|
523
|
+
corruptBackupPath,
|
|
524
|
+
quarantined: async () => await readQuarantine(),
|
|
525
|
+
clearQuarantine: async () => {
|
|
526
|
+
quarantined = null;
|
|
527
|
+
quarantineChecked = true;
|
|
528
|
+
await rm(quarantinePath(), { force: true }).catch(() => undefined);
|
|
529
|
+
},
|
|
530
|
+
invalidateCache: () => { cache = null; },
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
/** 给条目追加一次迁移记录(保留最近 50 条)。 */
|
|
534
|
+
export function pushTransition(entry, from, to, actor, reason, now = Date.now()) {
|
|
535
|
+
if (from === to)
|
|
536
|
+
return;
|
|
537
|
+
entry.transitions.push({ at: new Date(now).toISOString(), from, to, actor, reason });
|
|
538
|
+
if (entry.transitions.length > 50)
|
|
539
|
+
entry.transitions.splice(0, entry.transitions.length - 50);
|
|
540
|
+
}
|