Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-core): memory size 软警告附带数值明细 (#906)
张怡01701a78d67f
diff --git a/packages/lizi-mcps/src/memory/write.ts b/packages/lizi-mcps/src/memory/write.tsindex eac21234ed..20167105d8 100644--- a/packages/lizi-mcps/src/memory/write.ts+++ b/packages/lizi-mcps/src/memory/write.ts@@ -9,8 +9,9 @@* - 'update' : 覆盖现有 (不存在抛 NOT_FOUND)* - 'append' : 追加到 body 末尾 (不存在抛 NOT_FOUND)*- * 返 WriteResult 含可选 warning ('shard-size-exceeded' / 'index-size-exceeded'),- * LLM 在 prompt 引导下走 memory_consolidate 瘦身。+ * 返 WriteResult 含可选 warning ('shard-size-exceeded' / 'index-size-exceeded')+ * 与 warningDetail (sizeBytes/softLimitBytes;hardLimitBytes 仅分片警告带,+ * 索引警告无硬上限), LLM 按超限幅度决定不动 / 微剪 / memory_consolidate 瘦身。*/import { z } from 'zod';@@ -29,7 +30,9 @@ export function registerMemoryWriteTool(registry: MemoryToolRegistry, deps: Memo'name 是 filename slug ([a-z0-9_-]{1,64}, 不是显示文本); title 显示标题 (中英均可); ' +'description 一行 hook (用作 MEMORY.md 索引行, 无换行, ≤ 200 字符); body 主体内容。' +'mode 默认 create (撞名拒绝), 可选 update/append。' +- ' 写入后 MEMORY.md 自动重建; 软超 size 上限返 warning, LLM 应调 memory_consolidate 瘦身。',+ ' 写入后 MEMORY.md 自动重建; 软超 size 上限返 warning + warningDetail' ++ ' (sizeBytes/softLimitBytes, 分片警告另带 hardLimitBytes; 索引警告无硬上限),' ++ ' 按超限幅度决定不动 / 微剪 / memory_consolidate。',inputShape: {type: z.enum(['user', 'feedback', 'project', 'reference']),name: zdiff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.tsindex 2b73781684..0ead78ccaa 100644--- a/packages/maker-core/src/memory/storage.ts+++ b/packages/maker-core/src/memory/storage.ts@@ -33,7 +33,7 @@ import {type MemoryType,type WriteOptions,type WriteResult,- type WriteWarning,+ type WriteWarningDetail,} from './types.js';const INDEX_FILENAME = 'MEMORY.md';@@ -172,7 +172,8 @@ export class MemoryStorage {* 写完自动重建 MEMORY.md。返 WriteResult.warning:* - 'shard-size-exceeded' : 写完后 body 超 maxShardBytes (软上限)* - 'index-size-exceeded' : 重建后 MEMORY.md 超 maxIndexBytes (软上限)- * 软警告 = 写入仍成功, LLM 在 prompt 引导下走 consolidate。+ * 软警告 = 写入仍成功; warningDetail 附当前字节/软上限/硬上限,+ * 调用方据此判断超了多少再决定不动 / 微剪 / consolidate。*/async write(opts: WriteOptions): Promise<WriteResult> {this.validateOpts(opts);@@ -226,8 +227,11 @@ export class MemoryStorage {await this.rebuildIndex();const result: WriteResult = { ok: true, filename };- const warning = this.computeWarning(nextBody);- if (warning) result.warning = warning;+ const detail = this.computeWarning(nextBody);+ if (detail) {+ result.warning = detail.kind;+ result.warningDetail = detail;+ }return result;}@@ -370,13 +374,37 @@ export class MemoryStorage {}}- private computeWarning(body: string): WriteWarning | undefined {- if (Buffer.byteLength(body, 'utf8') > this.config.maxShardBytes) {- return 'shard-size-exceeded';+ /**+ * 重算某分片的软警告 (含索引侧)。分片侧读盘; 索引侧走 indexCache —+ * 本实例的 write/delete 都会刷新缓存, 因此反映的是**本实例视角**的最新状态;+ * 若 MEMORY.md 被其他实例/进程改写, 索引侧评估可能滞后。+ * consolidate 删源后索引已变小, 写入时点的警告可能失真 — 收尾用本方法重算。+ */+ async assessWarning(filename: string): Promise<WriteWarningDetail | undefined> {+ const rec = await this.read(filename);+ await this.getIndex(); // 确保 indexCache 就绪 (新实例上也能评估索引侧)+ return this.computeWarning(rec.body);+ }++ private computeWarning(body: string): WriteWarningDetail | undefined {+ const bodyBytes = Buffer.byteLength(body, 'utf8');+ if (bodyBytes > this.config.maxShardBytes) {+ return {+ kind: 'shard-size-exceeded',+ sizeBytes: bodyBytes,+ softLimitBytes: this.config.maxShardBytes,+ hardLimitBytes: this.config.hardShardBytes,+ };}// 索引刚被 rebuildIndex 写过, 直接读 cache- if (this.indexCache !== null && Buffer.byteLength(this.indexCache, 'utf8') > this.config.maxIndexBytes) {- return 'index-size-exceeded';+ const indexBytes =+ this.indexCache !== null ? Buffer.byteLength(this.indexCache, 'utf8') : 0;+ if (indexBytes > this.config.maxIndexBytes) {+ return {+ kind: 'index-size-exceeded',+ sizeBytes: indexBytes,+ softLimitBytes: this.config.maxIndexBytes,+ };}return undefined;}diff --git a/packages/maker-core/src/memory/storage.warning.test.ts b/packages/maker-core/src/memory/storage.warning.test.tsnew file mode 100644index 0000000000..1b7257b5ad--- /dev/null+++ b/packages/maker-core/src/memory/storage.warning.test.ts@@ -0,0 +1,130 @@+/**+ * MemoryStorage size 软警告的数值明细 (#891):+ * warning 枚举保持不变, warningDetail 附当前字节 / 软上限 / (分片) 硬上限,+ * 让调用方判断超了多少, 而不是盲目瘦身。+ */++import { mkdtemp, rm } 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, type WriteOptions } from './types.js';++let dir: string;++beforeEach(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'memory-warning-'));+});++afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+});++function writeOpts(body: string, name = 'warn-case'): WriteOptions {+ return {+ type: 'project',+ name,+ title: '测试分片',+ description: '软警告数值明细测试用',+ body,+ };+}++describe('MemoryStorage · size 软警告数值明细', () => {+ it('分片超软上限: warning 不变, warningDetail 带 sizeBytes/软上限/硬上限', async () => {+ const storage = new MemoryStorage(dir, {+ ...DEFAULT_MEMORY_CONFIG,+ maxShardBytes: 64,+ });+ await storage.init(dir);+ const body = 'x'.repeat(100);+ const result = await storage.write(writeOpts(body));+ expect(result.ok).toBe(true);+ expect(result.warning).toBe('shard-size-exceeded');+ expect(result.warningDetail).toEqual({+ kind: 'shard-size-exceeded',+ sizeBytes: 100,+ softLimitBytes: 64,+ hardLimitBytes: DEFAULT_MEMORY_CONFIG.hardShardBytes,+ });+ });++ it('索引超软上限: warningDetail 是索引字节数, 不带 hardLimitBytes', async () => {+ const storage = new MemoryStorage(dir, {+ ...DEFAULT_MEMORY_CONFIG,+ maxIndexBytes: 8,+ });+ await storage.init(dir);+ const result = await storage.write(writeOpts('短内容'));+ expect(result.warning).toBe('index-size-exceeded');+ expect(result.warningDetail).toBeDefined();+ expect(result.warningDetail?.kind).toBe('index-size-exceeded');+ expect(result.warningDetail?.softLimitBytes).toBe(8);+ expect(result.warningDetail?.sizeBytes).toBeGreaterThan(8);+ expect(result.warningDetail?.hardLimitBytes).toBeUndefined();+ });++ it('分片与索引同时超限: 分片警告优先(与既有优先级一致)', async () => {+ const storage = new MemoryStorage(dir, {+ ...DEFAULT_MEMORY_CONFIG,+ maxShardBytes: 64,+ maxIndexBytes: 8,+ });+ await storage.init(dir);+ const result = await storage.write(writeOpts('x'.repeat(100)));+ expect(result.warning).toBe('shard-size-exceeded');+ expect(result.warningDetail?.kind).toBe('shard-size-exceeded');+ });++ it('未超限: warning 与 warningDetail 均不出现', async () => {+ const storage = new MemoryStorage(dir, DEFAULT_MEMORY_CONFIG);+ await storage.init(dir);+ const result = await storage.write(writeOpts('小分片'));+ expect(result.warning).toBeUndefined();+ expect(result.warningDetail).toBeUndefined();+ });++ it('assessWarning: 删源后索引回落则不再报警(consolidate 删源前的写入警告失真场景)', async () => {+ // 探针: 默认配置下量出 1 条 / 2 条时的真实索引字节+ const probe = new MemoryStorage(dir, DEFAULT_MEMORY_CONFIG);+ await probe.init(dir);+ await probe.write(writeOpts('内容 a', 'src-a'));+ const size1 = await probe.getIndexSize();+ await probe.write(writeOpts('内容 b', 'src-b'));+ const size2 = await probe.getIndexSize();+ expect(size2).toBeGreaterThan(size1);++ // 正式: 索引软上限落在两者之间 → 第二条写入报索引警告, 删掉一条后回落+ const dir2 = await mkdtemp(path.join(tmpdir(), 'memory-warning-'));+ try {+ const storage = new MemoryStorage(dir2, {+ ...DEFAULT_MEMORY_CONFIG,+ maxIndexBytes: Math.floor((size1 + size2) / 2),+ });+ await storage.init(dir2);+ await storage.write(writeOpts('内容 a', 'src-a'));+ const over = await storage.write(writeOpts('内容 b', 'src-b'));+ expect(over.warning).toBe('index-size-exceeded');++ await storage.delete('project_src-b.md');+ expect(await storage.assessWarning('project_src-a.md')).toBeUndefined();+ } finally {+ await rm(dir2, { recursive: true, force: true });+ }+ });++ it('assessWarning: 分片本身仍超软上限时保持分片警告明细', async () => {+ const storage = new MemoryStorage(dir, {+ ...DEFAULT_MEMORY_CONFIG,+ maxShardBytes: 64,+ });+ await storage.init(dir);+ await storage.write(writeOpts('x'.repeat(100)));+ const detail = await storage.assessWarning('project_warn-case.md');+ expect(detail?.kind).toBe('shard-size-exceeded');+ expect(detail?.sizeBytes).toBe(100);+ });+});diff --git a/packages/maker-core/src/memory/store.ts b/packages/maker-core/src/memory/store.tsindex 23f028ad64..3b80a2d8f4 100644--- a/packages/maker-core/src/memory/store.ts+++ b/packages/maker-core/src/memory/store.ts@@ -58,8 +58,10 @@ export interface ConsolidateResult {filename: string;/** 实际删除的源文件 (源不存在的会被跳过) */deletedSources: string[];- /** 写入 warning (通常 consolidate 后 size 会降, 但兜底带上) */+ /** 软警告: 删源后按最终磁盘状态重算 (可能与写入时点不同, 也可能出现/消失); 重算失败退回写入时点值 */warning?: WriteResult['warning'];+ /** 软警告数值明细, 与 warning 同生同灭 */+ warningDetail?: WriteResult['warningDetail'];}export class MakerMemoryStore {@@ -190,11 +192,22 @@ export class MakerMemoryStore {this.logger.warn('consolidate fts rebuild failed', { error: String(e) });}+ // 删源后索引已变小, 写入时点的软警告可能失真 — 以最终磁盘状态重算;+ // 重算失败时退回写入时点的值 (宁可保守报警, 不静默丢警告)+ let finalDetail = writeRes.warningDetail;+ try {+ finalDetail = await this.storage.assessWarning(writeRes.filename);+ } catch (e) {+ this.logger.warn('consolidate: reassess warning failed, using write-time detail', {+ error: String(e),+ });+ }+return {ok: true,filename: writeRes.filename,deletedSources: deleted,- ...(writeRes.warning ? { warning: writeRes.warning } : {}),+ ...(finalDetail ? { warning: finalDetail.kind, warningDetail: finalDetail } : {}),};}diff --git a/packages/maker-core/src/memory/system-prompt.md b/packages/maker-core/src/memory/system-prompt.mdindex 6f481f1fc4..9f5742cafb 100644--- a/packages/maker-core/src/memory/system-prompt.md+++ b/packages/maker-core/src/memory/system-prompt.md@@ -37,7 +37,7 @@ If a user message starts with `Save in memory:` or `记到 memory:`, treat the r## Size warnings-`memory_write` may return `warning: "shard-size-exceeded"` or `"index-size-exceeded"` — the write succeeded, but the shard or index is bigger than ideal. Read the offending shards and call `memory_consolidate({sources, target})` to merge / shrink atomically.+`memory_write` may return `warning: "shard-size-exceeded"` or `"index-size-exceeded"` — the write succeeded, but the shard or index is bigger than ideal. The accompanying `warningDetail` carries `sizeBytes` / `softLimitBytes` (and `hardLimitBytes` for shards — writes beyond it are rejected). Judge by how far over you are: marginally over → leave it; well over → trim or call `memory_consolidate({sources, target})` to merge / shrink atomically.## Tool selectiondiff --git a/packages/maker-core/src/memory/types.ts b/packages/maker-core/src/memory/types.tsindex f69c9ef5e8..b17b9d1037 100644--- a/packages/maker-core/src/memory/types.ts+++ b/packages/maker-core/src/memory/types.ts@@ -71,12 +71,25 @@ export interface WriteOptions {export type WriteWarning = 'shard-size-exceeded' | 'index-size-exceeded';+/** 软警告的数值明细: 让调用方判断超了多少, 而不是盲目瘦身 (见 #891) */+export interface WriteWarningDetail {+ kind: WriteWarning;+ /** 超限对象当前字节数 (分片 body 或 MEMORY.md 索引) */+ sizeBytes: number;+ /** 软上限 (默认分片 2048 / 索引 4096) */+ softLimitBytes: number;+ /** 分片硬上限 (默认 8192, 超过将被 reject); 索引警告无硬上限, 不带此字段 */+ hardLimitBytes?: number;+}+export interface WriteResult {ok: true;/** 写入后文件相对 storage dir 的名字 (e.g. 'feedback_xxx.md') */filename: string;/** 软警告: 调用方按 prompt 引导 consolidate */warning?: WriteWarning;+ /** 软警告数值明细, 与 warning 同生同灭 */+ warningDetail?: WriteWarningDetail;}export interface MemoryConfig {