dsh-plugin-tool-management 0.22.4 → 0.22.6
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 +1624 -1395
- package/README.md +194 -177
- package/README_EN.md +194 -177
- package/docs/ARCHITECTURE.md +137 -0
- package/docs/COMPATIBILITY.md +112 -0
- package/docs/TROUBLESHOOTING.md +287 -0
- package/lib/client.js +14984 -12279
- package/lib/compat/capability-specs.js +66 -16
- package/lib/compat/host-contracts.js +14 -3
- 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 +96 -11
- 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 +38 -19
- package/lib/context-inject-select.js +33 -4
- package/lib/context-inject-surface.js +74 -22
- package/lib/context-inject.js +107 -15
- package/lib/evolution/cold.js +389 -0
- package/lib/evolution/config.js +507 -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 +874 -0
- package/lib/evolution/limits.js +21 -0
- package/lib/evolution/maintenance.js +516 -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 +179 -0
- package/lib/evolution/scope-card.js +144 -0
- package/lib/evolution/state.js +514 -0
- package/lib/evolution/write.js +1773 -0
- package/lib/imports/unzip.js +144 -26
- package/lib/index.js +1371 -79
- package/lib/legacy-tool-names.js +19 -4
- package/lib/mcp/manager.js +1 -0
- package/lib/mcp/tool-visibility.js +204 -11
- package/lib/memories/catalog.js +215 -0
- package/lib/memories/constants.js +115 -7
- package/lib/memories/discovery.js +59 -25
- package/lib/memories/projection.js +116 -31
- package/lib/memories/render-auto.js +198 -0
- package/lib/memories/search.js +3 -5
- package/lib/memories/service.js +252 -17
- package/lib/memories/snapshot.js +174 -23
- package/lib/op-registry.js +59 -0
- package/lib/ops/compat.js +2 -0
- package/lib/ops/evolution.js +887 -0
- package/lib/ops/memory.js +95 -72
- package/lib/ops/trash.js +14 -2
- package/lib/prompts/service.js +30 -0
- package/lib/scope/workspace-key.js +39 -0
- package/lib/settings-sidecars.js +2 -2
- package/lib/skills/dir-watch.js +49 -22
- package/lib/skills/official.js +180 -36
- package/lib/skills/service.js +2 -2
- package/lib/subagents/run-provider.js +35 -22
- package/lib/text-width.js +59 -0
- package/lib/tool-table-switch.js +104 -16
- 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 +1045 -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 +76 -20
- package/package.json +155 -152
- package/docs/UPDATE.md +0 -49
package/lib/ops/memory.js
CHANGED
|
@@ -9,12 +9,45 @@ import { lstat, mkdir, readFile, rename, rm } from 'node:fs/promises';
|
|
|
9
9
|
import { basename, dirname, join } from 'node:path';
|
|
10
10
|
import { parseSkillDoc, unquote } from '../skills/core.js';
|
|
11
11
|
import { expandUploads, planMemoryImport } from '../imports/upload.js';
|
|
12
|
-
import {
|
|
12
|
+
import { MAX_RULE_WIDTH, MAX_MEMORY_NAME_WIDTH, DEFAULT_ORDER, DEFAULT_GROUP_ORDER, GLOBAL_SCENE, GLOBAL_SCENE_LABEL, SHARED_GROUP, MAX_ATTACH_ENTRY_BYTES, MAX_ATTACH_TOTAL_BYTES, MAX_ATTACH_ENTRIES, LEGACY_BUNDLE_DOC, bundleDocName, SEGMENT_RULE_HINT, isValidGroupSegment, isValidGroupPath, isReservedGroup, message, fail } from '../memories/constants.js';
|
|
13
|
+
import { excerptOf, textWidthOf } from '../text-width.js';
|
|
13
14
|
import { normalizeActive, enabledSceneOf, sceneOf, sceneLabel, attachmentSummarySync } from '../memories/projection.js';
|
|
14
15
|
import { writeFileAtomically, writeFileAtomicBinary, readIndex, writeIndex, pathExists } from '../memories/index-io.js';
|
|
15
|
-
import { deriveDescription } from '../memories/snapshot.js';
|
|
16
16
|
import { stampConflict, stampOfText } from '../stale-write.js';
|
|
17
17
|
import { searchMemories } from '../memories/search.js';
|
|
18
|
+
/**
|
|
19
|
+
* 按创建时间升序;读不到创建时间(stat 失败 / 文件系统不给)的排在最后。
|
|
20
|
+
*
|
|
21
|
+
* 不能拿空串当"最旧":空串比任何 ISO 字符串都小,会让读不到时间的条目冒充最老的一条。
|
|
22
|
+
* ISO 8601 同时区下字符串序与时间序一致,直接比字符串即可。
|
|
23
|
+
*/
|
|
24
|
+
function compareCreatedAt(a, b) {
|
|
25
|
+
if (a === undefined)
|
|
26
|
+
return b === undefined ? 0 : 1;
|
|
27
|
+
if (b === undefined)
|
|
28
|
+
return -1;
|
|
29
|
+
return a.localeCompare(b);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* 正文按显示宽度校验(不是字节):同一条规则写中文比写英文密一倍,按字节卡会让中文记忆
|
|
33
|
+
* 只有英文的一半内容。超限返回拒绝回执,没超返回 null。
|
|
34
|
+
*
|
|
35
|
+
* 盘上已有的超长文件不受影响 —— 这条闸只在**写入**时生效,读与注入照旧(`memories/constants.ts`
|
|
36
|
+
* 的 `DEFAULT_MAX_BYTES` 才是注入侧那道闸)。
|
|
37
|
+
*/
|
|
38
|
+
function bodyWidthError(body) {
|
|
39
|
+
const width = textWidthOf(body);
|
|
40
|
+
if (width <= MAX_RULE_WIDTH)
|
|
41
|
+
return null;
|
|
42
|
+
return fail('error.rules.tooLarge', `记忆正文过长(${width} 显示宽度,上限 ${MAX_RULE_WIDTH},约 ${MAX_RULE_WIDTH / 2} 汉字 / ${MAX_RULE_WIDTH} 字母)`);
|
|
43
|
+
}
|
|
44
|
+
/** 名称按显示宽度校验;`isValidGroupSegment` 只卡 64 字符,中文名 64 字就是 128 宽度。 */
|
|
45
|
+
function nameWidthError(name) {
|
|
46
|
+
const width = textWidthOf(name);
|
|
47
|
+
if (width <= MAX_MEMORY_NAME_WIDTH)
|
|
48
|
+
return null;
|
|
49
|
+
return fail('error.rules.invalidName', `记忆名过长(${width} 显示宽度,上限 ${MAX_MEMORY_NAME_WIDTH},约 ${MAX_MEMORY_NAME_WIDTH / 2} 汉字 / ${MAX_MEMORY_NAME_WIDTH} 字母)`);
|
|
50
|
+
}
|
|
18
51
|
/** 组装本域 op。rc 由 createMemoriesService 组装,契约见 ./ctx.ts。 */
|
|
19
52
|
export function buildMemoryOps(rc) {
|
|
20
53
|
const { buildProjected, copyIntoMemoriesTrash, invalidateSnapshot, listAttachments, locateRule, maxBytes, parseId, refuseOutsideRoot, memoriesRoot, sceneMemory, scenePrompt, sceneRows, scenesRoot, serializeRuleFile, serializeUpdatedFile, snapshot, stateDir } = rc;
|
|
@@ -43,18 +76,29 @@ export function buildMemoryOps(rc) {
|
|
|
43
76
|
const index = snap.index;
|
|
44
77
|
const rules = snap.rules
|
|
45
78
|
.filter((r) => !groupFilter || r.group === groupFilter)
|
|
46
|
-
|
|
79
|
+
// 场景内:显式 `order` 优先(用户手动排过就听用户的),其次按**创建时间**升序 ——
|
|
80
|
+
// 越早记下的越靠前。此前第三档直接比名字,而所有记忆的 order 都是默认 1000,
|
|
81
|
+
// 于是实际按名字排:新建的条目只因名字凑巧(中文按拼音、英文按字母)就顶到最前,
|
|
82
|
+
// 读起来像"agent 写的被置顶了"。创建时间读不到(stat 失败)的排最后,不冒充最旧。
|
|
83
|
+
.sort((a, b) => a.group.localeCompare(b.group)
|
|
84
|
+
|| a.order - b.order
|
|
85
|
+
|| compareCreatedAt(a.createdAt, b.createdAt)
|
|
86
|
+
|| a.name.localeCompare(b.name))
|
|
47
87
|
// bundle 记忆附带附件摘要:界面要显示「几个附件」。
|
|
48
88
|
// 代价是**同步**系统调用(其余读路径都是 await):每条 bundle 一次 `readdirSync`
|
|
49
89
|
// + 每个附件一次 `statSync`,总量 = bundle 条数 × 平均附件数,随内容线性增长。
|
|
50
90
|
// 「可以忽略」这个判断只成立于 bundle 少、附件也少的时候 —— 记忆页不轮询(刷新点是
|
|
51
91
|
// 页面打开 / 切换会话 / 写操作之后),但每次刷新都是全量,bundle 到几百条就该换缓存或异步。
|
|
52
92
|
// flat 没有目录,原样返回(不加字段 = 界面不显示附件标签)。
|
|
93
|
+
//
|
|
94
|
+
// 顺带补上列表行的正文摘要:界面扫读用,注入仍用完整正文(见 `Rule.excerpt`)。
|
|
53
95
|
.map((r) => {
|
|
96
|
+
const excerpt = excerptOf(snap.bodies.get(r.id) ?? '');
|
|
97
|
+
const withExcerpt = excerpt === '' ? r : { ...r, excerpt };
|
|
54
98
|
if (r.form !== 'bundle')
|
|
55
|
-
return
|
|
99
|
+
return withExcerpt;
|
|
56
100
|
const attach = attachmentSummarySync(dirname(r.path), r.name);
|
|
57
|
-
return attach ? { ...
|
|
101
|
+
return attach ? { ...withExcerpt, attach } : withExcerpt;
|
|
58
102
|
});
|
|
59
103
|
const groups = groupFilter ? snap.groups.filter((g) => g.name === groupFilter) : snap.groups;
|
|
60
104
|
// 会话层:`scenes[]` 每一行的 `active` / `selectable` 也按本会话投影 ——
|
|
@@ -106,6 +150,13 @@ export function buildMemoryOps(rc) {
|
|
|
106
150
|
enabled: effectiveRules.filter((r) => r.enabled).length,
|
|
107
151
|
scenes: scenes.filter((s) => s.active).length,
|
|
108
152
|
},
|
|
153
|
+
// 工作区清单(只给界面用):`_ws/<hash16>` 那几节要显示项目名,而不是 hash 前 8 位。
|
|
154
|
+
//
|
|
155
|
+
// 每条带 `missing`:目录已经不在了的那些不进「新建记忆」的落点,但**已有条目照常列出**
|
|
156
|
+
// —— 条目还在盘上,凭空消失比多一行更糟。恢复目录后 `missing` 自然变回 false。
|
|
157
|
+
//
|
|
158
|
+
// 读不到就整个字段不给(界面退回 hash 短码):报空数组会被当成「一个工作区都没有」。
|
|
159
|
+
...(rc.workspacesOf === undefined ? {} : { workspaces: await rc.workspacesOf().catch(() => null) ?? undefined }),
|
|
109
160
|
...(snap.warnings.length ? { warnings: snap.warnings } : {}),
|
|
110
161
|
};
|
|
111
162
|
}
|
|
@@ -134,7 +185,6 @@ export function buildMemoryOps(rc) {
|
|
|
134
185
|
attachments: entry.kind === 'bundle' ? await listAttachments(entry.entryPath, entry.name) : [],
|
|
135
186
|
frontmatter: {
|
|
136
187
|
name: doc.map.name != null ? String(doc.map.name) : undefined,
|
|
137
|
-
description: doc.map.description != null ? String(doc.map.description) : undefined,
|
|
138
188
|
whenToUse: doc.map.whenToUse != null ? String(doc.map.whenToUse) : undefined,
|
|
139
189
|
globs: doc.map.globs != null ? String(doc.map.globs) : undefined,
|
|
140
190
|
metadata: doc.map.metadata !== undefined ? doc.map.metadata : undefined,
|
|
@@ -173,9 +223,6 @@ export function buildMemoryOps(rc) {
|
|
|
173
223
|
if (rule.shadowed) {
|
|
174
224
|
issues.push({ severity: 'warning', code: 'shadowed', ruleId: rule.id, message: `规则「${rule.id}」被同名 bundle 遮蔽,不会被加载。` });
|
|
175
225
|
}
|
|
176
|
-
if (String(rule.description || '').length > MAX_DESCRIPTION_LENGTH) {
|
|
177
|
-
issues.push({ severity: 'error', code: 'descriptionTooLong', ruleId: rule.id, message: `规则「${rule.id}」描述超过 ${MAX_DESCRIPTION_LENGTH} 字符,会被列表与检索截断。` });
|
|
178
|
-
}
|
|
179
226
|
if (rule.form === 'flat') {
|
|
180
227
|
const fileBase = basename(rule.path);
|
|
181
228
|
const base = fileBase.toLowerCase().endsWith('.md') ? fileBase.slice(0, -3) : fileBase;
|
|
@@ -187,9 +234,6 @@ export function buildMemoryOps(rc) {
|
|
|
187
234
|
if (body.trim() === '') {
|
|
188
235
|
issues.push({ severity: 'error', code: 'emptyBody', ruleId: rule.id, message: `规则「${rule.id}」正文为空。` });
|
|
189
236
|
}
|
|
190
|
-
if (rule.descriptionDerived && String(rule.description || '').length < 10) {
|
|
191
|
-
issues.push({ severity: 'info', code: 'vagueDescription', ruleId: rule.id, message: `规则「${rule.id}」描述过于笼统(自动派生,不足 10 字符),建议补充。` });
|
|
192
|
-
}
|
|
193
237
|
// 记忆所在场景未启用 → 不会自动生效(不是错误,但值得提示,避免"改了没效果")。
|
|
194
238
|
const scene = sceneOf(rule.group);
|
|
195
239
|
if (scene === '') {
|
|
@@ -250,12 +294,21 @@ export function buildMemoryOps(rc) {
|
|
|
250
294
|
return fail('error.rules.invalidGroup', `场景名非法:${group}(${SEGMENT_RULE_HINT})`);
|
|
251
295
|
const targetGroup = group === '' ? GLOBAL_SCENE : group;
|
|
252
296
|
const indexForScene = await readIndex(stateDir);
|
|
253
|
-
//
|
|
254
|
-
|
|
297
|
+
// 工作区记忆:`_ws/<hash16>` 是**用户手写**的工作区记忆(与自主笔记的 `_ws` 分属两棵树,
|
|
298
|
+
// 靠 origin 区分)。它不进场景列表 —— 工作区不是场景,进了就会以 `## Scene Memories: _ws/3f2a`
|
|
299
|
+
// 出现,也会被当成可选场景。这里放行它,其余保留组仍然拒绝。
|
|
300
|
+
const isWorkspaceGroup = /^_ws\/[0-9a-f]{16}$/.test(targetGroup);
|
|
301
|
+
if (targetGroup !== GLOBAL_SCENE && targetGroup !== SHARED_GROUP && !isWorkspaceGroup && !indexForScene.scenes?.[targetGroup] && !(await pathExists(join(memoriesRoot, targetGroup)))) {
|
|
255
302
|
return fail('error.rules.sceneNotFound', `场景不存在:${targetGroup}(请先在「场景」页创建该场景)`, { group: targetGroup });
|
|
256
303
|
}
|
|
304
|
+
if (isReservedGroup(targetGroup) && !isWorkspaceGroup && targetGroup !== SHARED_GROUP && targetGroup !== GLOBAL_SCENE) {
|
|
305
|
+
return fail('error.rules.invalidGroup', `保留组不能作为记忆目标:${targetGroup}`, { group: targetGroup });
|
|
306
|
+
}
|
|
257
307
|
if (!isValidGroupSegment(name))
|
|
258
308
|
return fail('error.rules.invalidName', `记忆名非法:${name}(${SEGMENT_RULE_HINT})`);
|
|
309
|
+
const nameTooWide = nameWidthError(name);
|
|
310
|
+
if (nameTooWide)
|
|
311
|
+
return nameTooWide;
|
|
259
312
|
// 目标已存在(bundle 或 flat 皆算)→ 拒绝,避免静默覆盖。
|
|
260
313
|
// 用 exists 而不是 shadowed:后者说的是「同名 bundle 把 flat 遮蔽了」,用户看到
|
|
261
314
|
// 「被同名 bundle 遮蔽」会去找一个并不存在的 bundle。
|
|
@@ -270,35 +323,25 @@ export function buildMemoryOps(rc) {
|
|
|
270
323
|
const body = String((args && args.body) ?? '');
|
|
271
324
|
if (body.trim() === '')
|
|
272
325
|
return fail('error.rules.bodyRequired', '规则正文不能为空');
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
const rawDescription = args && args.description != null ? String(args.description).trim() : '';
|
|
277
|
-
if (rawDescription !== '') {
|
|
278
|
-
if (rawDescription.length > MAX_DESCRIPTION_LENGTH) {
|
|
279
|
-
return fail('error.rules.descriptionTooLong', `描述超过 ${MAX_DESCRIPTION_LENGTH} 字符(当前 ${rawDescription.length})`);
|
|
280
|
-
}
|
|
281
|
-
description = rawDescription;
|
|
282
|
-
}
|
|
283
|
-
else {
|
|
284
|
-
const derived = deriveDescription(body);
|
|
285
|
-
if (!derived)
|
|
286
|
-
return fail('error.rules.descriptionRequired', '请提供规则描述(正文中也无可派生的标题或首行)');
|
|
287
|
-
description = derived; // 派生只进内存投影,不写回文件
|
|
288
|
-
}
|
|
326
|
+
const bodyTooWide = bodyWidthError(body);
|
|
327
|
+
if (bodyTooWide)
|
|
328
|
+
return bodyTooWide;
|
|
289
329
|
// 正文序列化(frontmatter 仅写用户显式提供的字段)。是否生效由"场景是否启用"决定,
|
|
290
330
|
// 超预算只在渲染时确定性截断 + 告警,不再拒绝写入。
|
|
331
|
+
//
|
|
332
|
+
// 不写 `description`:它只是正文的有损副本(首行 / 首个标题),而正文本身就会注入,
|
|
333
|
+
// 副本既多一份会过期的数据,也让「改正文但忘了改描述」变成一种静默不一致。
|
|
291
334
|
const fields = { name };
|
|
292
|
-
if (rawDescription !== '')
|
|
293
|
-
fields.description = description;
|
|
294
335
|
const text = serializeRuleFile(fields, body);
|
|
295
336
|
// 更新索引(force 重读后合并,避免覆盖用户手工编辑)。
|
|
296
337
|
// id 恒为 `<场景>/<名>`(与 parseId 同构);场景记录此时必然已存在。
|
|
297
338
|
const createdId = `${targetGroup}/${name}`;
|
|
298
339
|
const index = indexForScene;
|
|
299
|
-
//
|
|
340
|
+
// 新建记忆默认**不开启** —— 记忆的开关是单一真相源(`enabled`),
|
|
300
341
|
// 用户要求「创建的记忆默认不开启,在记忆页开启后对应的场景档案也要显示开启」。
|
|
301
|
-
|
|
342
|
+
// 调用方可以显式传 `enabled: true`(`memory_remember` 建的就是一条当时就要生效的记忆);
|
|
343
|
+
// 界面新建不传,保持默认关闭,由用户在记忆页决定。
|
|
344
|
+
index.rules[createdId] = { order: DEFAULT_ORDER, enabled: args && args.enabled === true, updatedAt: new Date().toISOString() };
|
|
302
345
|
if (!index.groups[targetGroup])
|
|
303
346
|
index.groups[targetGroup] = { order: DEFAULT_GROUP_ORDER, label: targetGroup };
|
|
304
347
|
// **先落索引、再落文件**,顺序不能反。索引条目指向一个尚不存在的文件是无害的:列表与投影
|
|
@@ -359,13 +402,18 @@ export function buildMemoryOps(rc) {
|
|
|
359
402
|
skipped.push({ name: target.name, reason: '记忆名不合法,已跳过' });
|
|
360
403
|
continue;
|
|
361
404
|
}
|
|
405
|
+
const importedNameTooWide = nameWidthError(target.name);
|
|
406
|
+
if (importedNameTooWide) {
|
|
407
|
+
skipped.push({ name: target.name, reason: importedNameTooWide.error });
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
362
410
|
const text = Buffer.from(target.bytes).toString('utf8').replace(/^\uFEFF/, '');
|
|
363
411
|
if (text.trim() === '') {
|
|
364
412
|
skipped.push({ name: target.name, reason: '内容为空,已跳过' });
|
|
365
413
|
continue;
|
|
366
414
|
}
|
|
367
|
-
if (
|
|
368
|
-
skipped.push({ name: target.name, reason: `正文超过 ${
|
|
415
|
+
if (textWidthOf(text) > MAX_RULE_WIDTH) {
|
|
416
|
+
skipped.push({ name: target.name, reason: `正文超过 ${MAX_RULE_WIDTH} 显示宽度,已跳过` });
|
|
369
417
|
continue;
|
|
370
418
|
}
|
|
371
419
|
// bundle 附件复检(规划层已过滤,这里按 rules-attach 同口径再拦一次,防绕过规划层的调用方)。
|
|
@@ -510,47 +558,22 @@ export function buildMemoryOps(rc) {
|
|
|
510
558
|
const newName = args && args.name != null ? String(args.name).trim() : currentName;
|
|
511
559
|
if (!isValidGroupSegment(newName))
|
|
512
560
|
return fail('error.rules.invalidName', `记忆名非法:${newName}(${SEGMENT_RULE_HINT})`);
|
|
561
|
+
const nameTooWide = nameWidthError(newName);
|
|
562
|
+
if (nameTooWide)
|
|
563
|
+
return nameTooWide;
|
|
513
564
|
const newForm = args && args.form === 'bundle' ? 'bundle' : args && args.form === 'flat' ? 'flat' : located.kind;
|
|
514
565
|
const newBody = args && args.body != null ? String(args.body) : doc.body;
|
|
515
566
|
if (newBody.trim() === '')
|
|
516
567
|
return fail('error.rules.bodyRequired', '规则正文不能为空');
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
let description;
|
|
521
|
-
if (args && args.description != null) {
|
|
522
|
-
const ds = String(args.description).trim();
|
|
523
|
-
if (ds !== '') {
|
|
524
|
-
if (ds.length > MAX_DESCRIPTION_LENGTH) {
|
|
525
|
-
return fail('error.rules.descriptionTooLong', `描述超过 ${MAX_DESCRIPTION_LENGTH} 字符(当前 ${ds.length})`);
|
|
526
|
-
}
|
|
527
|
-
description = ds;
|
|
528
|
-
}
|
|
529
|
-
else {
|
|
530
|
-
const derived = deriveDescription(newBody);
|
|
531
|
-
if (!derived)
|
|
532
|
-
return fail('error.rules.descriptionRequired', '请提供规则描述(正文中也无可派生的标题或首行)');
|
|
533
|
-
description = derived; // 派生不写回
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
else {
|
|
537
|
-
const existing = doc.map.description != null ? unquote(String(doc.map.description)).trim() : '';
|
|
538
|
-
if (existing !== '')
|
|
539
|
-
description = existing;
|
|
540
|
-
else
|
|
541
|
-
description = deriveDescription(newBody) || undefined;
|
|
542
|
-
}
|
|
568
|
+
const bodyTooWide = bodyWidthError(newBody);
|
|
569
|
+
if (bodyTooWide)
|
|
570
|
+
return bodyTooWide;
|
|
543
571
|
// 形态转换 / 改名:先建新形态文件,再把旧形态复制进回收站、最后删原件
|
|
544
572
|
// (确保任意失败点不产生半份规则;旧形态随时可恢复,README「删除都进回收站」无例外)。
|
|
545
|
-
//
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
descArg = String(args.description).trim() === '' ? null : description;
|
|
550
|
-
else
|
|
551
|
-
descArg = undefined;
|
|
552
|
-
return serializeUpdatedFile(text, newName, descArg, newBody);
|
|
553
|
-
};
|
|
573
|
+
//
|
|
574
|
+
// 不碰 `description`:那是正文的有损副本,新版不再读写它。旧文件里残留的那一行
|
|
575
|
+
// 原样留着(用户资产,删字段不该顺手改正文),读侧已忽略。
|
|
576
|
+
const serialize = () => serializeUpdatedFile(text, newName, newBody);
|
|
554
577
|
// 所有写入 / 删除分支的落点都在 `<root>/<group>` 之下:先确认这个目录(经 realpath)仍在根内。
|
|
555
578
|
const denied = await refuseOutsideRoot(join(memoriesRoot, parts.group));
|
|
556
579
|
if (denied)
|
|
@@ -780,10 +803,10 @@ export function buildMemoryOps(rc) {
|
|
|
780
803
|
id: r.id,
|
|
781
804
|
name: r.name,
|
|
782
805
|
group: r.group,
|
|
783
|
-
description: r.description || '',
|
|
784
806
|
tags: Array.isArray(r.tags) ? r.tags : [],
|
|
785
807
|
body: snap.bodies.get(r.id) || '',
|
|
786
808
|
enabled: typeof over === 'boolean' ? over : r.enabled,
|
|
809
|
+
...(r.origin !== undefined ? { origin: r.origin } : {}),
|
|
787
810
|
};
|
|
788
811
|
});
|
|
789
812
|
const hits = searchMemories(docs, query, args && args.limit);
|
package/lib/ops/trash.js
CHANGED
|
@@ -77,7 +77,7 @@ export function buildTrashOps(rc) {
|
|
|
77
77
|
// 回去改名。所以拒绝时**连候选名字一起回**(`params.next`)—— 弹窗才能如实写出"确认后
|
|
78
78
|
// 会叫 `测(1)`"。用户点确认后带 `dedupe: true` 再来一次,这一次真的按退号的名字恢复。
|
|
79
79
|
//
|
|
80
|
-
// `dedupe` 是**可选入参、缺省即旧行为**:模型工具(
|
|
80
|
+
// `dedupe` 是**可选入参、缺省即旧行为**:模型工具(memory_get / memory_remember)走的是同一个 op,
|
|
81
81
|
// 它们依赖"撞名就拒"来决定新建还是更新,不能因为界面想要退号就改掉这条语义。
|
|
82
82
|
const conflict = await locateRule(manifest.group, manifest.name);
|
|
83
83
|
let name = manifest.name;
|
|
@@ -189,7 +189,19 @@ export function buildTrashOps(rc) {
|
|
|
189
189
|
catch { /* 内容缺失 */ }
|
|
190
190
|
}
|
|
191
191
|
}
|
|
192
|
-
|
|
192
|
+
const auto = manifest.auto === true;
|
|
193
|
+
entries.push({
|
|
194
|
+
trashId,
|
|
195
|
+
group,
|
|
196
|
+
name: manifest.name,
|
|
197
|
+
form,
|
|
198
|
+
deletedAt: String(manifest.deletedAt || ''),
|
|
199
|
+
bytes,
|
|
200
|
+
...(auto ? { auto: true } : {}),
|
|
201
|
+
...(auto && typeof manifest.autoId === 'string' ? { autoId: manifest.autoId } : {}),
|
|
202
|
+
...(auto && typeof manifest.autoLayer === 'string' ? { autoLayer: manifest.autoLayer } : {}),
|
|
203
|
+
...(auto && typeof manifest.autoStatus === 'string' ? { autoStatus: manifest.autoStatus } : {}),
|
|
204
|
+
});
|
|
193
205
|
}
|
|
194
206
|
catch { /* 损坏条目跳过 */ }
|
|
195
207
|
}
|
package/lib/prompts/service.js
CHANGED
|
@@ -37,6 +37,24 @@ const META_FILE = 'meta.json';
|
|
|
37
37
|
* 一句用户提示"),但那是两个各自独立的预算,别当成同一个常量共用。
|
|
38
38
|
*/
|
|
39
39
|
export const DEFAULT_PRESET_DESC_MAX_LENGTH = 300;
|
|
40
|
+
/**
|
|
41
|
+
* 预设正文的字节上限(256 KiB),与记忆注入总盘(`memories/constants.ts` 的 `DEFAULT_MAX_BYTES`)同档。
|
|
42
|
+
*
|
|
43
|
+
* 注意别与 `project-instructions.ts` 里同名的 `DEFAULT_MAX_BYTES`(64 KiB,单个指令文件上限)
|
|
44
|
+
* 搞混 —— 两个常量同名不同值,说的是两件事。
|
|
45
|
+
*
|
|
46
|
+
* 为什么需要:注入侧虽按 64 KiB 截断(`AGENTS_MD_MAX_BYTES`),但盘上可以无限大,
|
|
47
|
+
* 而每次读都要整份进内存。上限拦在**写**这一侧 —— 已存在的超大文件不阻断读取,
|
|
48
|
+
* 用户还能把它改小。
|
|
49
|
+
*/
|
|
50
|
+
export const MAX_PRESET_BYTES = 256 * 1024;
|
|
51
|
+
/** 正文超限时的拒绝回执;没超返回 null。 */
|
|
52
|
+
function presetTooLarge(content) {
|
|
53
|
+
const bytes = Buffer.byteLength(String(content ?? ''), 'utf8');
|
|
54
|
+
if (bytes <= MAX_PRESET_BYTES)
|
|
55
|
+
return null;
|
|
56
|
+
return { ok: false, error: `提示词正文过大(${bytes} 字节,上限 ${MAX_PRESET_BYTES >> 10} KiB)` };
|
|
57
|
+
}
|
|
40
58
|
/**
|
|
41
59
|
* 压成一行并按上限截断。与 `normalizeMcpNote`(`../mcp/state-section.ts`)同形:两处都是
|
|
42
60
|
* "给模型看的一句用户文字",口径必须一致,否则同一句在界面、段、工具里会是三个样子。
|
|
@@ -243,6 +261,10 @@ export function createPromptsService(_ctx, deps) {
|
|
|
243
261
|
content = BLANK_TEMPLATE;
|
|
244
262
|
}
|
|
245
263
|
}
|
|
264
|
+
// 判在 mkdir 之前:拒绝时磁盘上不留空目录。
|
|
265
|
+
const tooLarge = presetTooLarge(content);
|
|
266
|
+
if (tooLarge)
|
|
267
|
+
return tooLarge;
|
|
246
268
|
await mkdir(dir, { recursive: true });
|
|
247
269
|
await writeFileAtomically(join(dir, FILENAME), content);
|
|
248
270
|
await writeDescription(safeId, options?.description);
|
|
@@ -256,6 +278,10 @@ export function createPromptsService(_ctx, deps) {
|
|
|
256
278
|
const bad = idError(id);
|
|
257
279
|
if (bad)
|
|
258
280
|
return { ok: false, error: '非法 id:' + bad };
|
|
281
|
+
// 判在任何落盘之前:否则改名会先发生,正文却被拒,目录停在新 id 上。
|
|
282
|
+
const tooLarge = presetTooLarge(content);
|
|
283
|
+
if (tooLarge)
|
|
284
|
+
return tooLarge;
|
|
259
285
|
const safeId = String(id ?? '').trim();
|
|
260
286
|
const dir = join(deps.presetsDir, safeId);
|
|
261
287
|
try {
|
|
@@ -636,6 +662,10 @@ export function createPromptsService(_ctx, deps) {
|
|
|
636
662
|
return { ok: false, error: 'id 已存在:' + safeId };
|
|
637
663
|
}
|
|
638
664
|
catch { /* 不存在,继续 */ }
|
|
665
|
+
// 判在 mkdir 之前:拒绝时磁盘上不留空目录。
|
|
666
|
+
const tooLarge = presetTooLarge(content);
|
|
667
|
+
if (tooLarge)
|
|
668
|
+
return tooLarge;
|
|
639
669
|
await mkdir(dir, { recursive: true });
|
|
640
670
|
await writeFileAtomically(join(dir, FILENAME), String(content ?? ''));
|
|
641
671
|
await writeDescription(safeId, description);
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
// ——宁可少共享一层,也不截断一个路径键导致两个工作区撞在一起。
|
|
12
12
|
//
|
|
13
13
|
// 前缀 `ws:` 只用于本侧车;宿主会话 id 不会以它开头,真实会话 id 仍原样存在。
|
|
14
|
+
import { existsSync } from 'node:fs';
|
|
15
|
+
import { dirname, join } from 'node:path';
|
|
14
16
|
import { workspaceBaseName, workspacePathKey } from '../sessions/path-key.js';
|
|
15
17
|
/** 工作区作用域键的前缀。 */
|
|
16
18
|
export const WORKSPACE_SCOPE_PREFIX = 'ws:';
|
|
@@ -62,3 +64,40 @@ export function scopeKeyOfRow(row, mode) {
|
|
|
62
64
|
}
|
|
63
65
|
return row.id;
|
|
64
66
|
}
|
|
67
|
+
// ── 记忆层用的工作区身份 ───────────────────────────────────────────────────
|
|
68
|
+
/** cwd → 项目根:向上找 `.git`(文件或目录),最多 8 层;找不到就用 cwd 自己。 */
|
|
69
|
+
const rootCache = new Map();
|
|
70
|
+
export function workspaceRootOf(cwd) {
|
|
71
|
+
if (typeof cwd !== 'string' || cwd.trim() === '')
|
|
72
|
+
return undefined;
|
|
73
|
+
const cached = rootCache.get(cwd);
|
|
74
|
+
if (cached !== undefined)
|
|
75
|
+
return cached;
|
|
76
|
+
let cur = cwd;
|
|
77
|
+
let found = cwd;
|
|
78
|
+
for (let i = 0; i < 8; i++) {
|
|
79
|
+
if (existsSync(join(cur, '.git'))) {
|
|
80
|
+
found = cur;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
const parent = dirname(cur);
|
|
84
|
+
if (parent === cur || parent === '')
|
|
85
|
+
break;
|
|
86
|
+
cur = parent;
|
|
87
|
+
}
|
|
88
|
+
// 简单的上界:一个进程通常只碰几个项目,超过 256 条就整体清空(不做 LRU,代价不值得)。
|
|
89
|
+
if (rootCache.size > 256)
|
|
90
|
+
rootCache.clear();
|
|
91
|
+
rootCache.set(cwd, found);
|
|
92
|
+
return found;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* 记忆层用的工作区键:**先向上收敛到 git root**,再派生 `ws:` 键。
|
|
96
|
+
*
|
|
97
|
+
* 为什么不复用 `workspaceScopeKeyOf`:它直接吃 cwd(「作用域」页的现有口径,改了会让存量的
|
|
98
|
+
* 逐条开关全部失配)。记忆层是新数据,可以从一开始就用更稳的身份 —— 否则用户从 `/repo`
|
|
99
|
+
* 进到 `/repo/src`,刚学的项目事实就"消失"了,而他只会认为"记忆丢了"。
|
|
100
|
+
*/
|
|
101
|
+
export function workspaceMemoryKeyOf(cwd) {
|
|
102
|
+
return workspaceScopeKeyOf(workspaceRootOf(cwd));
|
|
103
|
+
}
|
package/lib/settings-sidecars.js
CHANGED
|
@@ -31,8 +31,8 @@ export function createSettingsSidecars(deps) {
|
|
|
31
31
|
// 注入设置(侧车 `inject-settings.json`,界面在「兼容」页):
|
|
32
32
|
// - underSuppressingPresets:压制型预设(persona complete / 关运行时上下文,如极简)
|
|
33
33
|
// 下是否仍然注入。默认 false = 跟随预设。
|
|
34
|
-
// - domains
|
|
35
|
-
// `InjectDomain.applicableTo
|
|
34
|
+
// - domains:各域开关(任何预设下都生效;界面六个勾选,两块记忆共用一个。深度判据不在这里 —— 见
|
|
35
|
+
// `InjectDomain.applicableTo`:场景与两块记忆只在顶层,子智能体目录按人设 catalogDepth)。
|
|
36
36
|
// 注入器每个 step 都要同步读一次设置 → 走 TTL 缓存;未加载时先给默认值并异步预热。
|
|
37
37
|
const INJECT_SETTINGS_FILE = 'inject-settings.json';
|
|
38
38
|
const INJECT_SETTINGS_TTL_MS = 3000;
|
package/lib/skills/dir-watch.js
CHANGED
|
@@ -4,21 +4,24 @@
|
|
|
4
4
|
// 写在它自己的注释里 —— Windows 上那条路会在目录被删除时静默卡死事件循环。
|
|
5
5
|
import { existsSync } from 'node:fs';
|
|
6
6
|
import { Worker } from 'node:worker_threads';
|
|
7
|
-
// ── 文件监听:外部改动自动失效 ────────────────────────────────────────────
|
|
8
7
|
/**
|
|
9
8
|
* 监听目录,200ms 防抖后回调:在编辑器或其他工具里新增/修改/删除文件后,无需手动
|
|
10
|
-
*
|
|
9
|
+
* 刷新即可看到变化。技能来源与记忆根目录共用。
|
|
11
10
|
*
|
|
12
11
|
* 为什么用 worker_threads:Windows 上 fs.watch(recursive) 的句柄在「被监听
|
|
13
12
|
* 目录被删除」时会静默卡死事件循环(不触发 error、unref 也无效)——宿主
|
|
14
13
|
* 进程将永远无法退出。把 watcher 放进独立的 worker 线程,主线程对 worker
|
|
15
14
|
* unref(),无论目录发生什么,宿主与测试进程都能正常收尾;worker 内部失败
|
|
16
|
-
*
|
|
15
|
+
* 也不影响主线程。目录不存在或平台不支持递归监听时静默跳过(`attached: false`)。
|
|
16
|
+
*
|
|
17
|
+
* 已知边界:worker 崩溃或某个目录监听失败**不会**回报(它只是少了一条变化通知)。
|
|
18
|
+
* 所以依赖 `attached` 做缓存的调用方必须再叠一层 TTL —— 把"监听还在"当成前提,
|
|
19
|
+
* 静默失效就会变成永久返回旧内容。
|
|
17
20
|
*/
|
|
18
21
|
export function watchDirectories(paths, invalidate) {
|
|
19
22
|
const valid = paths.filter((dir) => dir && existsSync(dir));
|
|
20
23
|
if (!valid.length)
|
|
21
|
-
return () => { };
|
|
24
|
+
return { dispose: () => { }, attached: () => false };
|
|
22
25
|
let timer = null;
|
|
23
26
|
const fire = () => {
|
|
24
27
|
if (timer)
|
|
@@ -32,40 +35,64 @@ export function watchDirectories(paths, invalidate) {
|
|
|
32
35
|
}, 200);
|
|
33
36
|
};
|
|
34
37
|
let worker = null;
|
|
38
|
+
let attached = false;
|
|
35
39
|
try {
|
|
36
40
|
// eval 模式内联 worker 代码:无需额外文件与构建步骤。worker 事件循环独立,
|
|
37
41
|
// 主线程 unref 后完全不参与宿主进程的退出判定。
|
|
38
42
|
const src = `
|
|
39
43
|
const { watch } = require('node:fs');
|
|
40
44
|
const { parentPort, workerData } = require('node:worker_threads');
|
|
45
|
+
let live = 0;
|
|
41
46
|
for (const dir of workerData.paths) {
|
|
42
47
|
try {
|
|
43
|
-
|
|
48
|
+
// persistent: true 是必需的:worker 里若唯一的句柄是 non-persistent 的 watch,
|
|
49
|
+
// 事件循环当场空掉、worker 自己退出 —— 消息一条都收不到(实测)。不挡宿主退出
|
|
50
|
+
// 靠的是主线程对 worker 的 unref(),不是这里的 persistent。
|
|
51
|
+
const w = watch(dir, { recursive: true, persistent: true }, () => {
|
|
44
52
|
try { parentPort.postMessage('change') } catch { /* worker 正在关闭 */ }
|
|
45
53
|
});
|
|
46
54
|
w.on('error', () => { /* 目录被移除等:忽略,不向主线程传播 */ });
|
|
55
|
+
live += 1;
|
|
47
56
|
} catch { /* 不可监听(权限/平台)时跳过该目录 */ }
|
|
48
57
|
}
|
|
58
|
+
parentPort.postMessage({ attached: live > 0 });
|
|
49
59
|
`;
|
|
50
|
-
|
|
60
|
+
// `execArgv: []` 是必需的,不是洁癖:worker 默认**继承**父进程的 execArgv,
|
|
61
|
+
// 而 eval 模式的代码是 CommonJS(用了 `require`)。父进程若带着 `--input-type=module`
|
|
62
|
+
// (`node -e` / 测试用 `--input-type` 跑),那段代码会被当成 ESM 求值,
|
|
63
|
+
// `require is not defined` —— 表现为"监听静默没挂上",而这里的所有失败都是静默的。
|
|
64
|
+
worker = new Worker(src, { eval: true, workerData: { paths: valid }, execArgv: [] });
|
|
51
65
|
worker.unref();
|
|
52
|
-
worker.on('message', () =>
|
|
53
|
-
|
|
66
|
+
worker.on('message', (msg) => {
|
|
67
|
+
if (msg && typeof msg === 'object' && 'attached' in msg) {
|
|
68
|
+
attached = msg.attached === true;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
fire();
|
|
72
|
+
});
|
|
73
|
+
// 崩溃 / 意外退出必须把 `attached` 降回 false:否则调用方会一直以为监听还挂着,
|
|
74
|
+
// 只靠 TTL 兜底,而重试逻辑(见记忆服务的 `ensureMemoriesWatch`)永远等不到复活机会。
|
|
75
|
+
// `dispose()` 先 `removeAllListeners()`,所以主动终止不会走到这里。
|
|
76
|
+
worker.on('error', () => { attached = false; });
|
|
77
|
+
worker.on('exit', () => { attached = false; });
|
|
54
78
|
}
|
|
55
|
-
catch { /* worker
|
|
56
|
-
return
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
timer
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
worker
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
79
|
+
catch { /* worker 不可用时静默跳过,功能退化为依赖调用方自己的 TTL */ }
|
|
80
|
+
return {
|
|
81
|
+
attached: () => attached,
|
|
82
|
+
dispose: () => {
|
|
83
|
+
if (timer) {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
timer = null;
|
|
86
|
+
}
|
|
87
|
+
if (worker) {
|
|
88
|
+
const w = worker;
|
|
89
|
+
worker = null;
|
|
90
|
+
try {
|
|
91
|
+
w.removeAllListeners();
|
|
92
|
+
w.terminate();
|
|
93
|
+
}
|
|
94
|
+
catch { /* ignore */ }
|
|
67
95
|
}
|
|
68
|
-
|
|
69
|
-
}
|
|
96
|
+
},
|
|
70
97
|
};
|
|
71
98
|
}
|