Skip to content

Commit 0a53855

Browse files
author
linyuan.yang
committed
remeber
1 parent b968d2f commit 0a53855

10 files changed

Lines changed: 139 additions & 31 deletions

File tree

‎packages/sbot/prompts/memory/reader/default.md‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
## Long-term memory
22

3-
You have a long-term memory store that persists across conversations. You can only
4-
READ it — a separate curator model writes to it afterwards, from the transcript alone.
5-
Never try to edit or delete an entry yourself.
3+
You have a long-term memory store that persists across conversations. Ordinary durable
4+
information is curated afterwards from the transcript. When the user explicitly asks
5+
you to remember, save, or update a memory, call `remember_memory`. A successful call means
6+
the write was queued for background extraction; describe it as queued, not already stored.
67

78
### Available memories
89

@@ -16,6 +17,10 @@ exact wording, the reasoning behind it, edge cases, or an entry not listed above
1617

1718
### How to use
1819

20+
- **`remember_memory(scope, content)`** — queue a memory write when the user
21+
explicitly requests it. Use `workspace` for repository/project-specific information
22+
and `global` for cross-project user facts or preferences. Pass only the durable content,
23+
without the surrounding "remember this" instruction. Do not call it for implicit facts.
1924
- **`read_memory(slug, scope)`** — full body of one entry by its exact slug and required scope. Use when the user
2025
mentions a topic that **clearly matches an entry above** and the title alone isn't
2126
enough to act on.
@@ -24,8 +29,9 @@ exact wording, the reasoning behind it, edge cases, or an entry not listed above
2429
phrasing that matches no slug, or several entries you can't choose between.
2530

2631
Something fundamentally new — no related entry, no specific term to search — isn't worth
27-
a tool call. And for pure code/architecture questions, read the actual code; memory holds
28-
cross-conversation knowledge, not docs.
32+
a read/search tool call unless the user explicitly asks to persist it; then use
33+
`remember_memory`. For pure code/architecture questions, read the actual code; memory
34+
holds cross-conversation knowledge, not docs.
2935

3036
### Read before you act, not only when asked
3137

‎packages/scorpio.ai/src/Agents/Single/SingleAgentService.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { type StructuredToolInterface } from "@langchain/core/tools";
33
import { inject, T_StaticSystemPrompts, T_DynamicSystemPrompts, T_ModelCallTimeout, T_ToolOverflowDir, T_ChannelSessionId, truncate, formatError } from "../../Core";
44
import { IModelService } from "../../Model";
55
import { ISkillService } from "../../Skills";
6-
import { IMemoryService, MemoryToolProvider } from "../../Memory";
6+
import { IMemoryService, MemoryToolProvider, REMEMBER_MEMORY_TOOL_NAME } from "../../Memory";
77
import { IAgendaService, AgendaToolProvider } from "../../Agenda";
88
import { INoteService, NoteToolProvider } from "../../Note";
99
import { IWikiService } from "../../Wiki";
@@ -579,8 +579,16 @@ export class SingleAgentService extends AgentServiceBase {
579579
{ role: MessageRole.Human, content: query },
580580
...outputMessages,
581581
];
582-
if (this.memoryService) {
582+
const successfulToolCalls = new Set(outputMessages
583+
.filter(message => message.role === MessageRole.Tool && message.status === 'success')
584+
.map(message => message.tool_call_id));
585+
const rememberQueued = outputMessages.some(message => message.tool_calls?.some(call =>
586+
call.name === REMEMBER_MEMORY_TOOL_NAME && successfulToolCalls.has(call.id),
587+
));
588+
if (this.memoryService && !rememberQueued) {
583589
this.memoryService.extractFromConversation(conversation);
590+
} else if (rememberQueued) {
591+
this.logger?.debug('本轮 remember_memory 已处理显式写入,跳过后台记忆抽取');
584592
}
585593
if (this.agendaService) {
586594
this.agendaService.extractFromConversation(conversation, this.channelSessionId);

‎packages/scorpio.ai/src/Memory/Service/IMemoryService.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,13 @@ export interface IMemoryService {
5050
*/
5151
search(query: string, limit?: number): Promise<MemorySearchHit[]>;
5252

53-
/** 工具描述(注入到 read_memory / search_memory 工具的 description 字段)。 */
53+
/**
54+
* 用户显式要求保存时使用:把消息持久化到 extract 队列并返回 job id。
55+
* 消费时绕过 Selector 的 shouldWrite 否决,并把 mutation 锁定到 requested scope。
56+
*/
57+
remember(content: string, scope: MemoryScope): Promise<number>;
58+
59+
/** read_memory / search_memory 的工具描述。 */
5460
getToolDescs(): MemoryToolDescs;
5561

5662
/**

‎packages/scorpio.ai/src/Memory/Service/MemoryService.ts‎

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,27 @@ export class MemoryService {
438438
.slice(0, cap);
439439
}
440440

441+
async remember(content: string, scope: MemoryScope, viewTarget: MemoryTarget): Promise<number> {
442+
const normalized = content.trim();
443+
if (!normalized) throw new Error('Memory content is empty');
444+
// 在入队前验证 view 是否具备 requested scope,避免产生永远无法执行的任务。
445+
this.entryTarget(scope, viewTarget);
446+
try {
447+
const jobId = this.store.pushPendingMessages(
448+
[{ role: MessageRole.Human, content: normalized }],
449+
Date.now(),
450+
viewTarget,
451+
scope,
452+
);
453+
this.logMemory('info', `显式记忆已入队:job=${jobId},scope=${scope},内容=${truncateForLog(normalized)}`);
454+
void this.checkJobs();
455+
return jobId;
456+
} catch (e: any) {
457+
this.logMemory('warn', `显式记忆入队失败:scope=${scope},错误=${formatError(e, true)}`);
458+
throw e;
459+
}
460+
}
461+
441462
getToolDescs(): MemoryToolDescs {
442463
return DEFAULT_TOOL_DESCS;
443464
}
@@ -602,20 +623,19 @@ export class MemoryService {
602623

603624
// ── MemoryLLM CRUD 抽取(原 MemoryWriterWorker) ──
604625

605-
/**
606-
* 单轮抽取:把一组对话消息喂给 MemoryLLM,应用返回的 ops。
607-
* 模型调用失败会抛出,由 checkJobs 决定是否标记 pending job 为 failed。
608-
*/
626+
/** 普通 turn 和 remember_memory 共用同一条 extract 执行链;requestedScope 表示显式写入。 */
609627
private async extractFromMessages(job: PendingMemoryJobRow, target: MemoryTarget): Promise<MemoryWriterOpStats> {
610628
const messages = job.messages ?? [];
629+
const explicitScope = job.requestedScope;
611630
if (messages.length === 0) {
612631
return { create: 0, update: 0, delete: 0, noop: 1, failed: 0 };
613632
}
614633

615634
const conversation = renderConversation(messages);
616635
const allRows = await this.listAll(target);
617-
const selection = await this.selectExtractionCandidates(conversation, allRows, target);
618-
if (!selection.shouldWrite && selection.rows.length === 0) {
636+
const candidateRows = explicitScope ? allRows.filter(row => row.scope === explicitScope) : allRows;
637+
const selection = await this.selectExtractionCandidates(conversation, candidateRows, target);
638+
if (!explicitScope && !selection.shouldWrite && selection.rows.length === 0) {
619639
return { create: 0, update: 0, delete: 0, noop: 1, failed: 0 };
620640
}
621641

@@ -631,6 +651,7 @@ export class MemoryService {
631651
row.body,
632652
].join('\n')).join('\n\n---\n\n');
633653
const input = [
654+
...(explicitScope ? [`# Requested scope`, explicitScope, ``] : []),
634655
`# Current workspace`,
635656
``,
636657
target.scope === MemoryScope.Workspace
@@ -647,37 +668,59 @@ export class MemoryService {
647668
``,
648669
`---`,
649670
``,
650-
`Decide what — if anything — to record. Default to a single \`noop\` if`,
651-
`nothing in this transcript meets the high-signal bar.`,
671+
explicitScope
672+
? `Persist this explicitly requested memory now; do not apply the normal high-signal veto.`
673+
: `Decide what — if anything — to record. Default to a single \`noop\` if`,
674+
...(explicitScope ? [] : [`nothing in this transcript meets the high-signal bar.`]),
652675
].join('\n');
653-
654676
const llmMessages: ChatMessage[] = [
655677
{
656678
role: MessageRole.System,
657679
content: [
658680
this.writerPrompt,
659-
`# Authoritative two-stage curation contract`,
660-
`This is the final curation pass. The selected existing memories below include their full bodies.`,
681+
explicitScope ? `# Explicit persistence contract` : `# Authoritative two-stage curation contract`,
682+
explicitScope
683+
? `Return exactly one create/update operation, or noop only when a selected entry already contains the same information. Never delete.`
684+
: `This is the final curation pass. The selected existing memories below include their full bodies.`,
661685
`Only update or delete an existing memory shown in that selected set, preserving its exact scope and slug.`,
662686
`When changing a body, return the complete final body without the H1 title line and use bodyMode="replace"; no later merge pass will run.`,
663687
`Create only when none of the selected entries covers the durable fact.`,
664688
`Delete only when the full body and conversation clearly prove the entry is false, superseded, or explicitly forgotten.`,
665-
`Default to noop when the selector was cautious but the full evidence does not justify a mutation.`,
689+
explicitScope
690+
? `Every mutation must use scope="${explicitScope}"; the runtime also enforces it.`
691+
: `Default to noop when the selector was cautious but the full evidence does not justify a mutation.`,
666692
`# Memory scope routing`,
667693
MEMORY_SCOPE_WRITER_INSTRUCTION,
668694
].join('\n\n'),
669695
},
670696
{ role: MessageRole.Human, content: input },
671697
];
672-
673698
const result = await this.writerModel.invokeStructured<MemoryWriteOutput>(MemoryWriteOutputSchema, llmMessages);
674-
// 抽取路径:本轮对话确实提到了被 update 的条目 → evidence +1
675-
return await this.applyOps(result.ops, {
699+
700+
if (!explicitScope) {
701+
return this.applyOps(result.ops, {
702+
evidenceDelta: 1,
703+
target,
704+
fixedScope: null,
705+
allowedExisting: new Set(selection.rows.map(row => MemoryService.rowKey(row))),
706+
});
707+
}
708+
709+
if (result.ops.length !== 1) throw new Error(`Explicit Writer must return exactly one operation`);
710+
const op = result.ops[0];
711+
if (op.action === MemoryOpAction.Delete) throw new Error(`Explicit Writer cannot delete memories`);
712+
if (op.action === MemoryOpAction.Noop) {
713+
if (selection.rows.length === 0) throw new Error(`Writer returned noop without an existing match: ${op.reason}`);
714+
return { create: 0, update: 0, delete: 0, noop: 1, failed: 0 };
715+
}
716+
const stats = await this.applyOps([op], {
676717
evidenceDelta: 1,
677718
target,
678-
fixedScope: null,
719+
fixedScope: explicitScope,
679720
allowedExisting: new Set(selection.rows.map(row => MemoryService.rowKey(row))),
680721
});
722+
if (stats.failed > 0) throw new Error(`Writer operation was not applied`);
723+
return stats;
681724
}
682725

683726
private async selectExtractionCandidates(

‎packages/scorpio.ai/src/Memory/Service/MemoryServiceView.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ export abstract class MemoryServiceView implements IMemoryService {
3131
return this.owner.search(query, limit, this.target);
3232
}
3333

34+
remember(content: string, scope: MemoryScope): Promise<number> {
35+
return this.owner.remember(content, scope, this.target);
36+
}
37+
3438
getToolDescs(): MemoryToolDescs {
3539
return this.owner.getToolDescs();
3640
}

‎packages/scorpio.ai/src/Memory/Storage/IMemoryStore.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,8 @@ interface PendingMemoryJobBase {
140140
id: number;
141141
type: MemoryPendingJobType;
142142
messages?: ChatMessage[];
143+
/** 仅 remember_memory 入队的 extract job 携带;存在时跳过 Selector 否决并锁定写入 scope。 */
144+
requestedScope?: MemoryScope;
143145
status: MemoryPendingJobStatus;
144146
attemptCount: number;
145147
errorMessage: string | null;
@@ -215,8 +217,8 @@ export interface IMemoryStore {
215217
// 全部同步:底层 better-sqlite3 是同步 API;MemoryService 依赖
216218
// "push 的 SQL 在 kick 前已落库" 这一点来避免漏单。
217219

218-
/** 入队一轮对话的消息快照,返回插入行 id。 */
219-
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget): number;
220+
/** 入队消息快照;requestedScope 仅由 remember_memory 传入。 */
221+
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget, requestedScope?: MemoryScope): number;
220222

221223
/** 入队一次 memory 整理 job,返回插入行 id。 */
222224
pushPendingConsolidate(now: number, target: MemoryTarget): number;

‎packages/scorpio.ai/src/Memory/Storage/MemoryStore.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -364,8 +364,8 @@ export class MemoryStore implements IMemoryStore {
364364

365365
// ── 待处理 job 队列 ──
366366

367-
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget): number {
368-
return this.pushPendingJob(MemoryPendingJobType.Extract, { messages, ...target }, now);
367+
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget, requestedScope?: MemoryScope): number {
368+
return this.pushPendingJob(MemoryPendingJobType.Extract, { messages, ...target, ...(requestedScope ? { requestedScope } : {}) }, now);
369369
}
370370

371371
pushPendingConsolidate(now: number, target: MemoryTarget): number {
@@ -548,13 +548,21 @@ export class MemoryStore implements IMemoryStore {
548548
return row ? this.mapRow(row) : null;
549549
}
550550

551-
private parsePendingPayload(json: string | null | undefined): { messages?: ChatMessage[]; target: MemoryTarget } {
551+
private parsePendingPayload(json: string | null | undefined): {
552+
messages?: ChatMessage[];
553+
requestedScope?: MemoryScope;
554+
target: MemoryTarget;
555+
} {
552556
try {
553557
const parsed = JSON.parse(json ?? '{}');
554558
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
555559
return { target: { scope: MemoryScope.Global } };
556560
}
557561
const messages = Array.isArray((parsed as any).messages) ? ((parsed as any).messages as ChatMessage[]) : undefined;
562+
const rawRequestedScope = (parsed as any).requestedScope;
563+
const requestedScope = rawRequestedScope === MemoryScope.Global || rawRequestedScope === MemoryScope.Workspace
564+
? rawRequestedScope
565+
: undefined;
558566
const rawWorkspace = (parsed as any).workspace;
559567
const workspace = rawWorkspace
560568
&& typeof rawWorkspace === 'object'
@@ -565,7 +573,11 @@ export class MemoryStore implements IMemoryStore {
565573
const target: MemoryTarget = workspace
566574
? { scope: MemoryScope.Workspace, workspace }
567575
: { scope: MemoryScope.Global };
568-
return { ...(messages ? { messages } : {}), target };
576+
return {
577+
...(messages ? { messages } : {}),
578+
...(requestedScope ? { requestedScope } : {}),
579+
target,
580+
};
569581
} catch {
570582
return { target: { scope: MemoryScope.Global } };
571583
}
@@ -604,6 +616,7 @@ export class MemoryStore implements IMemoryStore {
604616
id: r.id,
605617
type,
606618
messages: type === MemoryPendingJobType.Extract ? (payload.messages ?? []) : undefined,
619+
requestedScope: type === MemoryPendingJobType.Extract ? payload.requestedScope : undefined,
607620
status: this.normalizePendingStatus(r.status),
608621
attemptCount: r.attempt_count ?? 0,
609622
errorMessage: r.error_message ?? null,

‎packages/scorpio.ai/src/Memory/Tools/MemoryToolProvider.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@ import { MemoryScope } from "../Storage/IMemoryStore";
55

66
export const READ_MEMORY_TOOL_NAME = 'read_memory' as const;
77
export const SEARCH_MEMORY_TOOL_NAME = 'search_memory' as const;
8+
export const REMEMBER_MEMORY_TOOL_NAME = 'remember_memory' as const;
9+
const REMEMBER_MEMORY_TOOL_DESCRIPTION = 'Queue a memory only when the user explicitly asks to remember/save it. ' +
10+
'Use workspace for project-specific information and global for cross-project facts or preferences.';
811

912
/**
10-
* 工厂方法集合:用 IMemoryService 生成 read_memory / search_memory 两个 tool。
13+
* 工厂方法集合:用 IMemoryService 生成 read_memory / search_memory / remember_memory 工具。
1114
*
1215
* 设计:
1316
* - 工具描述从 service.getToolDescs() 取,允许将来按 profile 覆盖
@@ -18,11 +21,32 @@ export class MemoryToolProvider {
1821
static getTools(service: IMemoryService): DynamicStructuredTool[] {
1922
const descs = service.getToolDescs();
2023
return [
24+
MemoryToolProvider.createRememberTool(service, REMEMBER_MEMORY_TOOL_DESCRIPTION),
2125
MemoryToolProvider.createReadTool(service, descs.read),
2226
MemoryToolProvider.createSearchTool(service, descs.search),
2327
];
2428
}
2529

30+
private static createRememberTool(
31+
service: IMemoryService,
32+
description: string,
33+
): DynamicStructuredTool {
34+
return new DynamicStructuredTool({
35+
name: REMEMBER_MEMORY_TOOL_NAME,
36+
description,
37+
schema: z.object({
38+
scope: z.enum([MemoryScope.Global, MemoryScope.Workspace])
39+
.describe('Where the memory must be stored. Use workspace for project-specific information.'),
40+
content: z.string().trim().min(1).max(8000)
41+
.describe('The durable fact, preference, workflow, or decision to remember; omit the save request itself.'),
42+
}),
43+
func: async ({ scope, content }) => {
44+
const jobId = await service.remember(content, scope);
45+
return `Memory write queued: job=${jobId}, scope=${scope}`;
46+
},
47+
});
48+
}
49+
2650
private static createReadTool(service: IMemoryService, description: string): DynamicStructuredTool {
2751
return new DynamicStructuredTool({
2852
name: READ_MEMORY_TOOL_NAME,

‎packages/scorpio.ai/src/Memory/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,5 @@ export {
4848
MemoryToolProvider,
4949
READ_MEMORY_TOOL_NAME,
5050
SEARCH_MEMORY_TOOL_NAME,
51+
REMEMBER_MEMORY_TOOL_NAME,
5152
} from './Tools/MemoryToolProvider';

‎packages/scorpio.ai/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,7 @@ export {
244244
MemoryToolProvider,
245245
READ_MEMORY_TOOL_NAME,
246246
SEARCH_MEMORY_TOOL_NAME,
247+
REMEMBER_MEMORY_TOOL_NAME,
247248
MemoryKind,
248249
MemoryScope,
249250
type StoredMemoryRow,

0 commit comments

Comments
 (0)