pi-ate-memory 1.0.0 → 1.2.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.en.md +8 -0
- package/README.md +22 -1
- package/index.ts +285 -198
- package/lib/asset-catalog.ts +63 -0
- package/lib/conflict-detect.ts +44 -38
- package/lib/memory-hook.ts +47 -37
- package/lib/memory-inject.ts +74 -72
- package/lib/memory-parser.ts +100 -95
- package/lib/read-tracker.ts +77 -0
- package/lib/routing-register.ts +67 -0
- package/lib/routing.ts +160 -0
- package/lib/types.ts +24 -32
- package/lib/writer.ts +68 -69
- package/package.json +63 -60
- package/prompts/update-description.md +1 -1
- package/tsconfig.json +10 -10
package/lib/conflict-detect.ts
CHANGED
|
@@ -1,38 +1,44 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Memory 冲突检测 — 同目录中 topic 或关键词重叠检查
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import * as fs from "node:fs";
|
|
6
|
-
import * as path from "node:path";
|
|
7
|
-
import { parseFileName } from "./memory-parser";
|
|
8
|
-
|
|
9
|
-
/** 检测同目录中与目标文件存在 topic 或关键词重叠的文件 */
|
|
10
|
-
export function detectConflicts(
|
|
11
|
-
dir: string,
|
|
12
|
-
newFileName: string,
|
|
13
|
-
newParsed: ReturnType<typeof parseFileName>,
|
|
14
|
-
): Array<{ name: string; reason: string }> {
|
|
15
|
-
const results: Array<{ name: string; reason: string }> = [];
|
|
16
|
-
const newKeywords = new Set(newParsed.keywords);
|
|
17
|
-
const newTopic = newParsed.topic;
|
|
18
|
-
|
|
19
|
-
for (const f of fs.readdirSync(dir)) {
|
|
20
|
-
if (!f.endsWith(".md") || f === "MEMORY.md" || f === newFileName) continue;
|
|
21
|
-
const existing = parseFileName(f);
|
|
22
|
-
if (!existing) continue;
|
|
23
|
-
|
|
24
|
-
// 同 topic → 冲突
|
|
25
|
-
if (existing.topic === newTopic) {
|
|
26
|
-
const lines = fs
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Memory 冲突检测 — 同目录中 topic 或关键词重叠检查
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { parseFileName } from "./memory-parser";
|
|
8
|
+
|
|
9
|
+
/** 检测同目录中与目标文件存在 topic 或关键词重叠的文件 */
|
|
10
|
+
export function detectConflicts(
|
|
11
|
+
dir: string,
|
|
12
|
+
newFileName: string,
|
|
13
|
+
newParsed: ReturnType<typeof parseFileName>,
|
|
14
|
+
): Array<{ name: string; reason: string }> {
|
|
15
|
+
const results: Array<{ name: string; reason: string }> = [];
|
|
16
|
+
const newKeywords = new Set(newParsed.keywords);
|
|
17
|
+
const newTopic = newParsed.topic;
|
|
18
|
+
|
|
19
|
+
for (const f of fs.readdirSync(dir)) {
|
|
20
|
+
if (!f.endsWith(".md") || f === "MEMORY.md" || f === newFileName) continue;
|
|
21
|
+
const existing = parseFileName(f);
|
|
22
|
+
if (!existing) continue;
|
|
23
|
+
|
|
24
|
+
// 同 topic → 冲突
|
|
25
|
+
if (existing.topic === newTopic) {
|
|
26
|
+
const lines = fs
|
|
27
|
+
.readFileSync(path.join(dir, f), "utf-8")
|
|
28
|
+
.split("\n").length;
|
|
29
|
+
results.push({ name: f, reason: `同topic, ${lines}行` });
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
// 关键词重叠 ≥ 3 → 冲突
|
|
33
|
+
const overlap = existing.keywords.filter((k: string) =>
|
|
34
|
+
newKeywords.has(k),
|
|
35
|
+
).length;
|
|
36
|
+
if (overlap >= 3) {
|
|
37
|
+
const lines = fs
|
|
38
|
+
.readFileSync(path.join(dir, f), "utf-8")
|
|
39
|
+
.split("\n").length;
|
|
40
|
+
results.push({ name: f, reason: `${overlap}关键词重叠, ${lines}行` });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return results;
|
|
44
|
+
}
|
package/lib/memory-hook.ts
CHANGED
|
@@ -1,37 +1,47 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Memory 注入 — before_agent_start hook 注册
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import * as fs from "node:fs";
|
|
6
|
-
import * as path from "node:path";
|
|
7
|
-
import type {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Memory 注入 — before_agent_start hook 注册
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import type {
|
|
8
|
+
BeforeAgentStartEvent,
|
|
9
|
+
BeforeAgentStartEventResult,
|
|
10
|
+
ExtensionAPI,
|
|
11
|
+
} from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { resolveMemoryInjection } from "./memory-inject";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 注册 before_agent_start hook:
|
|
16
|
+
* 1. 注入 memory-prompt.md 说明文本
|
|
17
|
+
* 2. 注入 L1/L2 MEMORY.md 索引内容
|
|
18
|
+
*/
|
|
19
|
+
export function registerMemoryHook(pi: ExtensionAPI): void {
|
|
20
|
+
const memoryPromptPath = path.join(__dirname, "..", "memory-prompt.md");
|
|
21
|
+
let memoryPrompt = "";
|
|
22
|
+
try {
|
|
23
|
+
if (fs.existsSync(memoryPromptPath)) {
|
|
24
|
+
memoryPrompt = fs.readFileSync(memoryPromptPath, "utf-8").trim();
|
|
25
|
+
}
|
|
26
|
+
} catch {
|
|
27
|
+
// 文件不存在或权限异常 → 跳过注入
|
|
28
|
+
/* ignore */
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (!memoryPrompt) return;
|
|
32
|
+
|
|
33
|
+
pi.on(
|
|
34
|
+
"before_agent_start",
|
|
35
|
+
async (
|
|
36
|
+
event: BeforeAgentStartEvent,
|
|
37
|
+
): Promise<BeforeAgentStartEventResult> => {
|
|
38
|
+
const cwd = event.systemPromptOptions?.cwd || process.cwd();
|
|
39
|
+
const injection = resolveMemoryInjection(cwd);
|
|
40
|
+
const parts = [memoryPrompt];
|
|
41
|
+
if (injection) parts.push(injection);
|
|
42
|
+
return {
|
|
43
|
+
systemPrompt: `${event.systemPrompt}\n\n${parts.join("\n\n")}`,
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
);
|
|
47
|
+
}
|
package/lib/memory-inject.ts
CHANGED
|
@@ -1,72 +1,74 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Memory 注入 — 读取 MEMORY.md 索引并拼接为 systemPrompt 注入文本
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import * as fs from "node:fs";
|
|
6
|
-
import * as path from "node:path";
|
|
7
|
-
import { AGENT_DIR } from "./types";
|
|
8
|
-
|
|
9
|
-
// ── 注入截断常量 ─────────────────────────────────────────
|
|
10
|
-
|
|
11
|
-
/** 注入索引的最大行数 */
|
|
12
|
-
const MAX_MEMORY_LINES = 200;
|
|
13
|
-
|
|
14
|
-
/** 注入索引的最大字节数 */
|
|
15
|
-
const MAX_MEMORY_BYTES = 25_000;
|
|
16
|
-
|
|
17
|
-
// ── 工具函数 ─────────────────────────────────────────────
|
|
18
|
-
|
|
19
|
-
/** 读取文件,成功返回 trim 内容,否则空字符串 */
|
|
20
|
-
export function readMemoryFile(filePath: string): string {
|
|
21
|
-
try {
|
|
22
|
-
if (fs.existsSync(filePath))
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if (entries.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Memory 注入 — 读取 MEMORY.md 索引并拼接为 systemPrompt 注入文本
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import { AGENT_DIR } from "./types";
|
|
8
|
+
|
|
9
|
+
// ── 注入截断常量 ─────────────────────────────────────────
|
|
10
|
+
|
|
11
|
+
/** 注入索引的最大行数 */
|
|
12
|
+
const MAX_MEMORY_LINES = 200;
|
|
13
|
+
|
|
14
|
+
/** 注入索引的最大字节数 */
|
|
15
|
+
const MAX_MEMORY_BYTES = 25_000;
|
|
16
|
+
|
|
17
|
+
// ── 工具函数 ─────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
/** 读取文件,成功返回 trim 内容,否则空字符串 */
|
|
20
|
+
export function readMemoryFile(filePath: string): string {
|
|
21
|
+
try {
|
|
22
|
+
if (fs.existsSync(filePath))
|
|
23
|
+
return fs.readFileSync(filePath, "utf-8").trim();
|
|
24
|
+
} catch {
|
|
25
|
+
// 文件不存在或权限异常 → 降级为空字符串
|
|
26
|
+
}
|
|
27
|
+
return "";
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 截断超长记忆索引 */
|
|
31
|
+
export function truncateMemory(raw: string): string {
|
|
32
|
+
const lines = raw.split("\n");
|
|
33
|
+
let truncated =
|
|
34
|
+
lines.length > MAX_MEMORY_LINES
|
|
35
|
+
? lines.slice(0, MAX_MEMORY_LINES).join("\n")
|
|
36
|
+
: raw;
|
|
37
|
+
if (truncated.length > MAX_MEMORY_BYTES) {
|
|
38
|
+
const cutAt = truncated.lastIndexOf("\n", MAX_MEMORY_BYTES);
|
|
39
|
+
truncated = truncated.slice(0, cutAt > 0 ? cutAt : MAX_MEMORY_BYTES);
|
|
40
|
+
}
|
|
41
|
+
if (truncated.length < raw.length) {
|
|
42
|
+
truncated += "\n\n> ⚠️ MEMORY.md 索引已截断。";
|
|
43
|
+
}
|
|
44
|
+
return truncated;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 拼接记忆注入文本。
|
|
49
|
+
* @returns 完整的注入文本,或 null(无记忆时)
|
|
50
|
+
*/
|
|
51
|
+
export function buildMemoryPrompt(
|
|
52
|
+
globalMemory: string,
|
|
53
|
+
projectMemory: string,
|
|
54
|
+
): string | null {
|
|
55
|
+
const entries: string[] = [];
|
|
56
|
+
if (globalMemory) entries.push(globalMemory);
|
|
57
|
+
if (projectMemory) entries.push(projectMemory);
|
|
58
|
+
if (entries.length === 0) return null;
|
|
59
|
+
return `## 记忆\n\n${entries.join("\n\n")}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 读取 L1/L2 的 MEMORY.md 索引,返回注入文本。
|
|
64
|
+
* 供 before_agent_start hook 调用。
|
|
65
|
+
*/
|
|
66
|
+
export function resolveMemoryInjection(cwd: string): string | null {
|
|
67
|
+
const l1Path = path.join(AGENT_DIR, "MEMORY.md");
|
|
68
|
+
const l2Path = path.join(cwd, ".pi", "memory", "MEMORY.md");
|
|
69
|
+
|
|
70
|
+
const globalMemory = truncateMemory(readMemoryFile(l1Path));
|
|
71
|
+
const projectMemory = truncateMemory(readMemoryFile(l2Path));
|
|
72
|
+
|
|
73
|
+
return buildMemoryPrompt(globalMemory, projectMemory);
|
|
74
|
+
}
|
package/lib/memory-parser.ts
CHANGED
|
@@ -1,95 +1,100 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Memory Parser — 共享的记忆文件名解析与目录扫描
|
|
3
|
-
*
|
|
4
|
-
* 文件名格式:topic--kw1,kw2,kw3,kw4,kw5.md
|
|
5
|
-
* -- 分隔 topic 和关键词
|
|
6
|
-
* , 分隔关键词
|
|
7
|
-
*
|
|
8
|
-
* 被 memory 扩展和 smart-context 扩展共同使用。
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import * as fs from "node:fs";
|
|
12
|
-
import * as path from "node:path";
|
|
13
|
-
|
|
14
|
-
// ── 类型定义 ─────────────────────────────────────────────
|
|
15
|
-
|
|
16
|
-
export interface MemoryEntry {
|
|
17
|
-
name: string;
|
|
18
|
-
file: string;
|
|
19
|
-
description: string;
|
|
20
|
-
lines: number;
|
|
21
|
-
scope: "L1" | "L2";
|
|
22
|
-
topic: string;
|
|
23
|
-
keywords: string[];
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// ── 文件名解析 ───────────────────────────────────────────
|
|
27
|
-
|
|
28
|
-
/** 从文件名解析 topic 和 keywords
|
|
29
|
-
*
|
|
30
|
-
* 格式:topic--kw1,kw2,kw3.md
|
|
31
|
-
* 无 -- 时 topic = basename(兼容旧格式)
|
|
32
|
-
*/
|
|
33
|
-
export function parseFileName(fileName: string): {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Memory Parser — 共享的记忆文件名解析与目录扫描
|
|
3
|
+
*
|
|
4
|
+
* 文件名格式:topic--kw1,kw2,kw3,kw4,kw5.md
|
|
5
|
+
* -- 分隔 topic 和关键词
|
|
6
|
+
* , 分隔关键词
|
|
7
|
+
*
|
|
8
|
+
* 被 memory 扩展和 smart-context 扩展共同使用。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as fs from "node:fs";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
|
|
14
|
+
// ── 类型定义 ─────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
export interface MemoryEntry {
|
|
17
|
+
name: string;
|
|
18
|
+
file: string;
|
|
19
|
+
description: string;
|
|
20
|
+
lines: number;
|
|
21
|
+
scope: "L1" | "L2";
|
|
22
|
+
topic: string;
|
|
23
|
+
keywords: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ── 文件名解析 ───────────────────────────────────────────
|
|
27
|
+
|
|
28
|
+
/** 从文件名解析 topic 和 keywords
|
|
29
|
+
*
|
|
30
|
+
* 格式:topic--kw1,kw2,kw3.md
|
|
31
|
+
* 无 -- 时 topic = basename(兼容旧格式)
|
|
32
|
+
*/
|
|
33
|
+
export function parseFileName(fileName: string): {
|
|
34
|
+
topic: string;
|
|
35
|
+
keywords: string[];
|
|
36
|
+
} {
|
|
37
|
+
if (fileName == null) return { topic: "", keywords: [] };
|
|
38
|
+
const base = fileName.replace(/\.md$/, "");
|
|
39
|
+
const idx = base.indexOf("--");
|
|
40
|
+
if (idx === -1) {
|
|
41
|
+
return { topic: base, keywords: [] };
|
|
42
|
+
}
|
|
43
|
+
const topic = base.substring(0, idx);
|
|
44
|
+
const kwStr = base.substring(idx + 2);
|
|
45
|
+
const keywords = kwStr ? kwStr.split(",") : [];
|
|
46
|
+
return { topic, keywords };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 生成文件名:topic--kw1,kw2,...md */
|
|
50
|
+
export function buildFileName(topic: string, keywords: string[]): string {
|
|
51
|
+
const kwPart = keywords.length > 0 ? keywords.join(",") : "";
|
|
52
|
+
const base = kwPart ? `${topic}--${kwPart}` : topic;
|
|
53
|
+
return `${base}.md`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ── 目录扫描 ─────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
/** 扫描目录下的记忆文件,从文件名解析 topic + keywords */
|
|
59
|
+
export function scanMemoryDir(dir: string, scope: "L1" | "L2"): MemoryEntry[] {
|
|
60
|
+
const entries: MemoryEntry[] = [];
|
|
61
|
+
if (!fs.existsSync(dir)) return entries;
|
|
62
|
+
|
|
63
|
+
const files = fs
|
|
64
|
+
.readdirSync(dir)
|
|
65
|
+
.filter((f) => f.endsWith(".md") && f !== "MEMORY.md")
|
|
66
|
+
.sort();
|
|
67
|
+
|
|
68
|
+
for (const file of files) {
|
|
69
|
+
const filePath = path.join(dir, file);
|
|
70
|
+
try {
|
|
71
|
+
const content = fs.readFileSync(filePath, "utf-8");
|
|
72
|
+
const lines = content.split("\n").length;
|
|
73
|
+
const titleLine = content.split("\n").find((l) => l.startsWith("# "));
|
|
74
|
+
const description = titleLine?.replace(/^#\s+/, "") || "";
|
|
75
|
+
const parsed = parseFileName(file);
|
|
76
|
+
entries.push({
|
|
77
|
+
name: file.replace(".md", ""),
|
|
78
|
+
file,
|
|
79
|
+
description,
|
|
80
|
+
lines,
|
|
81
|
+
scope,
|
|
82
|
+
topic: parsed.topic,
|
|
83
|
+
keywords: parsed.keywords,
|
|
84
|
+
});
|
|
85
|
+
} catch {
|
|
86
|
+
// 文件读取失败 → 用降级信息填充
|
|
87
|
+
entries.push({
|
|
88
|
+
name: file.replace(".md", ""),
|
|
89
|
+
file,
|
|
90
|
+
description: "(读取失败)",
|
|
91
|
+
lines: 0,
|
|
92
|
+
scope,
|
|
93
|
+
topic: parseFileName(file).topic,
|
|
94
|
+
keywords: parseFileName(file).keywords,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return entries;
|
|
100
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read Tracker — 会话内 read 路径跟踪 + 白名单校验
|
|
3
|
+
*
|
|
4
|
+
* 数据源:tool_result 钩子(toolName === "read" 且非 error)
|
|
5
|
+
* 用途:
|
|
6
|
+
* 1. 判定时剔除已读条目(防重复提醒)
|
|
7
|
+
* 2. 判定输出的路径白名单校验(幻觉路径丢弃)
|
|
8
|
+
*
|
|
9
|
+
* 路径归一化:全部转小写、正斜杠,便于跨形态匹配(C:\a\b.md vs c:/a/b.md)。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export function normalizePath(p: string): string {
|
|
13
|
+
return p.replace(/\\/g, "/").replace(/^\/+/, "").toLowerCase();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 归一化后按尾段匹配(清单条目可能是相对路径,判定输出可能是绝对路径或反之) */
|
|
17
|
+
export function pathEndsWith(candidate: string, entry: string): boolean {
|
|
18
|
+
const c = normalizePath(candidate);
|
|
19
|
+
const e = normalizePath(entry);
|
|
20
|
+
return c === e || c.endsWith("/" + e) || e.endsWith("/" + c);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class ReadTracker {
|
|
24
|
+
private readPaths = new Set<string>();
|
|
25
|
+
private readonly sessionStart: number;
|
|
26
|
+
|
|
27
|
+
constructor() {
|
|
28
|
+
this.sessionStart = Date.now();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 记录一次成功 read(tool_result:toolName === "read" 且非 error) */
|
|
32
|
+
recordRead(toolName: string, args: unknown, isError: boolean): void {
|
|
33
|
+
if (toolName !== "read" || isError) return;
|
|
34
|
+
const p =
|
|
35
|
+
(args as { path?: unknown; file_path?: unknown } | null)?.path ??
|
|
36
|
+
(args as { file_path?: unknown } | null)?.file_path;
|
|
37
|
+
if (typeof p === "string" && p.length > 0) {
|
|
38
|
+
this.readPaths.add(normalizePath(p));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 条目是否已被 read(尾段匹配,容忍绝对/相对差异) */
|
|
43
|
+
hasRead(entry: string): boolean {
|
|
44
|
+
for (const p of this.readPaths) {
|
|
45
|
+
if (pathEndsWith(p, entry)) return true;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 快照(诊断用) */
|
|
51
|
+
snapshot(): readonly string[] {
|
|
52
|
+
return [...this.readPaths];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
get startedAt(): number {
|
|
56
|
+
return this.sessionStart;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 判定输出行 → 白名单内条目映射;白名单外(幻觉)丢弃;上限 max 条 */
|
|
61
|
+
export function filterVerdictPaths(
|
|
62
|
+
lines: string[],
|
|
63
|
+
whitelist: string[],
|
|
64
|
+
max = 3,
|
|
65
|
+
): string[] {
|
|
66
|
+
const out: string[] = [];
|
|
67
|
+
for (const raw of lines) {
|
|
68
|
+
const line = raw.trim().replace(/^[-*\d.\s"']+|["']+$/g, "");
|
|
69
|
+
if (!line || line.length > 260) continue;
|
|
70
|
+
const hit = whitelist.find((w) => pathEndsWith(line, w));
|
|
71
|
+
if (hit && !out.some((o) => pathEndsWith(o, hit))) {
|
|
72
|
+
out.push(hit);
|
|
73
|
+
if (out.length >= max) break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* memory-routing 事件接线与命令注册。
|
|
3
|
+
* 核心路由器见 routing.ts。
|
|
4
|
+
*/
|
|
5
|
+
import { mkdirSync, appendFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { MemoryRouter, routingJudge, loadConfig } from "./routing";
|
|
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
|
+
}
|
|
23
|
+
|
|
24
|
+
export function registerRouting(pi: ExtensionAPI): void {
|
|
25
|
+
const router = new MemoryRouter(process.cwd());
|
|
26
|
+
const pendingTools = new Map<string, unknown>();
|
|
27
|
+
pi.on("message_end", async (event: unknown, ctx: unknown) => {
|
|
28
|
+
if (ctx) routingJudge.setContext(ctx as never); // 事件回调是 ctx 权威来源(shepherd 模式)
|
|
29
|
+
router.accumulate(event);
|
|
30
|
+
await router.maybeTrigger(pi);
|
|
31
|
+
});
|
|
32
|
+
pi.on("tool_execution_start", (event: unknown) => {
|
|
33
|
+
const { toolName, args, toolCallId } = event as {
|
|
34
|
+
toolName?: string; args?: unknown; toolCallId?: string;
|
|
35
|
+
};
|
|
36
|
+
if (toolName === "read" && toolCallId) pendingTools.set(toolCallId, args);
|
|
37
|
+
});
|
|
38
|
+
pi.on("tool_result", (event: unknown) => {
|
|
39
|
+
const { toolCallId, isError } = event as { toolCallId?: string; isError?: boolean };
|
|
40
|
+
if (!toolCallId || !pendingTools.has(toolCallId)) return;
|
|
41
|
+
const args = pendingTools.get(toolCallId);
|
|
42
|
+
pendingTools.delete(toolCallId);
|
|
43
|
+
if (!isError) router.recordRead("read", args, false);
|
|
44
|
+
});
|
|
45
|
+
pi.registerCommand("memory-routing", {
|
|
46
|
+
handler: async (rawArgs: string, ctx) => {
|
|
47
|
+
const sub = rawArgs.trim();
|
|
48
|
+
const notify = (ctx as { ui?: { notify?: (t: string) => void } })?.ui?.notify;
|
|
49
|
+
if (!notify) return;
|
|
50
|
+
const cfg = loadConfig(process.cwd());
|
|
51
|
+
if (/^\d+$/.test(sub)) {
|
|
52
|
+
router.setConfig({ batchSize: Number(sub) });
|
|
53
|
+
notify(`memoryRouting.batchSize = ${sub}`);
|
|
54
|
+
} else if (sub === "off" || sub === "on") {
|
|
55
|
+
router.setConfig({ enabled: sub === "on" });
|
|
56
|
+
notify(`memoryRouting.enabled = ${sub === "on"}`);
|
|
57
|
+
} else {
|
|
58
|
+
notify(
|
|
59
|
+
`memory-routing: enabled=${cfg.enabled} batchSize=${cfg.batchSize} ` +
|
|
60
|
+
`includeSpecs=${cfg.includeSpecs}\n用法: /memory-routing [N|on|off]`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
description: "记忆按需路由配置. 用法: /memory-routing | /memory-routing <N|on|off>",
|
|
65
|
+
});
|
|
66
|
+
appendRunLog("routing registered");
|
|
67
|
+
}
|