pi-ate-memory 1.3.0 → 1.3.2

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.
@@ -0,0 +1,41 @@
1
+ import type { KnowledgeAsset } from "./asset-catalog";
2
+
3
+ /** 资产元数据词表:记忆文件名 kw 段 / spec capability 名 */
4
+ export function kwOf(asset: KnowledgeAsset): string[] {
5
+ if (asset.entry.startsWith("openspec/")) {
6
+ const cap = asset.entry.split("/")[2] ?? "";
7
+ return cap ? [cap.toLowerCase()] : [];
8
+ }
9
+ const stem = asset.entry.split("/").pop() ?? "";
10
+ const kwPart = stem.replace(/\.md$/, "").split("--")[1] ?? "";
11
+ return kwPart.split(",").map((k) => k.trim().toLowerCase()).filter((k) => k.length >= 2);
12
+ }
13
+
14
+ /** 词库构建:全部资产词表去重(按长度降序,进判定 question,纯受限选择) */
15
+ export function buildVocabulary(assets: KnowledgeAsset[]): string[] {
16
+ const s = new Set<string>();
17
+ for (const a of assets) for (const k of kwOf(a)) s.add(k);
18
+ return [...s].sort((x, y) => y.length - x.length);
19
+ }
20
+
21
+ /** 判定输出解析:词级容错(分隔符拆分 + 短词过滤),返回 null=判定作废 */
22
+ export function parseKeywords(raw: string): string[] | null {
23
+ const lines = raw.trim().split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
24
+ if (lines.length === 1 && /^(无|none|n\/a)$/i.test(lines[0])) return [];
25
+ const out: string[] = [];
26
+ for (const line of lines) {
27
+ const toks = line.split(/[\s,,、;;|]+/).filter((t) => t.length >= 2 && t.length <= 40);
28
+ for (const t of toks.slice(0, 3)) if (!out.includes(t)) out.push(t);
29
+ }
30
+ return out.length ? out.slice(0, 5) : null;
31
+ }
32
+
33
+ /** 纯倒排匹配:选中词 ∈ 资产词表即命中(无自创兜底,desc 不参与匹配) */
34
+ export function matchAssets(keywords: string[], assets: KnowledgeAsset[]): KnowledgeAsset[] {
35
+ const kws = keywords.map((k) => k.trim().toLowerCase()).filter((k) => k.length >= 2);
36
+ const hits: KnowledgeAsset[] = [];
37
+ for (const a of assets) {
38
+ if (kwOf(a).some((k) => kws.includes(k)) && !hits.some((h) => h.entry === a.entry)) hits.push(a);
39
+ }
40
+ return hits;
41
+ }
@@ -10,6 +10,7 @@ export function registerRouting(pi: ExtensionAPI): void {
10
10
  const pendingTools = new Map<string, { toolName: string; args: unknown }>();
11
11
 
12
12
  pi.on("message_end", async (event: unknown, ctx: unknown) => {
13
+ if (ctx) router.setJudgeContext(ctx);
13
14
  router.accumulate(event as { message?: { content?: unknown } });
14
15
  void router.maybeTrigger(pi);
15
16
  });
@@ -40,8 +41,7 @@ export function registerRouting(pi: ExtensionAPI): void {
40
41
  if (sub === "on" || sub === "off") {
41
42
  const enabled = sub === "on";
42
43
  const updated = setRoutingConfig({ enabled });
43
- router.config = updated;
44
- router.setEnabled(enabled);
44
+ router.setConfig(updated);
45
45
  notify(`✅ memoryRouting.enabled = ${updated.enabled}(已持久化 settings.json)`);
46
46
  return;
47
47
  }
package/lib/routing.ts CHANGED
@@ -1,69 +1,41 @@
1
- /**
2
- * 记忆路由核心:三信号源积累 → 字符池批式触发 → LLM 主题关键词标注 → 程序匹配资产 → ephemeral 提醒(不进 session 历史)
3
- * 方案:openspec/changes/memory-routing(v2.1 定稿)
4
- */
5
- import { randomUUID } from "node:crypto";
6
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
- import { createJudge } from "@pi-atelier/shared-utils/judge";
8
2
  import { getEffectiveConfig, patchSettingsSection } from "@pi-atelier/shared-utils";
3
+ import { createJudge, type JudgeInstance } from "@pi-atelier/shared-utils/judge";
9
4
  import { collectMemoryAssets, collectSpecAssets, type KnowledgeAsset } from "./asset-catalog";
10
- import { createReadTracker, filterVerdictPaths } from "./read-tracker";
5
+ import { createReadTracker } from "./read-tracker";
6
+ import { buildVocabulary, matchAssets, parseKeywords } from "./keyword-routing";
11
7
 
8
+ /** 记忆路由配置(settings memoryRouting 段;judgeModel 缺省走共享三层链) */
12
9
  export interface RoutingConfig {
13
10
  enabled: boolean;
11
+ /** 判定触发字符阈值:叙述/工具摘要/报错共用字符池,满则判(tumbling window) */
14
12
  batchChars: number;
13
+ /** openspec specs 目录的 capability 进判定资产池 */
15
14
  includeSpecs: boolean;
15
+ /** 显式判定模型(缺省 = judgeModel 顶层/legacy/会话默认三层链) */
16
16
  judgeModel: string;
17
17
  }
18
18
 
19
19
  const DEFAULTS: RoutingConfig = { enabled: true, batchChars: 1200, includeSpecs: true, judgeModel: "" };
20
20
 
21
- const NARRATIVE_CAP = 6000; // 叙事窗口上限(截尾防撑爆)
22
21
  /** 单信号行截断 */
23
22
  const LINE_CAP = 2000;
24
23
 
25
24
  const SYSTEM_PROMPT =
26
- "你是主题标注器。阅读 AI 工作记录(含 [叙述]/[tool]/[tool✗] 三类标签行,报错信号已在行内)," +
27
- "提炼其涉及的核心主题关键词(技术域/工具名/问题类型/报错特征),每行一个,最多 5 个。" +
28
- "只输出关键词本身,不要解释、不要编号、不要路径、不要标点符号前后缀。" +
29
- "没有明确技术主题时只输出:无";
25
+ "你是主题路由标注器。你会收到一个主题词库和一段 AI 工作记录(含 [叙述]/[tool]/[tool✗] 三类标签行,报错信号已在行内)。" +
26
+ "你的任务:【只能从词库中选出】与工作记录最相关的主题关键词,每行一个,最多 5 个。" +
27
+ "禁止自创词库外的词;词库内确实无合适项时只输出:无。" +
28
+ "只输出词本身,不要解释、不要编号、不要标点符号前后缀。";
30
29
 
31
30
  export function loadConfig(cwd: string): RoutingConfig {
32
31
  const r = getEffectiveConfig("memoryRouting", { ...DEFAULTS }, cwd) as { config?: Partial<RoutingConfig> };
33
32
  return { ...DEFAULTS, ...(r.config ?? {}) };
34
33
  }
35
34
 
36
-
37
-
38
35
  export function setRoutingConfig(patch: Partial<RoutingConfig>): RoutingConfig {
39
36
  return patchSettingsSection<RoutingConfig>("memoryRouting", patch, DEFAULTS);
40
37
  }
41
38
 
42
- /** 判定输出解析:词级容错(分隔符拆分 + 短词过滤),返回 null=判定作废 */
43
- export function parseKeywords(raw: string): string[] | null {
44
- const lines = raw.trim().split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
45
- if (lines.length === 1 && /^(无|none|n\/a)$/i.test(lines[0])) return [];
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;
52
- }
53
-
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
39
  /** 工具调用参数摘要:bash 取 command,read/edit 取 path,其余 JSON 截断 */
68
40
  function summarizeToolCall(toolName: string, args: unknown): string {
69
41
  const a = (args ?? {}) as Record<string, unknown>;
@@ -72,66 +44,74 @@ function summarizeToolCall(toolName: string, args: unknown): string {
72
44
  try {
73
45
  return `${toolName}: ${JSON.stringify(a).slice(0, 150)}`;
74
46
  } catch {
75
- return `${toolName}: [unserializable args]`;
47
+ return toolName;
76
48
  }
77
49
  }
78
50
 
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);
51
+ /** 报错摘要:截 200 字头部(特征码区) */
52
+ function summarizeError(result: unknown): string {
53
+ const s = typeof result === "string" ? result : JSON.stringify(result);
54
+ return String(s).slice(0, 200);
96
55
  }
97
56
 
57
+ /**
58
+ * 记忆路由核心:字符池(三信号源)→ 计满批量判定(词表路由)→ 倒排匹配 →
59
+ * 未读过滤 → shepherd ephemeral:hint(不进 session 历史,无勿荐降权)。
60
+ */
98
61
  export class MemoryRouter {
99
- readonly cwd: string;
100
- readonly readTracker = createReadTracker();
101
62
  config: RoutingConfig;
102
63
  private buffer: string[] = [];
103
64
  private charCount = 0;
104
65
  private judgedBatches = new Set<string>();
105
- private judge: ReturnType<typeof createJudge<string[]>> | null = null;
66
+ private judgeInstance: JudgeInstance<string[]> | null = null;
67
+ private pendingCtx: unknown = null;
68
+
69
+ /** message_end 事件的 ExtensionContext —— judge 调 LLM 的必要通道,首个事件到达时注入 */
70
+ setJudgeContext(ctx: unknown): void {
71
+ this.pendingCtx = ctx;
72
+ if (this.judgeInstance) (this.judgeInstance as unknown as { setContext(c: unknown): void }).setContext(ctx);
73
+ }
74
+ readonly readTracker = createReadTracker();
75
+
76
+ constructor(private cwd: string, config: RoutingConfig) {
77
+ this.config = { ...config };
78
+ }
106
79
 
107
- constructor(cwd: string, config?: Partial<RoutingConfig>) {
108
- this.cwd = cwd;
109
- this.config = { ...DEFAULTS, ...config };
80
+ setConfig(cfg: RoutingConfig): void {
81
+ this.config = { ...cfg };
110
82
  }
111
83
 
112
- /** message_end:叙述 + 工具调用摘要入池(D3 三信号源) */
113
- accumulate(event: { message?: { content?: unknown } }): void {
114
- if (!this.config.enabled) return;
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)}`);
84
+ /** message_end:叙述(text 块)+ 工具摘要(toolCall 块)入池 */
85
+ accumulate(event: unknown): void {
86
+ try {
87
+ const msg = (event as { message?: { content?: unknown } }).message;
88
+ const blocks = Array.isArray(msg?.content) ? (msg.content as Array<Record<string, unknown>>) : [];
89
+ const lines: string[] = [];
90
+ for (const b of blocks) {
91
+ if (b.type === "text" && typeof b.text === "string" && b.text.trim()) {
92
+ lines.push(`[叙述] ${b.text.slice(0, LINE_CAP)}`);
93
+ } else if (b.type === "toolCall" && typeof b.name === "string") {
94
+ lines.push(`[tool] ${summarizeToolCall(b.name, b.arguments).slice(0, LINE_CAP)}`);
95
+ }
122
96
  }
97
+ this.push(lines);
98
+ } catch {
99
+ /* 信号提取失败静默 */
123
100
  }
124
101
  }
125
102
 
126
- /** tool_result:仅报错入池(成功结果体积大信号弱不进) */
103
+ /** tool_result:报错(isError)入池(成功结果体积大信号弱不入) */
127
104
  observeToolResult(toolName: string, args: unknown, isError: boolean, result: unknown): void {
128
- if (!this.config.enabled || !isError) return;
129
- this.push(`[tool✗] ${summarizeToolError(result)}`);
105
+ if (!isError) return;
106
+ this.push([`[tool✗] ${toolName} → ${summarizeError(result)}`]);
130
107
  }
131
108
 
132
- private push(line: string): void {
133
- this.buffer.push(line);
134
- this.charCount += line.length;
109
+ private push(lines: string[]): void {
110
+ for (const l of lines) {
111
+ this.buffer.push(l);
112
+ this.charCount += l.length;
113
+ }
114
+ if (this.charCount > 6000) this.buffer = this.buffer.slice(-10);
135
115
  }
136
116
 
137
117
  private takeBatch(): { lines: string[]; chars: number } | null {
@@ -143,34 +123,38 @@ export class MemoryRouter {
143
123
  }
144
124
 
145
125
  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;
126
+ if (!this.judgeInstance) {
127
+ this.judgeInstance = createJudge<string[]>({
128
+ label: "memory-routing",
129
+ systemPrompt: SYSTEM_PROMPT,
130
+ parse: parseKeywords,
131
+ judgeLogPath: `${process.env.USERPROFILE ?? process.env.HOME ?? ""}/.pi/agent/logs/memory-routing-llmjudge.log`,
132
+ legacySectionKeys: ["memoryRouting", "shepherd"],
133
+ });
134
+ if (this.pendingCtx != null) (this.judgeInstance as unknown as { setContext(c: unknown): void }).setContext(this.pendingCtx);
135
+ }
136
+ return this.judgeInstance;
155
137
  }
156
138
 
157
139
  async maybeTrigger(pi: ExtensionAPI): Promise<void> {
158
- if (!this.config.enabled) return;
159
140
  const batch = this.takeBatch();
160
141
  if (!batch) return;
142
+ const narrative = batch.lines.join("\n");
143
+ const hash = sha1Lite(narrative);
144
+ if (this.judgedBatches.has(hash)) return;
145
+ this.judgedBatches.add(hash);
146
+ if (this.judgedBatches.size > 50) this.judgedBatches.clear();
161
147
  try {
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
148
  const assets: KnowledgeAsset[] = collectMemoryAssets(this.cwd);
169
149
  if (this.config.includeSpecs) assets.push(...collectSpecAssets(this.cwd));
170
150
  if (assets.length === 0) return;
151
+ const vocab = buildVocabulary(assets);
152
+ if (vocab.length === 0) return;
171
153
 
172
154
  const keywords = await this.ensureJudge().judge({
173
- question: "标注这批工作记录的主题关键词(每行一个,≤5 个)",
155
+ question:
156
+ "从下方词库中【只能选不能创造】与本批工作记录最相关的主题关键词(每行一个,≤5 个,无合适输出“无”)。\n词库:" +
157
+ vocab.join("、"),
174
158
  text: narrative,
175
159
  contextLabel: `batch-${hash}(${batch.chars}字)`,
176
160
  model: this.config.judgeModel || undefined,
@@ -178,11 +162,7 @@ export class MemoryRouter {
178
162
  if (!keywords || keywords.length === 0) return;
179
163
 
180
164
  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);
165
+ const candidates = hits.filter((a) => !this.readTracker.hasRead(a.entry)).slice(0, 3);
186
166
  if (candidates.length === 0) return;
187
167
 
188
168
  const lines = candidates.map((a) => `- ${a.entry}(${a.desc.slice(0, 60)})`).join("\n");
@@ -195,8 +175,14 @@ export class MemoryRouter {
195
175
  /* fail-open */
196
176
  }
197
177
  }
178
+ }
198
179
 
199
- setEnabled(v: boolean): void {
200
- this.config.enabled = v;
180
+ /** 轻量 sha1(幂等去重用,非安全场景) */
181
+ function sha1Lite(s: string): string {
182
+ let h = 0x811c9dc5;
183
+ for (let i = 0; i < s.length; i++) {
184
+ h ^= s.charCodeAt(i);
185
+ h = Math.imul(h, 0x01000193) >>> 0;
201
186
  }
187
+ return h.toString(16).padStart(8, "0");
202
188
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ate-memory",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "File-based persistent memory for AI coding agents",
5
5
  "keywords": [
6
6
  "pi-package"