pi-ate-memory 1.2.0 → 1.3.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/README.md +3 -3
- package/lib/read-tracker.ts +5 -0
- package/lib/routing-register.ts +42 -50
- package/lib/routing.ts +171 -129
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -242,11 +242,11 @@ extensions/memory/
|
|
|
242
242
|
批量判定路由器:AI 叙述(text 块)计满 N 条 → LLM 判定与哪些**未读**记忆/spec 强相关 → steer 注入指路。
|
|
243
243
|
|
|
244
244
|
```jsonc
|
|
245
|
-
// settings.json(可选;缺省 enabled=true/
|
|
246
|
-
"memoryRouting": { "enabled": true, "
|
|
245
|
+
// settings.json(可选;缺省 enabled=true/batchChars=1200/includeSpecs=true)
|
|
246
|
+
"memoryRouting": { "enabled": true, "batchChars": 1200, "includeSpecs": true, "judgeModel": "" }
|
|
247
247
|
```
|
|
248
248
|
|
|
249
|
-
- `/memory-routing` — 查看当前配置;`/memory-routing
|
|
249
|
+
- `/memory-routing` — 查看当前配置;`/memory-routing 1500` 改字符阈值(200–20000);`on/off` 开关(N/on/off 持久化 settings.json,与生态 /aging-config 同形态;读仍三层合并支持项目级覆盖)
|
|
250
250
|
- 防护:白名单容错匹配(幻觉路径丢弃,max 3)、sha1 幂等、fail-open、已读剔除、已提醒未读标注自降权
|
|
251
251
|
- 判定日志:`~/.pi/agent/logs/memory-routing-llmjudge.log`
|
|
252
252
|
|
package/lib/read-tracker.ts
CHANGED
package/lib/routing-register.ts
CHANGED
|
@@ -1,67 +1,59 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* 核心路由器见 routing.ts。
|
|
2
|
+
* routing 扩展接线:事件钩子(message_end/tool_execution_start/tool_result)+ 命令注册
|
|
4
3
|
*/
|
|
5
|
-
import { mkdirSync, appendFileSync } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
7
4
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
|
-
import { MemoryRouter,
|
|
9
|
-
|
|
10
|
-
const AGENT_DIR = process.env.PI_AGENT_DIR ?? join(process.env.HOME ?? "", ".pi", "agent");
|
|
11
|
-
|
|
12
|
-
function appendRunLog(line: string): void {
|
|
13
|
-
try {
|
|
14
|
-
mkdirSync(join(AGENT_DIR, "logs"), { recursive: true });
|
|
15
|
-
appendFileSync(
|
|
16
|
-
join(AGENT_DIR, "logs", "memory-routing.log"),
|
|
17
|
-
`${new Date().toISOString()} ${line}\n`,
|
|
18
|
-
);
|
|
19
|
-
} catch {
|
|
20
|
-
// 日志失败不影响主流程
|
|
21
|
-
}
|
|
22
|
-
}
|
|
5
|
+
import { MemoryRouter, loadConfig, setRoutingConfig } from "./routing";
|
|
23
6
|
|
|
24
7
|
export function registerRouting(pi: ExtensionAPI): void {
|
|
25
|
-
const
|
|
26
|
-
const
|
|
8
|
+
const cfg = loadConfig(process.cwd());
|
|
9
|
+
const router = new MemoryRouter(process.cwd(), cfg);
|
|
10
|
+
const pendingTools = new Map<string, { toolName: string; args: unknown }>();
|
|
11
|
+
|
|
27
12
|
pi.on("message_end", async (event: unknown, ctx: unknown) => {
|
|
28
|
-
|
|
29
|
-
router.
|
|
30
|
-
await router.maybeTrigger(pi);
|
|
13
|
+
router.accumulate(event as { message?: { content?: unknown } });
|
|
14
|
+
void router.maybeTrigger(pi);
|
|
31
15
|
});
|
|
16
|
+
|
|
32
17
|
pi.on("tool_execution_start", (event: unknown) => {
|
|
33
|
-
const { toolName, args, toolCallId } = event as {
|
|
34
|
-
|
|
35
|
-
};
|
|
36
|
-
if (toolName === "read" && toolCallId) pendingTools.set(toolCallId, args);
|
|
18
|
+
const { toolName, args, toolCallId } = event as { toolName?: string; args?: unknown; toolCallId?: string };
|
|
19
|
+
if (toolName && toolCallId) pendingTools.set(toolCallId, { toolName, args });
|
|
37
20
|
});
|
|
21
|
+
|
|
38
22
|
pi.on("tool_result", (event: unknown) => {
|
|
39
|
-
const { toolCallId, isError } = event as { toolCallId?: string; isError?: boolean };
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
pendingTools.delete(toolCallId);
|
|
43
|
-
|
|
23
|
+
const { toolCallId, isError, result } = event as { toolCallId?: string; isError?: boolean; result?: unknown };
|
|
24
|
+
const rec = toolCallId ? pendingTools.get(toolCallId) : undefined;
|
|
25
|
+
if (!rec) return;
|
|
26
|
+
pendingTools.delete(toolCallId!);
|
|
27
|
+
router.observeToolResult(rec.toolName, rec.args, isError === true, result);
|
|
28
|
+
router.readTracker.recordRead(rec.toolName ?? "", rec.args, isError === true);
|
|
44
29
|
});
|
|
30
|
+
|
|
45
31
|
pi.registerCommand("memory-routing", {
|
|
46
|
-
handler: async (rawArgs: string, ctx) => {
|
|
32
|
+
handler: async (rawArgs: string, ctx: unknown) => {
|
|
33
|
+
const notify = (text: string) => (ctx as { ui?: { notify?: (t: string, l?: string) => void } }).ui?.notify?.(text, "info");
|
|
47
34
|
const sub = rawArgs.trim();
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
notify(
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
35
|
+
if (sub === "" || sub === "status") {
|
|
36
|
+
const c = router.config;
|
|
37
|
+
notify(`memoryRouting: enabled=${c.enabled} batchChars=${c.batchChars} includeSpecs=${c.includeSpecs}\n用法: /memory-routing [N|on|off](N=字符阈值)`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (sub === "on" || sub === "off") {
|
|
41
|
+
const enabled = sub === "on";
|
|
42
|
+
const updated = setRoutingConfig({ enabled });
|
|
43
|
+
router.config = updated;
|
|
44
|
+
router.setEnabled(enabled);
|
|
45
|
+
notify(`✅ memoryRouting.enabled = ${updated.enabled}(已持久化 settings.json)`);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const n = Number.parseInt(sub, 10);
|
|
49
|
+
if (Number.isFinite(n) && n >= 200 && n <= 20000) {
|
|
50
|
+
const updated = setRoutingConfig({ batchChars: n });
|
|
51
|
+
router.config = updated;
|
|
52
|
+
notify(`✅ memoryRouting.batchChars = ${updated.batchChars}(已持久化 settings.json)`);
|
|
53
|
+
return;
|
|
62
54
|
}
|
|
55
|
+
notify(`无效参数「${sub}」:N(200-20000 字符阈值)| on | off | status`);
|
|
63
56
|
},
|
|
64
|
-
description: "
|
|
57
|
+
description: "记忆路由:查看/设置字符阈值与开关",
|
|
65
58
|
});
|
|
66
|
-
appendRunLog("routing registered");
|
|
67
59
|
}
|
package/lib/routing.ts
CHANGED
|
@@ -1,160 +1,202 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* 记忆路由核心:三信号源积累 → 字符池批式触发 → LLM 主题关键词标注 → 程序匹配资产 → ephemeral 提醒(不进 session 历史)
|
|
3
|
+
* 方案:openspec/changes/memory-routing(v2.1 定稿)
|
|
4
4
|
*/
|
|
5
|
-
import {
|
|
6
|
-
import { join } from "node:path";
|
|
7
|
-
import { getEffectiveConfig } from "@pi-atelier/shared-utils";
|
|
8
|
-
import { createJudge } from "@pi-atelier/shared-utils/judge";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
9
6
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
} from "./asset-catalog";
|
|
15
|
-
import { ReadTracker, filterVerdictPaths } from "./read-tracker";
|
|
16
|
-
|
|
17
|
-
const AGENT_DIR = process.env.PI_AGENT_DIR ?? join(process.env.HOME ?? "", ".pi", "agent");
|
|
18
|
-
const JUDGE_LOG = join(AGENT_DIR, "logs", "memory-routing-llmjudge.log");
|
|
19
|
-
const lastBatchHashes: string[] = [];
|
|
20
|
-
const DEDUP_WINDOW = 3;
|
|
7
|
+
import { createJudge } from "@pi-atelier/shared-utils/judge";
|
|
8
|
+
import { getEffectiveConfig, patchSettingsSection } from "@pi-atelier/shared-utils";
|
|
9
|
+
import { collectMemoryAssets, collectSpecAssets, type KnowledgeAsset } from "./asset-catalog";
|
|
10
|
+
import { createReadTracker, filterVerdictPaths } from "./read-tracker";
|
|
21
11
|
|
|
22
12
|
export interface RoutingConfig {
|
|
23
13
|
enabled: boolean;
|
|
24
|
-
|
|
14
|
+
batchChars: number;
|
|
25
15
|
includeSpecs: boolean;
|
|
26
16
|
judgeModel: string;
|
|
27
17
|
}
|
|
28
18
|
|
|
19
|
+
const DEFAULTS: RoutingConfig = { enabled: true, batchChars: 1200, includeSpecs: true, judgeModel: "" };
|
|
20
|
+
|
|
21
|
+
const NARRATIVE_CAP = 6000; // 叙事窗口上限(截尾防撑爆)
|
|
22
|
+
/** 单信号行截断 */
|
|
23
|
+
const LINE_CAP = 2000;
|
|
24
|
+
|
|
25
|
+
const SYSTEM_PROMPT =
|
|
26
|
+
"你是主题标注器。阅读 AI 工作记录(含 [叙述]/[tool]/[tool✗] 三类标签行,报错信号已在行内)," +
|
|
27
|
+
"提炼其涉及的核心主题关键词(技术域/工具名/问题类型/报错特征),每行一个,最多 5 个。" +
|
|
28
|
+
"只输出关键词本身,不要解释、不要编号、不要路径、不要标点符号前后缀。" +
|
|
29
|
+
"没有明确技术主题时只输出:无";
|
|
30
|
+
|
|
29
31
|
export function loadConfig(cwd: string): RoutingConfig {
|
|
30
|
-
const {
|
|
31
|
-
|
|
32
|
-
{ enabled: true, batchSize: 5, includeSpecs: true, judgeModel: "" },
|
|
33
|
-
cwd,
|
|
34
|
-
);
|
|
35
|
-
return {
|
|
36
|
-
enabled: config.enabled !== false,
|
|
37
|
-
batchSize: Math.max(1, Number(config.batchSize) || 5),
|
|
38
|
-
includeSpecs: config.includeSpecs !== false,
|
|
39
|
-
judgeModel: String(config.judgeModel ?? ""),
|
|
40
|
-
};
|
|
32
|
+
const r = getEffectiveConfig("memoryRouting", { ...DEFAULTS }, cwd) as { config?: Partial<RoutingConfig> };
|
|
33
|
+
return { ...DEFAULTS, ...(r.config ?? {}) };
|
|
41
34
|
}
|
|
42
35
|
|
|
43
|
-
const SYSTEM_PROMPT =
|
|
44
|
-
"你是知识资产路由判定器。根据会话最近的 AI 叙述,判断与哪些【未读】资产强相关。\n" +
|
|
45
|
-
"输出格式:每行一个路径(逐字取自清单),最多 3 条;无相关则只输出「无」。\n" +
|
|
46
|
-
"规则:只推荐未读条目;提醒 2+ 次仍未读的条目不再推荐;路径禁止构造,必须逐字来自清单。";
|
|
47
36
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
37
|
+
|
|
38
|
+
export function setRoutingConfig(patch: Partial<RoutingConfig>): RoutingConfig {
|
|
39
|
+
return patchSettingsSection<RoutingConfig>("memoryRouting", patch, DEFAULTS);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 判定输出解析:词级容错(分隔符拆分 + 短词过滤),返回 null=判定作废 */
|
|
43
|
+
export function parseKeywords(raw: string): string[] | null {
|
|
44
|
+
const lines = raw.trim().split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
51
45
|
if (lines.length === 1 && /^(无|none|n\/a)$/i.test(lines[0])) return [];
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
46
|
+
const out: string[] = [];
|
|
47
|
+
for (const line of lines) {
|
|
48
|
+
const toks = line.split(/[\s,,、;;|]+/).filter((t) => t.length >= 2 && t.length <= 40);
|
|
49
|
+
for (const t of toks.slice(0, 3)) if (!out.includes(t)) out.push(t);
|
|
50
|
+
}
|
|
51
|
+
return out.length ? out.slice(0, 5) : null;
|
|
55
52
|
}
|
|
56
53
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
});
|
|
54
|
+
/** 关键词 × 资产元数据匹配(substring 双向:hay 含 kw,或 kw 含资产主词) */
|
|
55
|
+
export function matchAssets(keywords: string[], assets: KnowledgeAsset[]): KnowledgeAsset[] {
|
|
56
|
+
const kws = keywords.map((k) => k.trim().toLowerCase()).filter((k) => k.length >= 2);
|
|
57
|
+
const hits: KnowledgeAsset[] = [];
|
|
58
|
+
for (const a of assets) {
|
|
59
|
+
const stem = (a.entry.split("/").pop() ?? "").split("--")[0].toLowerCase();
|
|
60
|
+
const hay = `${a.entry}\n${a.desc}`.toLowerCase();
|
|
61
|
+
const hit = kws.some((k) => hay.includes(k) || (stem.length >= 3 && k.includes(stem)));
|
|
62
|
+
if (hit && !hits.some((h) => h.entry === a.entry)) hits.push(a);
|
|
63
|
+
}
|
|
64
|
+
return hits;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 工具调用参数摘要:bash 取 command,read/edit 取 path,其余 JSON 截断 */
|
|
68
|
+
function summarizeToolCall(toolName: string, args: unknown): string {
|
|
69
|
+
const a = (args ?? {}) as Record<string, unknown>;
|
|
70
|
+
if (typeof a.command === "string") return `${toolName}: ${a.command.slice(0, LINE_CAP)}`;
|
|
71
|
+
if (typeof a.path === "string") return `${toolName}: ${a.path}`;
|
|
72
|
+
try {
|
|
73
|
+
return `${toolName}: ${JSON.stringify(a).slice(0, 150)}`;
|
|
74
|
+
} catch {
|
|
75
|
+
return `${toolName}: [unserializable args]`;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 报错内容摘要(头部特征码) */
|
|
80
|
+
export function summarizeToolError(result: unknown): string {
|
|
81
|
+
let text = "";
|
|
82
|
+
if (typeof result === "string") text = result;
|
|
83
|
+
else if (result && typeof result === "object") {
|
|
84
|
+
const r = result as Record<string, unknown>;
|
|
85
|
+
if (typeof r.error === "string") text = r.error;
|
|
86
|
+
else if (typeof r.output === "string") text = r.output;
|
|
87
|
+
else {
|
|
88
|
+
try {
|
|
89
|
+
text = JSON.stringify(result);
|
|
90
|
+
} catch {
|
|
91
|
+
text = "[unserializable]";
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return text.slice(0, LINE_CAP);
|
|
96
|
+
}
|
|
64
97
|
|
|
65
98
|
export class MemoryRouter {
|
|
99
|
+
readonly cwd: string;
|
|
100
|
+
readonly readTracker = createReadTracker();
|
|
101
|
+
config: RoutingConfig;
|
|
66
102
|
private buffer: string[] = [];
|
|
67
|
-
private
|
|
68
|
-
private
|
|
69
|
-
private
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
constructor(cwd: string, config?: RoutingConfig) {
|
|
103
|
+
private charCount = 0;
|
|
104
|
+
private judgedBatches = new Set<string>();
|
|
105
|
+
private judge: ReturnType<typeof createJudge<string[]>> | null = null;
|
|
106
|
+
|
|
107
|
+
constructor(cwd: string, config?: Partial<RoutingConfig>) {
|
|
73
108
|
this.cwd = cwd;
|
|
74
|
-
this.config = config
|
|
75
|
-
}
|
|
76
|
-
get enabled(): boolean { return this.config.enabled; }
|
|
77
|
-
setConfig(patch: Partial<RoutingConfig>): void {
|
|
78
|
-
this.config = { ...this.config, ...patch };
|
|
109
|
+
this.config = { ...DEFAULTS, ...config };
|
|
79
110
|
}
|
|
80
|
-
|
|
81
|
-
|
|
111
|
+
|
|
112
|
+
/** message_end:叙述 + 工具调用摘要入池(D3 三信号源) */
|
|
113
|
+
accumulate(event: { message?: { content?: unknown } }): void {
|
|
82
114
|
if (!this.config.enabled) return;
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
typeof b === "
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
115
|
+
const blocks = Array.isArray(event.message?.content) ? (event.message!.content as Array<Record<string, unknown>>) : [];
|
|
116
|
+
for (const b of blocks) {
|
|
117
|
+
if (b.type === "text" && typeof b.text === "string" && b.text.trim()) {
|
|
118
|
+
this.push(`[叙述] ${b.text.slice(0, LINE_CAP)}`);
|
|
119
|
+
} else if (b.type === "toolCall") {
|
|
120
|
+
const name = typeof b.name === "string" ? b.name : "tool";
|
|
121
|
+
this.push(`[tool] ${summarizeToolCall(name, b.arguments)}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** tool_result:仅报错入池(成功结果体积大信号弱不进) */
|
|
127
|
+
observeToolResult(toolName: string, args: unknown, isError: boolean, result: unknown): void {
|
|
128
|
+
if (!this.config.enabled || !isError) return;
|
|
129
|
+
this.push(`[tool✗] ${summarizeToolError(result)}`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private push(line: string): void {
|
|
133
|
+
this.buffer.push(line);
|
|
134
|
+
this.charCount += line.length;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private takeBatch(): { lines: string[]; chars: number } | null {
|
|
138
|
+
if (this.charCount < this.config.batchChars) return null;
|
|
139
|
+
const lines = this.buffer.splice(0);
|
|
140
|
+
const chars = this.charCount;
|
|
141
|
+
this.charCount = 0;
|
|
142
|
+
return { lines, chars };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private ensureJudge() {
|
|
146
|
+
if (this.judge) return this.judge;
|
|
147
|
+
this.judge = createJudge<string[]>({
|
|
148
|
+
label: "memory-routing",
|
|
149
|
+
systemPrompt: SYSTEM_PROMPT,
|
|
150
|
+
parse: parseKeywords,
|
|
151
|
+
judgeLogPath: "C:/Users/Administrator/.pi/agent/logs/memory-routing-llmjudge.log",
|
|
152
|
+
legacySectionKeys: ["memoryRouting", "shepherd"],
|
|
153
|
+
});
|
|
154
|
+
return this.judge;
|
|
94
155
|
}
|
|
95
|
-
|
|
96
|
-
async maybeTrigger(pi
|
|
156
|
+
|
|
157
|
+
async maybeTrigger(pi: ExtensionAPI): Promise<void> {
|
|
97
158
|
if (!this.config.enabled) return;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
this.seen = 0;
|
|
159
|
+
const batch = this.takeBatch();
|
|
160
|
+
if (!batch) return;
|
|
101
161
|
try {
|
|
102
|
-
|
|
162
|
+
const narrative = batch.lines.join("\n").slice(-NARRATIVE_CAP);
|
|
163
|
+
const hash = Buffer.from(narrative).toString("base64").slice(0, 8);
|
|
164
|
+
if (this.judgedBatches.has(hash)) return;
|
|
165
|
+
this.judgedBatches.add(hash);
|
|
166
|
+
if (this.judgedBatches.size > 50) this.judgedBatches.clear();
|
|
167
|
+
|
|
168
|
+
const assets: KnowledgeAsset[] = collectMemoryAssets(this.cwd);
|
|
169
|
+
if (this.config.includeSpecs) assets.push(...collectSpecAssets(this.cwd));
|
|
170
|
+
if (assets.length === 0) return;
|
|
171
|
+
|
|
172
|
+
const keywords = await this.ensureJudge().judge({
|
|
173
|
+
question: "标注这批工作记录的主题关键词(每行一个,≤5 个)",
|
|
174
|
+
text: narrative,
|
|
175
|
+
contextLabel: `batch-${hash}(${batch.chars}字)`,
|
|
176
|
+
model: this.config.judgeModel || undefined,
|
|
177
|
+
});
|
|
178
|
+
if (!keywords || keywords.length === 0) return;
|
|
179
|
+
|
|
180
|
+
const hits = matchAssets(keywords, assets);
|
|
181
|
+
const validEntries = filterVerdictPaths(hits.map((a) => a.entry), assets.map((a) => a.entry));
|
|
182
|
+
const candidates = hits
|
|
183
|
+
.filter((a) => validEntries.includes(a.entry))
|
|
184
|
+
.filter((a) => !this.readTracker.hasRead(a.entry))
|
|
185
|
+
.slice(0, 3);
|
|
186
|
+
if (candidates.length === 0) return;
|
|
187
|
+
|
|
188
|
+
const lines = candidates.map((a) => `- ${a.entry}(${a.desc.slice(0, 60)})`).join("\n");
|
|
189
|
+
const stems = candidates.map((a) => (a.entry.split("/").pop() ?? "").split("--")[0]).join("、");
|
|
190
|
+
pi.events.emit("ephemeral:hint", {
|
|
191
|
+
text: `💡 记忆路由:本段工作与以下知识资产相关(你尚未读过):\n${lines}\n如相关请 read;无关可忽略。`,
|
|
192
|
+
short: `💡 记忆路由:${stems}`,
|
|
193
|
+
});
|
|
103
194
|
} catch {
|
|
104
|
-
|
|
195
|
+
/* fail-open */
|
|
105
196
|
}
|
|
106
197
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
if (lastBatchHashes.includes(hash)) return; // 幂等
|
|
111
|
-
lastBatchHashes.push(hash);
|
|
112
|
-
if (lastBatchHashes.length > DEDUP_WINDOW) lastBatchHashes.shift();
|
|
113
|
-
const assets = [
|
|
114
|
-
...collectMemoryAssets(this.cwd),
|
|
115
|
-
...(this.config.includeSpecs ? collectSpecAssets(this.cwd) : []),
|
|
116
|
-
];
|
|
117
|
-
const candidates = assets.filter((a) => !this.readTracker.hasRead(a.entry));
|
|
118
|
-
if (candidates.length === 0) return;
|
|
119
|
-
const catalog = candidates
|
|
120
|
-
.map((a: KnowledgeAsset) => {
|
|
121
|
-
const n = this.remindedCount.get(a.entry) ?? 0;
|
|
122
|
-
const noted = n > 0 ? `(已提醒 ${n} 次未读)` : "";
|
|
123
|
-
const kind = a.entry.startsWith("openspec/") ? "spec" : "memory";
|
|
124
|
-
return `- ${a.entry}${noted} [${kind}] ${a.desc}`;
|
|
125
|
-
})
|
|
126
|
-
.join("\n");
|
|
127
|
-
const paths = await routingJudge.judge({
|
|
128
|
-
question: "判断这批 AI 叙述与哪些未读知识资产强相关,输出路径清单",
|
|
129
|
-
text: `【最近 AI 叙述】\n${narrative}\n\n【未读资产清单】\n${catalog}`,
|
|
130
|
-
contextLabel: `batch-${hash.slice(0, 8)}(${batch.length}条)`,
|
|
131
|
-
model: this.config.judgeModel || undefined,
|
|
132
|
-
});
|
|
133
|
-
if (!paths || paths.length === 0) return;
|
|
134
|
-
// 白名单校验:尾段容错匹配,仅留清单内路径,其余(幻觉)丢弃(specs §1.4)
|
|
135
|
-
const validEntries = filterVerdictPaths(paths, candidates.map((a) => a.entry));
|
|
136
|
-
if (validEntries.length === 0) return;
|
|
137
|
-
const valid = candidates.filter((a) => validEntries.includes(a.entry));
|
|
138
|
-
for (const a of valid) {
|
|
139
|
-
this.remindedCount.set(a.entry, (this.remindedCount.get(a.entry) ?? 0) + 1);
|
|
140
|
-
}
|
|
141
|
-
if (pi) {
|
|
142
|
-
const lines = valid
|
|
143
|
-
.map((a) =>
|
|
144
|
-
`- ${a.entry}(${a.entry.startsWith("openspec/") ? "规格" : "判例/记忆"}:${a.desc})`)
|
|
145
|
-
.join("\n");
|
|
146
|
-
pi.sendMessage(
|
|
147
|
-
{
|
|
148
|
-
customType: "memory-routing",
|
|
149
|
-
content: `💡 记忆路由:本段工作与以下知识资产相关(你尚未读过):\n${lines}\n如相关请 read;无关可忽略。`,
|
|
150
|
-
display: true,
|
|
151
|
-
},
|
|
152
|
-
{ deliverAs: "steer" },
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
/** read 成功对账回调(routing-register 的 tool 双事件对账后调用) */
|
|
157
|
-
recordRead(toolName: string, args: unknown, isError: boolean): void {
|
|
158
|
-
this.readTracker.recordRead(toolName, args, isError);
|
|
198
|
+
|
|
199
|
+
setEnabled(v: boolean): void {
|
|
200
|
+
this.config.enabled = v;
|
|
159
201
|
}
|
|
160
202
|
}
|