Skip to content

Commit 17084d2

Browse files
author
linyuan.yang
committed
整理 remember 流程
1 parent 0a53855 commit 17084d2

6 files changed

Lines changed: 75 additions & 82 deletions

File tree

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

Lines changed: 2 additions & 10 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, REMEMBER_MEMORY_TOOL_NAME } from "../../Memory";
6+
import { IMemoryService, MemoryToolProvider } from "../../Memory";
77
import { IAgendaService, AgendaToolProvider } from "../../Agenda";
88
import { INoteService, NoteToolProvider } from "../../Note";
99
import { IWikiService } from "../../Wiki";
@@ -579,16 +579,8 @@ export class SingleAgentService extends AgentServiceBase {
579579
{ role: MessageRole.Human, content: query },
580580
...outputMessages,
581581
];
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) {
582+
if (this.memoryService) {
589583
this.memoryService.extractFromConversation(conversation);
590-
} else if (rememberQueued) {
591-
this.logger?.debug('本轮 remember_memory 已处理显式写入,跳过后台记忆抽取');
592584
}
593585
if (this.agendaService) {
594586
this.agendaService.extractFromConversation(conversation, this.channelSessionId);

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ export interface IMemoryService {
5151
search(query: string, limit?: number): Promise<MemorySearchHit[]>;
5252

5353
/**
54-
* 用户显式要求保存时使用:把消息持久化到 extract 队列并返回 job id。
55-
* 消费时绕过 Selector 的 shouldWrite 否决,并把 mutation 锁定到 requested scope。
54+
* 用户显式要求保存时使用:暂存 pending remember message 并返回 id;
55+
* turn-end Extract 会统一接走并按消息处理。
5656
*/
5757
remember(content: string, scope: MemoryScope): Promise<number>;
5858

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

Lines changed: 18 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -444,15 +444,9 @@ export class MemoryService {
444444
// 在入队前验证 view 是否具备 requested scope,避免产生永远无法执行的任务。
445445
this.entryTarget(scope, viewTarget);
446446
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;
447+
const id = this.store.pushPendingRememberMessage(normalized, scope, Date.now(), viewTarget);
448+
this.logMemory('info', `显式记忆消息已暂存:id=${id},scope=${scope},内容=${truncateForLog(normalized)}`);
449+
return id;
456450
} catch (e: any) {
457451
this.logMemory('warn', `显式记忆入队失败:scope=${scope},错误=${formatError(e, true)}`);
458452
throw e;
@@ -623,19 +617,22 @@ export class MemoryService {
623617

624618
// ── MemoryLLM CRUD 抽取(原 MemoryWriterWorker) ──
625619

626-
/** 普通 turn 和 remember_memory 共用同一条 extract 执行链;requestedScope 表示显式写入。 */
620+
/** pending remember message 已在入队时合并进 messages,后续完全复用普通抽取。 */
627621
private async extractFromMessages(job: PendingMemoryJobRow, target: MemoryTarget): Promise<MemoryWriterOpStats> {
628622
const messages = job.messages ?? [];
629-
const explicitScope = job.requestedScope;
630623
if (messages.length === 0) {
631624
return { create: 0, update: 0, delete: 0, noop: 1, failed: 0 };
632625
}
633626

634627
const conversation = renderConversation(messages);
635628
const allRows = await this.listAll(target);
636-
const candidateRows = explicitScope ? allRows.filter(row => row.scope === explicitScope) : allRows;
629+
const explicitScopes = new Set(messages
630+
.filter(message => message.additional_kwargs?.explicitMemory === true)
631+
.map(message => message.additional_kwargs?.memoryScope as MemoryScope));
632+
const fixedScope = explicitScopes.size === 1 ? [...explicitScopes][0] : null;
633+
const candidateRows = fixedScope ? allRows.filter(row => row.scope === fixedScope) : allRows;
637634
const selection = await this.selectExtractionCandidates(conversation, candidateRows, target);
638-
if (!explicitScope && !selection.shouldWrite && selection.rows.length === 0) {
635+
if (explicitScopes.size === 0 && !selection.shouldWrite && selection.rows.length === 0) {
639636
return { create: 0, update: 0, delete: 0, noop: 1, failed: 0 };
640637
}
641638

@@ -651,7 +648,6 @@ export class MemoryService {
651648
row.body,
652649
].join('\n')).join('\n\n---\n\n');
653650
const input = [
654-
...(explicitScope ? [`# Requested scope`, explicitScope, ``] : []),
655651
`# Current workspace`,
656652
``,
657653
target.scope === MemoryScope.Workspace
@@ -668,59 +664,35 @@ export class MemoryService {
668664
``,
669665
`---`,
670666
``,
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.`]),
667+
`Decide what — if anything — to record. Default to a single \`noop\` if`,
668+
`nothing in this transcript meets the high-signal bar.`,
675669
].join('\n');
676670
const llmMessages: ChatMessage[] = [
677671
{
678672
role: MessageRole.System,
679673
content: [
680674
this.writerPrompt,
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.`,
675+
`# Authoritative two-stage curation contract`,
676+
`This is the final curation pass. The selected existing memories below include their full bodies.`,
677+
...(explicitScopes.size > 0 ? [`Messages marked [EXPLICIT MEMORY WRITE] must be persisted using their required scope.`] : []),
685678
`Only update or delete an existing memory shown in that selected set, preserving its exact scope and slug.`,
686679
`When changing a body, return the complete final body without the H1 title line and use bodyMode="replace"; no later merge pass will run.`,
687680
`Create only when none of the selected entries covers the durable fact.`,
688681
`Delete only when the full body and conversation clearly prove the entry is false, superseded, or explicitly forgotten.`,
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.`,
682+
`Default to noop when the selector was cautious but the full evidence does not justify a mutation.`,
692683
`# Memory scope routing`,
693684
MEMORY_SCOPE_WRITER_INSTRUCTION,
694685
].join('\n\n'),
695686
},
696687
{ role: MessageRole.Human, content: input },
697688
];
698689
const result = await this.writerModel.invokeStructured<MemoryWriteOutput>(MemoryWriteOutputSchema, llmMessages);
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], {
690+
return await this.applyOps(result.ops, {
717691
evidenceDelta: 1,
718692
target,
719-
fixedScope: explicitScope,
693+
fixedScope,
720694
allowedExisting: new Set(selection.rows.map(row => MemoryService.rowKey(row))),
721695
});
722-
if (stats.failed > 0) throw new Error(`Writer operation was not applied`);
723-
return stats;
724696
}
725697

726698
private async selectExtractionCandidates(

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

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

220-
/** 入队消息快照;requestedScope 仅由 remember_memory 传入。 */
221-
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget, requestedScope?: MemoryScope): number;
218+
/** 暂存一条 remember_memory 消息,等待 turn-end Extract 统一接走。 */
219+
pushPendingRememberMessage(content: string, scope: MemoryScope, now: number, target: MemoryTarget): number;
220+
221+
/** 入队一轮对话的消息快照;同时接走当前 target 下所有 pending remember message。 */
222+
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget): number;
222223

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

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

Lines changed: 46 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import {
2121
MemoryScope,
2222
} from "./IMemoryStore";
2323
import { HybridSearcher } from "../../Retrieval";
24-
import type { ChatMessage } from "../../Saver";
24+
import { MessageRole, type ChatMessage } from "../../Saver";
2525

2626
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
2727
const MEMORY_KINDS = new Set<string>(Object.values(MemoryKind));
@@ -104,6 +104,16 @@ export class MemoryStore implements IMemoryStore {
104104
updated_at INTEGER NOT NULL
105105
);
106106
CREATE INDEX IF NOT EXISTS idx_pending_status_id ON memory_pending_messages(status, id);
107+
108+
CREATE TABLE IF NOT EXISTS memory_pending_remember_messages (
109+
id INTEGER PRIMARY KEY AUTOINCREMENT,
110+
content TEXT NOT NULL,
111+
requested_scope TEXT NOT NULL,
112+
workspace_key TEXT,
113+
created_at INTEGER NOT NULL
114+
);
115+
CREATE INDEX IF NOT EXISTS idx_pending_remember_workspace_id
116+
ON memory_pending_remember_messages(workspace_key, id);
107117
`);
108118
// 旧库去列:description 曾是独立的 menu 标签,现已并入 title(= 文件 H1)。
109119
// 不搬运旧值(老条目的 menu 行退化成当时那个短标题,consolidate 会逐步重写),
@@ -364,8 +374,39 @@ export class MemoryStore implements IMemoryStore {
364374

365375
// ── 待处理 job 队列 ──
366376

367-
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget, requestedScope?: MemoryScope): number {
368-
return this.pushPendingJob(MemoryPendingJobType.Extract, { messages, ...target, ...(requestedScope ? { requestedScope } : {}) }, now);
377+
pushPendingRememberMessage(content: string, scope: MemoryScope, now: number, target: MemoryTarget): number {
378+
const result = this.db.prepare(`
379+
INSERT INTO memory_pending_remember_messages (content, requested_scope, workspace_key, created_at)
380+
VALUES (@content, @scope, @workspaceKey, @now)
381+
`).run({
382+
content,
383+
scope,
384+
workspaceKey: target.scope === MemoryScope.Workspace ? target.workspace.key : null,
385+
now,
386+
});
387+
return Number(result.lastInsertRowid);
388+
}
389+
390+
pushPendingMessages(messages: ChatMessage[], now: number, target: MemoryTarget): number {
391+
const workspaceKey = target.scope === MemoryScope.Workspace ? target.workspace.key : null;
392+
return this.db.transaction(() => {
393+
const where = workspaceKey === null ? `workspace_key IS NULL` : `workspace_key = @workspaceKey`;
394+
const params = workspaceKey === null ? {} : { workspaceKey };
395+
const pending = this.db.prepare(`
396+
SELECT content, requested_scope FROM memory_pending_remember_messages
397+
WHERE ${where} ORDER BY id ASC
398+
`).all(params) as Array<{ content: string; requested_scope: string }>;
399+
const jobMessages: ChatMessage[] = pending.length === 0 ? messages : pending.map(row => ({
400+
role: MessageRole.Human,
401+
content: `[EXPLICIT MEMORY WRITE]\nRequired scope: ${row.requested_scope}\n\n${row.content}`,
402+
additional_kwargs: { explicitMemory: true, memoryScope: row.requested_scope },
403+
}));
404+
const jobId = this.pushPendingJob(MemoryPendingJobType.Extract, { messages: jobMessages, ...target }, now);
405+
if (pending.length > 0) {
406+
this.db.prepare(`DELETE FROM memory_pending_remember_messages WHERE ${where}`).run(params);
407+
}
408+
return jobId;
409+
})();
369410
}
370411

371412
pushPendingConsolidate(now: number, target: MemoryTarget): number {
@@ -548,21 +589,13 @@ export class MemoryStore implements IMemoryStore {
548589
return row ? this.mapRow(row) : null;
549590
}
550591

551-
private parsePendingPayload(json: string | null | undefined): {
552-
messages?: ChatMessage[];
553-
requestedScope?: MemoryScope;
554-
target: MemoryTarget;
555-
} {
592+
private parsePendingPayload(json: string | null | undefined): { messages?: ChatMessage[]; target: MemoryTarget } {
556593
try {
557594
const parsed = JSON.parse(json ?? '{}');
558595
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
559596
return { target: { scope: MemoryScope.Global } };
560597
}
561598
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;
566599
const rawWorkspace = (parsed as any).workspace;
567600
const workspace = rawWorkspace
568601
&& typeof rawWorkspace === 'object'
@@ -573,11 +606,7 @@ export class MemoryStore implements IMemoryStore {
573606
const target: MemoryTarget = workspace
574607
? { scope: MemoryScope.Workspace, workspace }
575608
: { scope: MemoryScope.Global };
576-
return {
577-
...(messages ? { messages } : {}),
578-
...(requestedScope ? { requestedScope } : {}),
579-
target,
580-
};
609+
return { ...(messages ? { messages } : {}), target };
581610
} catch {
582611
return { target: { scope: MemoryScope.Global } };
583612
}
@@ -616,7 +645,6 @@ export class MemoryStore implements IMemoryStore {
616645
id: r.id,
617646
type,
618647
messages: type === MemoryPendingJobType.Extract ? (payload.messages ?? []) : undefined,
619-
requestedScope: type === MemoryPendingJobType.Extract ? payload.requestedScope : undefined,
620648
status: this.normalizePendingStatus(r.status),
621649
attemptCount: r.attempt_count ?? 0,
622650
errorMessage: r.error_message ?? null,

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ export class MemoryToolProvider {
4141
.describe('The durable fact, preference, workflow, or decision to remember; omit the save request itself.'),
4242
}),
4343
func: async ({ scope, content }) => {
44-
const jobId = await service.remember(content, scope);
45-
return `Memory write queued: job=${jobId}, scope=${scope}`;
44+
const pendingId = await service.remember(content, scope);
45+
return `Memory write queued: pending=${pendingId}, scope=${scope}`;
4646
},
4747
});
4848
}

0 commit comments

Comments
 (0)