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/lib/routing.ts ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * memory-routing 核心路由器:计数 → 批量判定 → 白名单校验 → 注入。
3
+ * 事件接线与命令注册见 routing-register.ts。
4
+ */
5
+ import { createHash } from "node:crypto";
6
+ import { join } from "node:path";
7
+ import { getEffectiveConfig } from "@pi-atelier/shared-utils";
8
+ import { createJudge } from "@pi-atelier/shared-utils/judge";
9
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ collectMemoryAssets,
12
+ collectSpecAssets,
13
+ type KnowledgeAsset,
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;
21
+
22
+ export interface RoutingConfig {
23
+ enabled: boolean;
24
+ batchSize: number;
25
+ includeSpecs: boolean;
26
+ judgeModel: string;
27
+ }
28
+
29
+ export function loadConfig(cwd: string): RoutingConfig {
30
+ const { config } = getEffectiveConfig(
31
+ "memoryRouting",
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
+ };
41
+ }
42
+
43
+ const SYSTEM_PROMPT =
44
+ "你是知识资产路由判定器。根据会话最近的 AI 叙述,判断与哪些【未读】资产强相关。\n" +
45
+ "输出格式:每行一个路径(逐字取自清单),最多 3 条;无相关则只输出「无」。\n" +
46
+ "规则:只推荐未读条目;提醒 2+ 次仍未读的条目不再推荐;路径禁止构造,必须逐字来自清单。";
47
+
48
+ function parsePathList(raw: string): string[] | null {
49
+ const lines = raw.split(/[\r\n]+/).map((l) => l.trim()).filter(Boolean);
50
+ if (lines.length === 0) return null;
51
+ if (lines.length === 1 && /^(无|none|n\/a)$/i.test(lines[0])) return [];
52
+ const bad = lines.find((l) => l.includes(" ") || l.length > 200);
53
+ if (bad) return null;
54
+ return lines.slice(0, 3);
55
+ }
56
+
57
+ export const routingJudge = createJudge<string[]>({
58
+ label: "memory-routing",
59
+ systemPrompt: SYSTEM_PROMPT,
60
+ parse: parsePathList,
61
+ judgeLogPath: JUDGE_LOG,
62
+ legacySectionKeys: ["memoryRouting", "shepherd"],
63
+ });
64
+
65
+ export class MemoryRouter {
66
+ private buffer: string[] = [];
67
+ private seen = 0;
68
+ private remindedCount = new Map<string, number>();
69
+ private config: RoutingConfig;
70
+ private readTracker = new ReadTracker();
71
+ private cwd: string;
72
+ constructor(cwd: string, config?: RoutingConfig) {
73
+ this.cwd = cwd;
74
+ this.config = config ?? loadConfig(cwd);
75
+ }
76
+ get enabled(): boolean { return this.config.enabled; }
77
+ setConfig(patch: Partial<RoutingConfig>): void {
78
+ this.config = { ...this.config, ...patch };
79
+ }
80
+ /** message_end:积累 text 块(纯 tool 轮不计数) */
81
+ accumulate(event: unknown): void {
82
+ if (!this.config.enabled) return;
83
+ const message = (event as { message?: { role?: string; content?: unknown[] } }).message;
84
+ if (!message || message.role !== "assistant") return;
85
+ const blocks = Array.isArray(message.content) ? message.content : [];
86
+ const texts = blocks
87
+ .filter((b): b is { type: "text"; text: string } =>
88
+ typeof b === "object" && b !== null && (b as { type?: string }).type === "text")
89
+ .map((b) => b.text)
90
+ .filter((t) => t && t.trim().length > 0);
91
+ if (texts.length === 0) return;
92
+ this.seen += 1;
93
+ this.buffer.push(texts.join("\n"));
94
+ }
95
+ /** 计满触发异步判定(fire-and-forget,异常静默 = fail-open) */
96
+ async maybeTrigger(pi?: ExtensionAPI): Promise<void> {
97
+ if (!this.config.enabled) return;
98
+ if (this.seen < this.config.batchSize) return;
99
+ const batch = this.buffer.splice(0, this.buffer.length);
100
+ this.seen = 0;
101
+ try {
102
+ await this.runBatch(batch, pi);
103
+ } catch {
104
+ // fail-open:静默丢弃本批(specs §1.5)
105
+ }
106
+ }
107
+ private async runBatch(batch: string[], pi?: ExtensionAPI): Promise<void> {
108
+ const narrative = batch.join("\n---\n").slice(-6000);
109
+ const hash = createHash("sha1").update(narrative).digest("hex");
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);
159
+ }
160
+ }
package/lib/types.ts CHANGED
@@ -1,32 +1,24 @@
1
- /**
2
- * Memory Tools — 公共类型与常量
3
- */
4
-
5
- import * as path from "node:path";
6
- import { homedir } from "node:os";
7
-
8
- export interface MemoryEntry {
9
- name: string;
10
- file: string;
11
- description: string;
12
- lines: number;
13
- scope: "L1" | "L2";
14
- }
15
-
16
- /** L1 全局目录 */
17
- export const AGENT_DIR = path.join(homedir(), ".pi/agent");
18
-
19
- /** 记忆文件行数上限 */
20
- export const MAX_FILE_LINES = 200;
21
-
22
- /** 记忆文件合并后行数上限 */
23
- export const MAX_MERGED_LINES = MAX_FILE_LINES * 2;
24
-
25
- /** 记忆文件总数硬限制(超过拒绝写入) */
26
- export const HARD_FILE_LIMIT = 40;
27
-
28
- /** 记忆文件总数软限制(超过发出警告) */
29
- export const SOFT_FILE_LIMIT = 25;
30
-
31
- /** 记忆文件总数提示阈值 */
32
- export const HINT_FILE_LIMIT = 20;
1
+ /**
2
+ * Memory Tools — 公共类型与常量
3
+ */
4
+
5
+ import { homedir } from "node:os";
6
+ import * as path from "node:path";
7
+
8
+ /** L1 全局目录 */
9
+ export const AGENT_DIR = path.join(homedir(), ".pi/agent");
10
+
11
+ /** 记忆文件行数上限 */
12
+ export const MAX_FILE_LINES = 200;
13
+
14
+ /** 记忆文件合并后行数上限 */
15
+ export const MAX_MERGED_LINES = MAX_FILE_LINES * 2;
16
+
17
+ /** 记忆文件总数硬限制(超过拒绝写入) */
18
+ export const HARD_FILE_LIMIT = 80;
19
+
20
+ /** 记忆文件总数软限制(超过发出警告) */
21
+ export const SOFT_FILE_LIMIT = 25;
22
+
23
+ /** 记忆文件总数提示阈值 */
24
+ export const HINT_FILE_LIMIT = 20;
package/lib/writer.ts CHANGED
@@ -1,69 +1,68 @@
1
- /**
2
- * Memory Tools — 文件写入与索引重建
3
- *
4
- * 索引(MEMORY.md)以磁盘文件为唯一真相源。
5
- * 每次 write 后全量重建索引,保证索引与磁盘始终一致。
6
- */
7
-
8
- import * as fs from "node:fs";
9
- import * as path from "node:path";
10
- import { scanMemoryDir } from "./memory-parser";
11
- import { MAX_FILE_LINES } from "./types";
12
-
13
- /**
14
- * 全量重建 MEMORY.md 索引
15
- *
16
- * 扫描 targetDir 下所有 .md 文件(排除 MEMORY.md 自身),
17
- * 生成 表格 + 链接区,覆盖写入 indexPath。
18
- *
19
- * 这是保证「索引 === 磁盘」的唯一函数。
20
- */
21
- export function rebuildIndex(targetDir: string, indexPath: string, scope: "L1" | "L2"): void {
22
- const entries = scanMemoryDir(targetDir, scope);
23
-
24
- if (entries.length === 0) {
25
- // 没有记忆文件时,写一个空索引(或删除索引)
26
- if (fs.existsSync(indexPath)) {
27
- fs.writeFileSync(indexPath, "", "utf-8");
28
- }
29
- return;
30
- }
31
-
32
- const lines: string[] = [
33
- "# Memory Index",
34
- "",
35
- "> 自动生成 — 列出所有记忆文件及其关键词摘要",
36
- "",
37
- `## 文件清单 (${entries.length})`,
38
- "",
39
- "| # | 文件 | 关键词 |",
40
- "|---|------|--------|",
41
- ];
42
-
43
- for (let i = 0; i < entries.length; i++) {
44
- const e = entries[i];
45
- const kws = e.keywords.join(", ") || "";
46
- lines.push(`| ${i + 1} | ${e.topic} | ${kws} |`);
47
- }
48
-
49
- lines.push("");
50
-
51
- for (const e of entries) {
52
- lines.push(`- [${e.topic}](${e.file})`);
53
- }
54
-
55
- lines.push(""); // trailing newline
56
-
57
- fs.mkdirSync(path.dirname(indexPath), { recursive: true });
58
- fs.writeFileSync(indexPath, lines.join("\n"), "utf-8");
59
- }
60
-
61
- /** 检查文件行数是否超限,返回警告或 null */
62
- export function checkLineCount(filePath: string): string | null {
63
- if (!fs.existsSync(filePath)) return null;
64
- const lines = fs.readFileSync(filePath, "utf-8").split("\n").length;
65
- if (lines > MAX_FILE_LINES) {
66
- return `⚠️ ${filePath} 超过 ${MAX_FILE_LINES} 行(当前 ${lines} 行),请拆分`;
67
- }
68
- return null;
69
- }
1
+ /**
2
+ * Memory Tools — 文件写入与索引重建
3
+ *
4
+ * 索引(MEMORY.md)以磁盘文件为唯一真相源。
5
+ * 每次 write 后全量重建索引,保证索引与磁盘始终一致。
6
+ */
7
+
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { scanMemoryDir } from "./memory-parser";
11
+ import { MAX_FILE_LINES } from "./types";
12
+
13
+ /**
14
+ * 全量重建 MEMORY.md 索引
15
+ *
16
+ * 扫描 targetDir 下所有 .md 文件(排除 MEMORY.md 自身),
17
+ * 生成 表格 + 链接区,覆盖写入 indexPath。
18
+ *
19
+ * 这是保证「索引 === 磁盘」的唯一函数。
20
+ */
21
+ export function rebuildIndex(
22
+ targetDir: string,
23
+ indexPath: string,
24
+ scope: "L1" | "L2",
25
+ ): void {
26
+ const entries = scanMemoryDir(targetDir, scope);
27
+
28
+ if (entries.length === 0) {
29
+ // 没有记忆文件时,写一个空索引(或删除索引)
30
+ if (fs.existsSync(indexPath)) {
31
+ fs.writeFileSync(indexPath, "", "utf-8");
32
+ }
33
+ return;
34
+ }
35
+
36
+ const scopeTitle = scope === "L1" ? "Global Memory Index (L1)" : "Project Memory Index (L2)";
37
+ const lines: string[] = [
38
+ `# ${scopeTitle}`,
39
+ "",
40
+ "> 自动生成 — 列出所有记忆文件及其关键词摘要;「文件」列为实际文件名(topic--kws.md),可直接 read",
41
+ "",
42
+ `## 文件清单 (${entries.length})`,
43
+ "",
44
+ "| # | 文件 | 关键词 |",
45
+ "|---|------|--------|",
46
+ ];
47
+
48
+ for (let i = 0; i < entries.length; i++) {
49
+ const e = entries[i];
50
+ const kws = e.keywords.join(", ") || "";
51
+ lines.push(`| ${i + 1} | ${e.file} | ${kws} |`);
52
+ }
53
+
54
+ lines.push(""); // trailing newline
55
+
56
+ fs.mkdirSync(path.dirname(indexPath), { recursive: true });
57
+ fs.writeFileSync(indexPath, lines.join("\n"), "utf-8");
58
+ }
59
+
60
+ /** 检查文件行数是否超限,返回警告或 null */
61
+ export function checkLineCount(filePath: string): string | null {
62
+ if (!fs.existsSync(filePath)) return null;
63
+ const lines = fs.readFileSync(filePath, "utf-8").split("\n").length;
64
+ if (lines > MAX_FILE_LINES) {
65
+ return `⚠️ ${filePath} 超过 ${MAX_FILE_LINES} 行(当前 ${lines} 行),请拆分`;
66
+ }
67
+ return null;
68
+ }
package/package.json CHANGED
@@ -1,60 +1,63 @@
1
- {
2
- "name": "pi-ate-memory",
3
- "version": "1.0.0",
4
- "description": "File-based persistent memory for AI coding agents",
5
- "keywords": [
6
- "pi-package"
7
- ],
8
- "type": "commonjs",
9
- "main": "index.ts",
10
- "types": "index.ts",
11
- "scripts": {
12
- "test": "vitest run",
13
- "typecheck": "tsc --noEemit"
14
- },
15
- "peerDependencies": {
16
- "@earendil-works/pi-coding-agent": ">=1.0.0"
17
- },
18
- "peerDependenciesMeta": {
19
- "@earendil-works/pi-coding-agent": {
20
- "optional": true
21
- }
22
- },
23
- "devDependencies": {
24
- "@sinclair/typebox": "^0.34.49",
25
- "@types/node": "^25.6.2",
26
- "@vitest/coverage-v8": "^3.2.4",
27
- "typescript": "^6.0.3",
28
- "vitest": "^3.0.0"
29
- },
30
- "pi": {
31
- "extensions": [
32
- "."
33
- ],
34
- "skills": [
35
- "skills"
36
- ],
37
- "prompts": [
38
- "prompts"
39
- ]
40
- },
41
- "files": [
42
- "index.ts",
43
- "lib/",
44
- "prompts/",
45
- "memory-prompt.md",
46
- "README.md",
47
- "README.en.md",
48
- "tsconfig.json",
49
- "package.json"
50
- ],
51
- "homepage": "https://catlain.github.io/pi-atelier/",
52
- "repository": {
53
- "type": "git",
54
- "url": "git+ssh://git@github.com:catlain/pi-memory.git"
55
- },
56
- "bugs": {
57
- "url": "https://github.com/catlain/pi-memory/issues"
58
- },
59
- "license": "MIT"
60
- }
1
+ {
2
+ "name": "pi-ate-memory",
3
+ "version": "1.2.0",
4
+ "description": "File-based persistent memory for AI coding agents",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "type": "commonjs",
9
+ "main": "index.ts",
10
+ "types": "index.ts",
11
+ "scripts": {
12
+ "test": "vitest run",
13
+ "typecheck": "tsc --noEmit"
14
+ },
15
+ "peerDependencies": {
16
+ "@earendil-works/pi-coding-agent": ">=1.0.0"
17
+ },
18
+ "peerDependenciesMeta": {
19
+ "@earendil-works/pi-coding-agent": {
20
+ "optional": true
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@pi-atelier/shared-utils": "^1.5.0"
25
+ },
26
+ "devDependencies": {
27
+ "@sinclair/typebox": "^0.34.49",
28
+ "@types/node": "^25.6.2",
29
+ "@vitest/coverage-v8": "^3.2.4",
30
+ "typescript": "^6.0.3",
31
+ "vitest": "^3.0.0"
32
+ },
33
+ "pi": {
34
+ "extensions": [
35
+ "."
36
+ ],
37
+ "skills": [
38
+ "skills"
39
+ ],
40
+ "prompts": [
41
+ "prompts"
42
+ ]
43
+ },
44
+ "files": [
45
+ "index.ts",
46
+ "lib/",
47
+ "prompts/",
48
+ "memory-prompt.md",
49
+ "README.md",
50
+ "README.en.md",
51
+ "tsconfig.json",
52
+ "package.json"
53
+ ],
54
+ "homepage": "https://catlain.github.io/pi-atelier/",
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "git+ssh://git@github.com:catlain/pi-memory.git"
58
+ },
59
+ "bugs": {
60
+ "url": "https://github.com/catlain/pi-memory/issues"
61
+ },
62
+ "license": "MIT"
63
+ }
@@ -20,7 +20,7 @@
20
20
  - 旧结论已被新结论取代 → 用新内容覆盖旧文件(同名),不要新建
21
21
  - 不确定是否重复 → 先 memory_index 确认,不要盲目新建
22
22
  - 记忆文件总数超过 25 个时 → 主动考虑合并/归档,减少碎片化
23
- - 记忆文件总数超过 40 个时 → 工具拒绝写入,必须先清理
23
+ - 记忆文件总数超过 80 个时 → 工具拒绝写入,必须先清理
24
24
 
25
25
  清理操作步骤(记忆文件过多时执行):
26
26
  A. 同主题合并:read 所有同 topic/高关键词重叠的文件 → 整合为一份 → memory_update 覆盖 → 删除旧文件
package/tsconfig.json CHANGED
@@ -1,10 +1,10 @@
1
- {
2
- "extends": "../tsconfig.base.json",
3
- "compilerOptions": {
4
- "module": "ES2022",
5
- "outDir": "dist",
6
- "rootDir": ".",
7
- "types": ["node", "vitest/globals"]
8
- },
9
- "include": ["index.ts", "lib/**/*.ts", "tests/**/*.ts"]
10
- }
1
+ {
2
+ "extends": "../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "ES2022",
5
+ "outDir": "dist",
6
+ "rootDir": ".",
7
+ "types": ["node", "vitest/globals"]
8
+ },
9
+ "include": ["index.ts", "lib/**/*.ts", "tests/**/*.ts"]
10
+ }