Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(pi): 压缩即记忆 —— 压缩摘要沉淀为 digest 记忆(不污染 curated)
zqchriseb8ba8ea58fc
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-compaction-memory.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-compaction-memory.test.tsnew file mode 100644index 0000000000..309beafd28--- /dev/null+++ b/packages/maker-core/src/agents/pi/__tests__/pi-compaction-memory.test.ts@@ -0,0 +1,141 @@+/**+ * PiAgent 压缩即记忆 —— compaction_end 带摘要正文时写 digest 记忆(mock pi 进程 + mock+ * makerMemory)。验证:开启时写 digest(字段正确)、关闭/无摘要时不写、写失败不阻断会话。+ */++import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const captured = vi.hoisted(() => ({+ onEvent: null as ((event: unknown) => void) | null,+}));++vi.mock('../rpc-client.js', () => ({+ PiRpcProcess: class {+ isClosed = false;+ constructor(opts: { onEvent: (event: unknown) => void }) {+ captured.onEvent = opts.onEvent;+ }+ async request(cmd: { type: string }): Promise<{ success: boolean; data?: unknown }> {+ if (cmd.type === 'get_state') {+ return { success: true, data: { sessionFile: '/mock/s.jsonl', model: { contextWindow: 200000 } } };+ }+ return { success: true, data: { entries: [] } };+ }+ send(): void {}+ async close(): Promise<void> {+ this.isClosed = true;+ }+ },+}));++import { PiAgent } from '../index.js';+import type { AgentDeps, AgentSessionHandle } from '../../base-agent.js';+import type { Logger } from '../../../interfaces/logger.js';++const noopLogger: Logger = {+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},+ child: () => noopLogger,+};++const flush = () => new Promise((r) => setTimeout(r, 0));++describe('PiAgent compaction → memory digest', () => {+ let agentHome = '';+ let cwd = '';+ let writeMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ captured.onEvent = null;+ agentHome = mkdtempSync(path.join(tmpdir(), 'pi-cm-home-'));+ cwd = mkdtempSync(path.join(tmpdir(), 'pi-cm-cwd-'));+ writeMock = vi.fn(async () => ({ ok: true, filename: 'digest_x.md' }));+ });+ afterEach(() => {+ rmSync(agentHome, { recursive: true, force: true });+ rmSync(cwd, { recursive: true, force: true });+ });++ function buildDeps(memoryEnabled: boolean, withManager = true): AgentDeps {+ return {+ auth: {+ getState: async () => ({ authenticated: true, identity: 't', authSource: 'api-key' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9', makerMemoryEnabled: memoryEnabled },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [{ id: 'm', displayName: 'M', contextWindow: 200_000, efforts: [], defaultEffort: null }],+ },+ resolvePiAgentHome: () => agentHome,+ ...(withManager ? { makerMemory: { write: writeMock } as never } : {}),+ };+ }++ async function start(memoryEnabled: boolean, withManager = true): Promise<AgentSessionHandle> {+ return new PiAgent(buildDeps(memoryEnabled, withManager)).startSession({+ sessionId: 'cm-session',+ workingDir: cwd,+ model: 'm',+ });+ }++ function fireCompaction(summary: unknown, reason = 'threshold'): void {+ captured.onEvent!({ type: 'compaction_end', reason, result: { summary, estimatedTokensAfter: 32000 } });+ }++ it('writes a digest entry with correct fields when memory is enabled', async () => {+ const handle = await start(true);+ fireCompaction('The conversation covered the API redesign and the test plan.');+ await flush();+ expect(writeMock).toHaveBeenCalledTimes(1);+ const [scopeKey, opts] = writeMock.mock.calls[0];+ expect(typeof scopeKey).toBe('string');+ expect(opts.type).toBe('digest');+ expect(opts.mode).toBe('create');+ expect(opts.title).toContain('threshold');+ expect(opts.description).toContain('API redesign');+ expect(opts.body).toContain('test plan');+ expect(opts.name).toMatch(/^[a-z0-9_-]{1,64}$/);+ await handle.close();+ });++ it('does not write when memory is disabled', async () => {+ const handle = await start(false);+ fireCompaction('some summary');+ await flush();+ expect(writeMock).not.toHaveBeenCalled();+ await handle.close();+ });++ it('does not write when there is no summary text', async () => {+ const handle = await start(true);+ fireCompaction(undefined);+ fireCompaction(' ');+ fireCompaction(42);+ await flush();+ expect(writeMock).not.toHaveBeenCalled();+ await handle.close();+ });++ it('does not write when no manager is injected even if flag is on', async () => {+ const handle = await start(true, false);+ fireCompaction('summary');+ await flush();+ expect(writeMock).not.toHaveBeenCalled();+ await handle.close();+ });++ it('a failing digest write does not throw into the event loop', async () => {+ writeMock.mockRejectedValueOnce(new Error('disk full'));+ const handle = await start(true);+ expect(() => fireCompaction('summary that fails to persist')).not.toThrow();+ await flush();+ await handle.close();+ });+});diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 5296bbdc8d..b85334f58b 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -38,6 +38,7 @@ import {CINDY_BRIDGE_EXTENSION_SOURCE,} from './cindy-bridge-source.js';import { classifyPiToolForAutoReview } from './auto-review-policy.js';+import { buildMemoryScopeKey } from '../../memory/storage.js';import type {Capabilities,ManualCompactResult,@@ -70,6 +71,21 @@ const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */const PI_COMPACT_TIMEOUT_MS = 600_000;+/** digest 分片 body 留点 headroom(硬上限 8192),摘要过长时截断。 */+const PI_DIGEST_MAX_BODY = 7000;++/** 任意串 → memory slug 片段([a-z0-9-],截断)。 */+function slugifyForMemory(input: string, maxLen: number): string {+ const s = input.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');+ return (s || 'anon').slice(0, maxLen);+}++/** 摘要正文 → 一行 description(折叠空白、去换行、截断)。 */+function oneLineDescription(text: string, maxLen: number): string {+ const line = text.replace(/\s+/g, ' ').trim();+ return line.length > maxLen ? line.slice(0, maxLen - 1) + '…' : line;+}+/*** NO_PROXY 兜底:pi 的模型请求打的是 Cindy 本地 compat proxy(loopback),bridge 的* MCP fetch 也是 localhost —— 用户设了全局 HTTP_PROXY 时这些请求不能进代理隧道。@@ -356,6 +372,39 @@ export class PiAgent extends BaseAgent {}}+ // 压缩即记忆:makerMemory 开启时,把 pi 压缩上下文时丢弃内容的摘要沉淀成 `digest`+ // 记忆(进 FTS 可 memory_search 检索,但排除出 MEMORY.md / system prompt,不污染+ // curated 记忆)。gate 与 CC 同口径;best-effort,失败只 warn,绝不阻断会话。+ const compactionMemoryEnabled =+ (opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false) === true &&+ !!this.deps.makerMemory;+ const memoryScopeKey = buildMemoryScopeKey(opts.workingDir, opts.remoteHostId);+ const digestSlugBase = slugifyForMemory(opts.sessionId ?? `pi-${process.pid}`, 24);+ let digestSeq = 0;+ const writeCompactionDigest = async (summary: string, reason: string): Promise<void> => {+ const manager = this.deps.makerMemory;+ if (!compactionMemoryEnabled || !manager) return;+ const body = summary.length > PI_DIGEST_MAX_BODY ? summary.slice(0, PI_DIGEST_MAX_BODY) + '\n…' : summary;+ const seq = ++digestSeq;+ // slug 唯一:sessionId 片段 + 递增序号;resume/跨会话用 Date.now 防撞名(create 模式撞名会抛)。+ const slug = slugifyForMemory(`digest-${digestSlugBase}-${Date.now()}-${seq}`, 64);+ try {+ await manager.write(memoryScopeKey, {+ type: 'digest',+ name: slug,+ title: `PI compaction digest (${reason})`,+ description: oneLineDescription(summary, 180),+ body,+ mode: 'create',+ });+ this.deps.logger.debug('pi compaction digest saved to memory', { slug, reason });+ } catch (err) {+ this.deps.logger.warn('pi compaction digest write failed (non-fatal)', {+ message: err instanceof Error ? err.message : String(err),+ });+ }+ };+// 追加而非替换:pi 默认 prompt(工具用法/工程约定)原样保留,只追加 host 产品段// 与用户段。前缀稳定(默认 prompt 静态),易变内容禁止进入(缓存规则 3.1)。const appendSections = [@@ -430,6 +479,15 @@ export class PiAgent extends BaseAgent {}));return;}+ // 压缩即记忆:compaction_end 带摘要正文时沉淀 digest(auto/manual 都触发,pi+ // 文档:两种压缩都发此事件)。fire-and-forget,不阻塞事件流。+ if (event.type === 'compaction_end' && compactionMemoryEnabled) {+ const summary = (event.result as { summary?: unknown } | null)?.summary;+ if (typeof summary === 'string' && summary.trim().length > 0) {+ const reason = typeof event.reason === 'string' ? event.reason : 'auto';+ void writeCompactionDigest(summary.trim(), reason);+ }+ }translatePiEvent(event, queue, ctx);},onExit: ({ code, signal }) => {diff --git a/packages/maker-core/src/memory/digest-type.test.ts b/packages/maker-core/src/memory/digest-type.test.tsnew file mode 100644index 0000000000..9357eb752a--- /dev/null+++ b/packages/maker-core/src/memory/digest-type.test.ts@@ -0,0 +1,62 @@+/**+ * digest 记忆类型 —— 压缩即记忆的存储契约:+ * - digest 可写入 store、进 list()(→ 进 FTS,可被 memory_search 检索);+ * - 但**排除出 MEMORY.md 索引**(rebuildIndex 只列 curated 类型),故不自动注入 system prompt、+ * 不污染 curated 记忆。+ */++import { mkdtemp, rm, readFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { MemoryStorage } from './storage.js';+import { DEFAULT_MEMORY_CONFIG, MEMORY_TYPES, CURATED_MEMORY_TYPES } from './types.js';++let dir: string;++beforeEach(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'memory-digest-'));+});+afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+});++describe('digest memory type', () => {+ it('is a valid storage type but not a curated type', () => {+ expect(MEMORY_TYPES).toContain('digest');+ expect(CURATED_MEMORY_TYPES).not.toContain('digest');+ });++ it('writes a digest entry that lists() sees but MEMORY.md excludes', async () => {+ const storage = new MemoryStorage(dir, DEFAULT_MEMORY_CONFIG);+ await storage.write({+ type: 'project',+ name: 'curated-note',+ title: 'Curated project note',+ description: 'a curated one-liner',+ body: 'curated body',+ });+ await storage.write({+ type: 'digest',+ name: 'pi-compaction-1',+ title: 'PI compaction digest (threshold)',+ description: 'summary of dropped context about the API redesign',+ body: 'The conversation covered the API redesign, auth changes, and test plan.',+ });++ // list() 两条都在(→ FTS 会索引 digest,memory_search 可查)。+ const records = await storage.list();+ const types = records.map((r) => r.frontmatter.type).sort();+ expect(types).toEqual(['digest', 'project']);++ // MEMORY.md:curated 在、digest 不在。+ const indexRaw = await readFile(path.join(dir, 'MEMORY.md'), 'utf8');+ expect(indexRaw).toContain('Curated project note');+ expect(indexRaw).not.toContain('PI compaction digest');+ expect(indexRaw).not.toContain('## digest');+ // digest 的文件确实落盘了(digest_<slug>.md)。+ expect(records.some((r) => r.filename === 'digest_pi-compaction-1.md')).toBe(true);+ });+});diff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.tsindex ba4d54c31b..eb2a49b59d 100644--- a/packages/maker-core/src/memory/storage.ts+++ b/packages/maker-core/src/memory/storage.ts@@ -25,6 +25,7 @@ import * as path from 'node:path';import matter from 'gray-matter';import {+ CURATED_MEMORY_TYPES,DEFAULT_MEMORY_CONFIG,isMemoryType,MemoryError,@@ -321,8 +322,11 @@ export class MemoryStorage {if (records.length === 0) {lines.push('_(empty — no memories saved yet for this workdir)_', '');} else {- // 固定顺序 user → feedback → project → reference- for (const type of ['user', 'feedback', 'project', 'reference'] as MemoryType[]) {+ // 固定顺序 user → feedback → project → reference。**只列 curated 类型** ——+ // `digest`(系统内部,如 pi 压缩摘要)故意排除:进 FTS 可 memory_search,但不进+ // MEMORY.md、不进 system prompt(见 types.ts MEMORY_TYPES 注释)。新增 curated+ // 类型时改 CURATED_MEMORY_TYPES;不要把 digest 加进来。+ for (const type of CURATED_MEMORY_TYPES) {const items = grouped.get(type);if (!items || items.length === 0) continue;lines.push(`## ${type}`);diff --git a/packages/maker-core/src/memory/types.ts b/packages/maker-core/src/memory/types.tsindex b17b9d1037..3a62c017e7 100644--- a/packages/maker-core/src/memory/types.ts+++ b/packages/maker-core/src/memory/types.ts@@ -12,7 +12,21 @@* 硬错误 (schema / 撞名 / 路径非法) 走 throw MemoryError。*/-export const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference'] as const;+/**+ * Curated 类型:LLM 可写(memory_write 工具)+ 进 MEMORY.md 索引 + 进 system prompt。+ */+export const CURATED_MEMORY_TYPES = ['user', 'feedback', 'project', 'reference'] as const;+/**+ * 全部 storage 允许的类型 = curated + `digest`。+ *+ * `digest` 是**系统内部类型**(当前:pi 压缩上下文时把被丢弃内容的摘要沉淀进来)。它:+ * - 可写入 store、进 FTS —— `memory_search` 能按需检索;+ * - **排除出 MEMORY.md 索引**(rebuildIndex 只列 CURATED_MEMORY_TYPES),故**不自动注入+ * system prompt**、不撑大上下文、不污染 curated 记忆;+ * - **不暴露给 LLM 的 memory_write 工具**(该工具自带 4 类 curated enum,与此处解耦)。+ * 改动前请读 docs/dev-rules/pi-remaining-work.md「压缩即记忆」与 pi-harness.md。+ */+export const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference', 'digest'] as const;export type MemoryType = (typeof MEMORY_TYPES)[number];export function isMemoryType(v: unknown): v is MemoryType {