Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(agent-signal): execAgent migration — serverRuntime bridge + completion projection + async memoryWriter + executeSelfIteration removal (#15392)

Arvin Xud9673c3c414c
diff --git a/package.json b/package.json
index 6bac5d4b387..7b3f11c4753 100644
--- a/package.json
+++ b/package.json
@@ -215,6 +215,7 @@
"@lobechat/builtin-tool-agent-builder": "workspace:*",
"@lobechat/builtin-tool-agent-documents": "workspace:*",
"@lobechat/builtin-tool-agent-management": "workspace:*",
+ "@lobechat/builtin-tool-agent-signal": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-calculator": "workspace:*",
"@lobechat/builtin-tool-claude-code": "workspace:*",
diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.ts
index cd6329ac0aa..42848475e12 100644
--- a/packages/agent-signal/src/source/sourceTypes.ts
+++ b/packages/agent-signal/src/source/sourceTypes.ts
@@ -32,6 +32,12 @@ export interface AgentSignalSourcePayloadMap {
[AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted]: {
agentId?: string;
operationId: string;
+ /**
+ * Opaque completion side-effect payload attached by the executor for
+ * builtin background agents (e.g. self-iteration tool outcomes used for
+ * receipt projection). Carried as-is; the producing layer owns its shape.
+ */
+ selfIteration?: unknown;
serializedContext?: string;
steps: number;
topicId?: string;
diff --git a/packages/builtin-agents/src/agents/nightly-review/index.ts b/packages/builtin-agents/src/agents/nightly-review/index.ts
index 71b6ea608a0..77881b54095 100644
--- a/packages/builtin-agents/src/agents/nightly-review/index.ts
+++ b/packages/builtin-agents/src/agents/nightly-review/index.ts
@@ -1,3 +1,6 @@
+import { DEFAULT_MINI_PROVIDER } from '@lobechat/business-const';
+import { DEFAULT_MINI_MODEL } from '@lobechat/const';
+
import type { BuiltinAgentDefinition } from '../../types';
import { BUILTIN_AGENT_SLUGS } from '../../types';
@@ -12,6 +15,12 @@ import { BUILTIN_AGENT_SLUGS } from '../../types';
* registration is dormant by design.
*/
export const NIGHTLY_REVIEW: BuiltinAgentDefinition = {
+ // Background self-iteration runs on the cheap mini system model (matching the
+ // legacy executeSelfIteration path), not the user's default chat model.
+ persist: {
+ model: DEFAULT_MINI_MODEL,
+ provider: DEFAULT_MINI_PROVIDER,
+ },
runtime: {
plugins: ['agent-signal-review'],
systemRole:
diff --git a/packages/builtin-agents/src/agents/self-feedback-intent/index.ts b/packages/builtin-agents/src/agents/self-feedback-intent/index.ts
index 0f4b2ee4936..062f1a1ad6e 100644
--- a/packages/builtin-agents/src/agents/self-feedback-intent/index.ts
+++ b/packages/builtin-agents/src/agents/self-feedback-intent/index.ts
@@ -1,3 +1,6 @@
+import { DEFAULT_MINI_PROVIDER } from '@lobechat/business-const';
+import { DEFAULT_MINI_MODEL } from '@lobechat/const';
+
import type { BuiltinAgentDefinition } from '../../types';
import { BUILTIN_AGENT_SLUGS } from '../../types';
@@ -12,6 +15,12 @@ import { BUILTIN_AGENT_SLUGS } from '../../types';
* follow-up PR.
*/
export const SELF_FEEDBACK_INTENT: BuiltinAgentDefinition = {
+ // Background self-iteration runs on the cheap mini system model (matching the
+ // legacy executeSelfIteration path), not the user's default chat model.
+ persist: {
+ model: DEFAULT_MINI_MODEL,
+ provider: DEFAULT_MINI_PROVIDER,
+ },
runtime: {
plugins: ['agent-signal-feedback-intent'],
systemRole:
diff --git a/packages/builtin-agents/src/agents/self-reflection/index.ts b/packages/builtin-agents/src/agents/self-reflection/index.ts
index d9d16e506c1..e3f902d1e6d 100644
--- a/packages/builtin-agents/src/agents/self-reflection/index.ts
+++ b/packages/builtin-agents/src/agents/self-reflection/index.ts
@@ -1,3 +1,6 @@
+import { DEFAULT_MINI_PROVIDER } from '@lobechat/business-const';
+import { DEFAULT_MINI_MODEL } from '@lobechat/const';
+
import type { BuiltinAgentDefinition } from '../../types';
import { BUILTIN_AGENT_SLUGS } from '../../types';
@@ -10,6 +13,12 @@ import { BUILTIN_AGENT_SLUGS } from '../../types';
* receipt table, idempotency namespace) are registered in a follow-up PR.
*/
export const SELF_REFLECTION: BuiltinAgentDefinition = {
+ // Background self-iteration runs on the cheap mini system model (matching the
+ // legacy executeSelfIteration path), not the user's default chat model.
+ persist: {
+ model: DEFAULT_MINI_MODEL,
+ provider: DEFAULT_MINI_PROVIDER,
+ },
runtime: {
plugins: ['agent-signal-reflection'],
systemRole:
diff --git a/packages/builtin-tool-agent-signal/src/index.ts b/packages/builtin-tool-agent-signal/src/index.ts
index 17667e6918a..4a1a6e050f4 100644
--- a/packages/builtin-tool-agent-signal/src/index.ts
+++ b/packages/builtin-tool-agent-signal/src/index.ts
@@ -14,11 +14,11 @@ export {
type AgentSignalToolApiName,
} from './shared/apiNames';
export {
+ type AgentSignalRuntimePrimitive,
+ type AgentSignalRuntimeService,
type AgentSignalToolContext,
AgentSignalToolExecutionRuntime,
type AgentSignalToolExecutionRuntimeOptions,
- type AgentSignalToolInvocationResult,
- type AgentSignalToolService,
type ToolResultKind,
} from './shared/ExecutionRuntime';
export {
diff --git a/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.ts b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.ts
index 6f547a5a43c..325d5a0a130 100644
--- a/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.ts
+++ b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.ts
@@ -1,17 +1,16 @@
import { describe, expect, it, vi } from 'vitest';
import { AGENT_SIGNAL_REVIEW_TOOL_API_NAMES } from './apiNames';
-import { AgentSignalToolExecutionRuntime, type AgentSignalToolService } from './ExecutionRuntime';
-
-const makeService = (
- impl: AgentSignalToolService['invoke'] = vi.fn(async () => ({ data: { ok: true } })),
-): AgentSignalToolService => ({ invoke: impl });
+import {
+ type AgentSignalRuntimeService,
+ AgentSignalToolExecutionRuntime,
+} from './ExecutionRuntime';
describe('AgentSignalToolExecutionRuntime', () => {
it('exposes one bound method per advertised api name', () => {
const runtime = new AgentSignalToolExecutionRuntime({
apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
- service: makeService(),
+ service: {},
});
for (const apiName of AGENT_SIGNAL_REVIEW_TOOL_API_NAMES) {
@@ -19,50 +18,68 @@ describe('AgentSignalToolExecutionRuntime', () => {
}
});
- it('dispatches to the service and stamps a mutation kind onto the result', async () => {
- const invoke = vi.fn(async () => ({ data: { memoryId: 'mem_1', summary: 'stored' } }));
+ it('routes a mutation to its primitive and stamps a mutation kind', async () => {
+ const writeMemory = vi.fn(async () => ({ memoryId: 'mem_1', summary: 'stored' }));
const runtime = new AgentSignalToolExecutionRuntime({
apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
- service: makeService(invoke),
+ service: { writeMemory },
});
- const writeMemory = runtime.writeMemory as (i: unknown, c: unknown) => Promise<any>;
- const result = await writeMemory({ content: 'x' }, { userId: 'u', agentId: 'a' });
-
- expect(invoke).toHaveBeenCalledWith(
- 'writeMemory',
+ const result = await (runtime.writeMemory as any)(
{ content: 'x' },
- { userId: 'u', agentId: 'a' },
+ { agentId: 'a', userId: 'u' },
);
+
+ expect(writeMemory).toHaveBeenCalledWith({ content: 'x' }, { agentId: 'a', userId: 'u' });
expect(result.success).toBe(true);
- expect(result.state).toEqual({ kind: 'mutation', memoryId: 'mem_1', summary: 'stored' });
+ expect(result.state).toEqual({
+ apiName: 'writeMemory',
+ kind: 'mutation',
+ memoryId: 'mem_1',
+ summary: 'stored',
+ });
expect(JSON.parse(result.content)).toEqual(result.state);
});
it('stamps read / artifact kinds correctly', async () => {
+ const service: AgentSignalRuntimeService = { getManagedSkill: async () => ({ items: [] }) };
const runtime = new AgentSignalToolExecutionRuntime({
apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
- service: makeService(async () => ({ data: { items: [] } })),
+ service,
});
- const digest = await (runtime.getEvidenceDigest as any)({}, {});
- expect(digest.state.kind).toBe('read');
+ const skill = await (runtime.getManagedSkill as any)({}, {});
+ expect(skill.state.kind).toBe('read');
- const idea = await (runtime.recordSelfReviewIdea as any)({}, {});
- expect(idea.state.kind).toBe('artifact');
+ // Artifact recorders have no primitive — the runtime echoes the input.
+ const idea = await (runtime.recordSelfReviewIdea as any)({ idea: 'do x' }, {});
+ expect(idea.state).toEqual({ apiName: 'recordSelfReviewIdea', idea: 'do x', kind: 'artifact' });
});
- it('surfaces service errors without throwing, preserving the kind', async () => {
+ it('surfaces primitive errors without throwing, preserving the kind', async () => {
const runtime = new AgentSignalToolExecutionRuntime({
apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
- service: makeService(async () => {
- throw new Error('db unavailable');
- }),
+ service: {
+ writeMemory: async () => {
+ throw new Error('db unavailable');
+ },
+ },
});
const result = await (runtime.writeMemory as any)({}, {});
expect(result.success).toBe(false);
expect(result.error?.message).toBe('db unavailable');
- expect(result.state).toEqual({ kind: 'mutation' });
+ expect(result.state).toEqual({ apiName: 'writeMemory', kind: 'mutation' });
+ });
+
+ it('fails a mutation whose primitive is not implemented', async () => {
+ const runtime = new AgentSignalToolExecutionRuntime({
+ apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
+ service: {},
+ });
+
+ const result = await (runtime.createSelfReviewProposal as any)({}, {});
+ expect(result.success).toBe(false);
+ expect(result.error?.message).toMatch(/Unsupported/);
});
});
diff --git a/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.ts b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.ts
index 9ecc4e31002..8057508802c 100644
--- a/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.ts
+++ b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.ts
@@ -7,8 +7,8 @@ export type ToolResultKind = 'artifact' | 'mutation' | 'read';
/**
* Per-call context handed to a self-iteration tool. Mirrors the subset of the
- * server `ToolExecutionContext` the tools actually need; the concrete service
- * (wired in the server runtime factory) owns db / charge / receipt access.
+ * server `ToolExecutionContext` the primitives actually need; the concrete
+ * primitive (wired in the server runtime factory) owns db / model access.
*/
export interface AgentSignalToolContext {
agentId?: string;
@@ -18,31 +18,36 @@ export interface AgentSignalToolContext {
userId?: string;
}
-export interface AgentSignalToolInvocationResult {
- /** Structured tool payload. Object results are spread into the result state. */
- data?: unknown;
- error?: { message: string };
- /** Defaults to `!error`. */
- success?: boolean;
-}
+/**
+ * A single DB-backed primitive for one api name. Resolves the live read or
+ * applies the durable write, then returns a plain payload — the runtime stamps
+ * the `kind` discriminator and serializes the tool result. Throw to surface a
+ * failure; return a `{ status: 'skipped_*' }` payload to surface a safe no-op.
+ */
+export type AgentSignalRuntimePrimitive = (
+ input: Record<string, unknown>,
+ context: AgentSignalToolContext,
+) => Promise<unknown>;
/**
- * Service boundary the ExecutionRuntime delegates to. The server runtime factory
- * implements `invoke` by routing each api name to the existing self-iteration
- * `createToolSet(adapters)` surface; this keeps the package free of server deps.
+ * Narrow DB seam the ExecutionRuntime delegates to — one named primitive per
+ * read / mutation api name. The server runtime factory builds this from the
+ * tool execution context (db / userId / agentId), so the package stays free of
+ * server deps.
+ *
+ * Artifact recorders (`recordSelfReviewIdea` / `recordReflectionIdea` /
+ * `recordSelfFeedbackIntent`) are intentionally absent: they have no durable
+ * side effect, so the runtime echoes their input instead of calling a primitive.
+ * Each mode implements only the subset of primitives it advertises.
*/
-export interface AgentSignalToolService {
- invoke: (
- apiName: AgentSignalToolApiName,
- input: Record<string, unknown>,
- context: AgentSignalToolContext,
- ) => Promise<AgentSignalToolInvocationResult>;
-}
+export type AgentSignalRuntimeService = Partial<
+ Record<AgentSignalToolApiName, AgentSignalRuntimePrimitive>
+>;
export interface AgentSignalToolExecutionRuntimeOptions {
/** Api names this runtime exposes (the mode's tool surface). */
apiNames: readonly AgentSignalToolApiName[];
- service: AgentSignalToolService;
+ service: AgentSignalRuntimeService;
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -52,14 +57,19 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
* Shared server-side runtime for the three self-iteration tool packages.
*
* Builds one bound method per api name (the `BuiltinToolsExecutor` dispatches by
- * `runtime[apiName](args, context)`), delegates to the injected service, and
- * stamps every result with its `kind` so `extractFromFinalState` can reconstruct
- * read / artifact / mutation outcomes from a persisted snapshot.
+ * `runtime[apiName](args, context)`), routes reads / mutations to the injected
+ * primitive, echoes artifact recorders, and stamps every result with its `kind`
+ * so `extractFromFinalState` can reconstruct read / artifact / mutation outcomes
+ * from a persisted snapshot.
+ *
+ * Note: the runtime carries no dedupe / receipt / operation-state side channel —
+ * tools just read or mutate the DB. Idempotency and receipt projection live on
+ * the execAgent completion path, not inside the tool call.
*/
export class AgentSignalToolExecutionRuntime {
[apiName: string]: unknown;
- private readonly service: AgentSignalToolService;
+ private readonly service: AgentSignalRuntimeService;
constructor(options: AgentSignalToolExecutionRuntimeOptions) {
this.service = options.service;
@@ -78,16 +88,18 @@ export class AgentSignalToolExecutionRuntime {
const kind = AGENT_SIGNAL_TOOL_RESULT_KIND[apiName];
try {
- const result = await this.service.invoke(apiName, input, context);
- const data = isRecord(result.data) ? result.data : { value: result.data };
- const state = { kind, ...data };
- const success = result.success ?? !result.error;
+ const raw = kind === 'artifact' ? input : await this.invokePrimitive(apiName, input, context);
+ const data = isRecord(raw) ? raw : { value: raw };
+ // Stamp both `apiName` and `kind` into the persisted result content. The
+ // agent runtime only persists tool messages with content/role/tool_call_id
+ // (no message-level apiName), so the completion-path extractor must recover
+ // apiName from the content — same channel as `kind`.
+ const state = { apiName, kind, ...data };
return {
content: JSON.stringify(state),
state,
- success,
- ...(result.error ? { error: result.error } : {}),
+ success: true,
};
} catch (e) {
const message = e instanceof Error ? e.message : 'Unknown agent-signal tool error';
@@ -95,9 +107,20 @@ export class AgentSignalToolExecutionRuntime {
return {
content: `${apiName} failed: ${message}`,
error: { message },
- state: { kind },
+ state: { apiName, kind },
success: false,
};
}
};
+
+ private invokePrimitive = async (
+ apiName: AgentSignalToolApiName,
+ input: Record<string, unknown>,
+ context: AgentSignalToolContext,
+ ): Promise<unknown> => {
+ const primitive = this.service[apiName];
+ if (!primitive) throw new Error(`Unsupported agent-signal tool: ${apiName}`);
+
+ return primitive(input, context);
+ };
}
diff --git a/packages/builtin-tool-agent-signal/src/shared/apiNames.ts b/packages/builtin-tool-agent-signal/src/shared/apiNames.ts
index 78235d14c68..b28b0a1d1bd 100644
--- a/packages/builtin-tool-agent-signal/src/shared/apiNames.ts
+++ b/packages/builtin-tool-agent-signal/src/shared/apiNames.ts
@@ -1,13 +1,17 @@
import type { ToolResultKind } from './ExecutionRuntime';
/**
- * Resource tools shared by every self-iteration mode (read evidence + apply safe
- * memory/skill writes).
+ * Resource tools shared by every self-iteration mode: live-DB skill reads + safe
+ * memory/skill writes.
+ *
+ * Note: there is intentionally no `getEvidenceDigest` tool — the evidence corpus
+ * is collected once at dispatch and embedded in the agent's prompt
+ * (`<nightly_review_context_json>` etc.), so the agent already has it in context.
+ * A tool re-serving that same blob would be redundant.
*/
export const AGENT_SIGNAL_RESOURCE_API_NAMES = [
'listManagedSkills',
'getManagedSkill',
- 'getEvidenceDigest',
'writeMemory',
'createSkillIfAbsent',
'replaceSkillContentCAS',
@@ -53,7 +57,6 @@ export const AGENT_SIGNAL_TOOL_RESULT_KIND: Record<AgentSignalToolApiName, ToolR
closeSelfReviewProposal: 'mutation',
createSelfReviewProposal: 'mutation',
createSkillIfAbsent: 'mutation',
- getEvidenceDigest: 'read',
getManagedSkill: 'read',
listManagedSkills: 'read',
listSelfReviewProposals: 'read',
diff --git a/packages/builtin-tool-agent-signal/src/shared/schemas.ts b/packages/builtin-tool-agent-signal/src/shared/schemas.ts
index b290b88253f..95301e2ed3e 100644
--- a/packages/builtin-tool-agent-signal/src/shared/schemas.ts
+++ b/packages/builtin-tool-agent-signal/src/shared/schemas.ts
@@ -14,7 +14,6 @@ interface ToolApiSpec {
}
const str = { type: 'string' } as const;
-const strArr = { items: { type: 'string' }, type: 'array' } as const;
const freeObj = { additionalProperties: true, type: 'object' } as const;
const freeArr = { items: { additionalProperties: true, type: 'object' }, type: 'array' } as const;
@@ -93,16 +92,6 @@ export const RESOURCE_TOOL_APIS: ToolApiSpec[] = [
name: 'getManagedSkill',
parameters: obj({ skillDocumentId: str }, ['skillDocumentId']),
},
- {
- description:
- 'Read bounded evidence details for cited topic, message, tool_call, or agent_document ids in the review window. Use this for evidenceRefs; do not pass evidence ids to proposal tools.',
- name: 'getEvidenceDigest',
- parameters: obj({
- evidenceIds: strArr,
- reviewWindowEnd: str,
- reviewWindowStart: str,
- }),
- },
{
description:
'Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.',
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index 8ab608b82fb..ddc7f68ebe6 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -54,6 +54,32 @@ describe('AgentOperationModel', () => {
expect(row?.completedAt).toBeNull();
});
+ it('persists the agent-signal marker into metadata so server tools can read it back', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+ const operationId = 'op-start-marker';
+ // Server-side self-iteration tools resolve the review window / source id from
+ // metadata.agentSignal (the trimmed appContext intentionally drops it). If
+ // the marker is not persisted here, tools fall back to a 1970 window +
+ // operationId source.
+ const agentSignal = {
+ agentId: 'agent_reviewed',
+ kind: 'nightly-review',
+ localDate: '2026-05-30',
+ reviewWindowEnd: '2026-05-30T00:00:00.000Z',
+ reviewWindowStart: '2026-05-29T00:00:00.000Z',
+ sourceId: 'nightly-review:user:agent_reviewed:2026-05-30',
+ };
+
+ await model.recordStart({
+ appContext: { scope: 'chat' },
+ metadata: { agentSignal },
+ operationId,
+ });
+
+ const row = await model.findById(operationId);
+ expect(row?.metadata).toEqual({ agentSignal });
+ });
+
it('is idempotent on the primary key', async () => {
const model = new AgentOperationModel(serverDB, userId);
const operationId = 'op-start-2';
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index af09493075c..237dcb7d85f 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -16,6 +16,12 @@ export interface RecordOperationStartParams {
appContext?: AgentOperationAppContext;
chatGroupId?: string | null;
maxSteps?: number;
+ /**
+ * Durable per-run metadata persisted on the operation row (jsonb). Carries the
+ * Agent Signal run marker so server-side tools can read it back from the row
+ * (`metadata.agentSignal`) at tool-call time.
+ */
+ metadata?: Record<string, unknown>;
model?: string;
modelRuntimeConfig?: Record<string, unknown>;
operationId: string;
@@ -74,6 +80,7 @@ export class AgentOperationModel {
chatGroupId: params.chatGroupId ?? null,
id: params.operationId,
maxSteps: params.maxSteps,
+ ...(params.metadata ? { metadata: params.metadata } : {}),
model: params.model,
modelRuntimeConfig: params.modelRuntimeConfig,
parentOperationId: params.parentOperationId ?? null,
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 03c9d780fd4..f4d388968e4 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -1,6 +1,46 @@
import type { TaskDetail, UIChatMessage } from '../message';
import type { ChatTopic } from '../topic';
+export type AgentSignalOperationKind =
+ | 'memory'
+ | 'nightly-review'
+ | 'self-feedback-intent'
+ | 'self-reflection';
+
+/**
+ * Run-scoped Agent Signal marker stamped onto a background agent operation at
+ * dispatch. It travels on `appContext.agentSignal`, lands in
+ * `state.metadata.agentSignal`, and is read back on the completion path to
+ * project receipts / briefs (the `agent.execution.completed` payload itself only
+ * carries `agentId/operationId/topicId`). Runtime parsing/validation helpers live
+ * server-side in `operationMarker.ts`.
+ */
+export interface AgentSignalOperationMarker {
+ /**
+ * The reviewed user agent a resulting receipt should be attributed to. Needed
+ * when the run executes under a builtin self-iteration slug (whose resolved
+ * operation agentId is the builtin agent, not the user's agent); the
+ * completion projector prefers this over the run's agentId.
+ */
+ agentId?: string;
+ /** Assistant message a resulting receipt should anchor to. */
+ anchorMessageId?: string;
+ /** Discriminator the completion handler dispatches on. */
+ kind: AgentSignalOperationKind;
+ /** Local review date (YYYY-MM-DD) for nightly review brief/receipt writes. */
+ localDate?: string;
+ /** Review window end (ISO) — lets tools re-derive the evidence digest. */
+ reviewWindowEnd?: string;
+ /** Review window start (ISO). */
+ reviewWindowStart?: string;
+ /** Stable producer source id of the originating signal. */
+ sourceId?: string;
+ /** Topic the run is scoped to. */
+ topicId?: string;
+ /** User message that initiated the originating feedback. */
+ triggerMessageId?: string;
+}
+
/**
* Application context for message storage
*/
@@ -13,6 +53,11 @@ export interface ExecAgentAppContext {
* for downstream tool calls.
*/
agentDocumentId?: string | null;
+ /**
+ * Run-scoped Agent Signal marker for background self-iteration / memory runs.
+ * Forwarded into the operation so the completion path can project receipts.
+ */
+ agentSignal?: AgentSignalOperationMarker;
/** Optional default assignee candidate for task manager prompts */
defaultTaskAssigneeAgentId?: string;
/** Current document ID for page-scoped conversations */
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 4ef3f0ca254..21a39792a7e 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -299,6 +299,10 @@ export class AgentRuntimeService {
},
chatGroupId: appContext?.groupId ?? null,
maxSteps,
+ // Persist the Agent Signal run marker on the operation row so server-side
+ // self-iteration tools can read it back (metadata.agentSignal) at tool-call
+ // time — the trimmed appContext above intentionally drops it.
+ ...(appContext?.agentSignal ? { metadata: { agentSignal: appContext.agentSignal } } : {}),
model: modelRuntimeConfig?.model,
modelRuntimeConfig,
operationId,
diff --git a/src/server/services/agentRuntime/CompletionLifecycle.ts b/src/server/services/agentRuntime/CompletionLifecycle.ts
index 0e46cdb162c..89f3490bbd7 100644
--- a/src/server/services/agentRuntime/CompletionLifecycle.ts
+++ b/src/server/services/agentRuntime/CompletionLifecycle.ts
@@ -9,6 +9,7 @@ import { type LobeChatDatabase } from '@/database/type';
import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
+import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
import { hookDispatcher } from './hooks';
@@ -176,6 +177,18 @@ export class CompletionLifecycle {
async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {
try {
const { metadata } = this.buildLifecycleEvent(operationId, state, reason);
+ const selfIteration =
+ reason === 'error' ? undefined : extractSelfIterationCompletionPayload(state);
+ if (reason !== 'error') {
+ log(
+ '[completion-lifecycle] emit agent.execution.completed op=%s userId=%s selfIteration=%s',
+ operationId,
+ metadata?.userId || this.userId,
+ selfIteration
+ ? `kind=${selfIteration.marker?.kind} mutations=${selfIteration.mutations?.length}`
+ : 'ABSENT',
+ );
+ }
const completionSignalEmission =
reason === 'error'
? await emitAgentSignalSourceEvent(
@@ -204,6 +217,10 @@ export class CompletionLifecycle {
payload: {
agentId: metadata?.agentId,
operationId,
+ // Self-iteration runs carry their finalState tool outcomes here
+ // (the one point finalState is in hand) so the completion policy
+ // can project receipts. Undefined for every other agent.
+ selfIteration,
serializedContext: undefined,
steps: state?.stepCount || 0,
topicId: metadata?.topicId,
@@ -220,6 +237,13 @@ export class CompletionLifecycle {
{ ignoreError: true },
);
+ log(
+ '[completion-lifecycle] emission done op=%s reason=%s deduped=%s',
+ operationId,
+ reason,
+ (completionSignalEmission as { deduped?: boolean } | undefined)?.deduped ?? 'n/a',
+ );
+
return toAgentSignalSnapshotEvents(completionSignalEmission);
} catch (error) {
log('[%s] Completion signal emission error (non-fatal): %O', operationId, error);
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index c6f92599001..faeabcc240e 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -9,6 +9,7 @@ import type {
import type { ChatTopicBotContext, UserInterventionConfig } from '@lobechat/types';
import { type ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
+import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';
import type { DeviceAccessReason } from '@/server/services/aiAgent/deviceAccessPolicy';
import { type AgentHook } from './hooks/types';
@@ -151,6 +152,12 @@ export interface OperationCreationParams {
agentConfig?: any;
appContext: {
agentId?: string;
+ /**
+ * Run-scoped Agent Signal marker. Stamped at dispatch for background
+ * self-iteration / memory runs; lands in `state.metadata.agentSignal` and is
+ * read on the completion path to project receipts.
+ */
+ agentSignal?: AgentSignalOperationMarker;
defaultTaskAssigneeAgentId?: string;
documentId?: string | null;
groupId?: string | null;
diff --git a/src/server/services/agentSignal/__tests__/index.integration.test.ts b/src/server/services/agentSignal/__tests__/index.integration.test.ts
index e401a7d636b..09ae1d5e898 100644
--- a/src/server/services/agentSignal/__tests__/index.integration.test.ts
+++ b/src/server/services/agentSignal/__tests__/index.integration.test.ts
@@ -139,7 +139,7 @@ describe('emitAgentSignalSourceEvent integration', () => {
);
});
- it('orchestrates source emission through the runtime boundary', async () => {
+ it('orchestrates source emission through the runtime boundary', { timeout: 15_000 }, async () => {
const emitSourceEvent = vi.fn().mockResolvedValue({
deduped: false,
source: {
diff --git a/src/server/services/agentSignal/__tests__/orchestrator.test.ts b/src/server/services/agentSignal/__tests__/orchestrator.test.ts
deleted file mode 100644
index 7c3b5b266ce..00000000000
--- a/src/server/services/agentSignal/__tests__/orchestrator.test.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-// @vitest-environment node
-import { describe, expect, it, vi } from 'vitest';
-
-import { BriefModel } from '@/database/models/brief';
-
-import type { AgentSignalEmitOptions } from '../emitter';
-import { withServerAgentSignalPolicyDefaults } from '../orchestrator';
-import { createBriefSelfReviewService } from '../services/selfIteration/review/brief';
-import type { NightlyReviewContext } from '../services/selfIteration/review/collect';
-import { ActionStatus, ReviewRunStatus, Scope } from '../services/selfIteration/types';
-
-const createNightlyReviewContext = (): NightlyReviewContext => ({
- agentId: 'agent-1',
- documentActivity: {
- ambiguousBucket: [],
- excludedSummary: { count: 0, reasons: [] },
- generalDocumentBucket: [],
- skillBucket: [],
- },
- feedbackActivity: {
- neutralCount: 0,
- notSatisfied: [],
- satisfied: [],
- },
- selfReviewSignals: [],
- managedSkills: [],
- proposalActivity: {
- active: [],
- dismissedCount: 0,
- expiredCount: 0,
- staleCount: 0,
- supersededCount: 0,
- },
- receiptActivity: {
- appliedCount: 0,
- duplicateGroups: [],
- failedCount: 0,
- pendingProposalCount: 0,
- recentReceipts: [],
- reviewCount: 0,
- },
- relevantMemories: [],
- reviewWindowEnd: '2026-05-04T14:30:00.000Z',
- reviewWindowStart: '2026-05-03T16:00:00.000Z',
- selfFeedbackCandidates: [],
- toolActivity: [],
- topics: [],
- userId: 'user-1',
-});
-
-const createNightlyReviewOptions = (): NonNullable<
- NonNullable<AgentSignalEmitOptions['policyOptions']>['nightlyReview']
-> => ({
- acquireReviewGuard: vi.fn(async () => true),
- canRunReview: vi.fn(async () => true),
- collectContext: vi.fn(async () => createNightlyReviewContext()),
- runSelfReviewAgent: vi.fn(async () => ({
- execution: {
- actions: [],
- status: ReviewRunStatus.Completed,
- },
- projectionPlan: {
- actions: [],
- plannerVersion: 'test',
- reviewScope: Scope.Nightly,
- summary: 'Quiet night.',
- },
- })),
-});
-
-describe('Agent Signal orchestrator policy defaults', () => {
- /**
- * @example
- * expect(result).toBeUndefined().
- */
- it('does not install nightly brief writing for analyze-intent-only policy options', () => {
- expect(
- withServerAgentSignalPolicyDefaults(
- {
- skillManagement: {
- selfIterationEnabled: true,
- },
- },
- { db: {} as never, userId: 'user-1' },
- )?.nightlyReview,
- ).toBeUndefined();
- });
-
- /**
- * @example
- * expect(options.nightlyReview?.writeDailyBrief).toBeTypeOf('function').
- */
- it('adds a server BriefModel writer when nightly review deps omit one', async () => {
- const create = vi.spyOn(BriefModel.prototype, 'create').mockResolvedValue({
- agentId: 'agent-1',
- createdAt: new Date('2026-05-04T14:30:00.000Z'),
- id: 'brief-1',
- metadata: {},
- priority: 'info',
- summary: '1 self-iteration update applied.',
- title: 'Agent self-review updated resources',
- trigger: 'agent-signal:nightly-review',
- type: 'insight',
- userId: 'user-1',
- } as Awaited<ReturnType<BriefModel['create']>>);
- const policyOptions = withServerAgentSignalPolicyDefaults(
- {
- nightlyReview: createNightlyReviewOptions(),
- },
- { db: {} as never, userId: 'user-1' },
- );
- const brief = createBriefSelfReviewService().projectNightlyReviewBrief({
- agentId: 'agent-1',
- localDate: '2026-05-04',
- result: {
- actions: [
- {
- idempotencyKey: 'source:write_memory:memory:concise',
- receiptId: 'receipt-1',
- status: ActionStatus.Applied,
- summary: 'Saved concise PR summary preference.',
- },
- ],
- status: ReviewRunStatus.Completed,
- },
- reviewWindowEnd: '2026-05-04T14:30:00.000Z',
- reviewWindowStart: '2026-05-03T16:00:00.000Z',
- timezone: 'Asia/Shanghai',
- userId: 'user-1',
- });
-
- if (!brief) throw new Error('Expected projected brief');
-
- await expect(policyOptions?.nightlyReview?.writeDailyBrief?.(brief)).resolves.toMatchObject({
- id: 'brief-1',
- });
- expect(create).toHaveBeenCalledWith(brief);
- });
-
- /**
- * @example
- * expect(existingWriter).toHaveBeenCalled().
- */
- it('preserves an explicitly injected nightly brief writer', async () => {
- const writeDailyBrief = vi.fn(async () => ({ id: 'custom-brief' }));
- const policyOptions = withServerAgentSignalPolicyDefaults(
- {
- nightlyReview: {
- ...createNightlyReviewOptions(),
- writeDailyBrief,
- },
- },
- { db: {} as never, userId: 'user-1' },
- );
-
- await expect(policyOptions?.nightlyReview?.writeDailyBrief?.({} as never)).resolves.toEqual({
- id: 'custom-brief',
- });
- expect(writeDailyBrief).toHaveBeenCalled();
- });
-});
diff --git a/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts b/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts
index dd6a0f7c4a9..593a89db581 100644
--- a/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts
+++ b/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts
@@ -9,18 +9,6 @@ const root = process.cwd();
const read = (filePath: string) => readFileSync(path.join(root, filePath), 'utf8');
describe('agent signal prompt boundaries', () => {
- /**
- * @example
- * Self-iteration execute delegates model-facing runtime prompt text to @lobechat/prompts.
- */
- it('keeps self-iteration runtime prompt words out of execute service', () => {
- const source = read('src/server/services/agentSignal/services/selfIteration/execute.ts');
-
- expect(source).not.toContain('const SELF_ITERATION_SYSTEM_ROLE');
- expect(source).not.toContain('const createNightlyReviewPromptXml');
- expect(source).toContain('createAgentSignalSelfIterationPrompt');
- });
-
/**
* @example
* Memory writer delegates model-facing prompt words to @lobechat/prompts.
diff --git a/src/server/services/agentSignal/operationMarker.ts b/src/server/services/agentSignal/operationMarker.ts
new file mode 100644
index 00000000000..5c2270eb542
--- /dev/null
+++ b/src/server/services/agentSignal/operationMarker.ts
@@ -0,0 +1,66 @@
+/**
+ * Run-scoped marker stamped onto an agent operation's `metadata.agentSignal` at
+ * dispatch, and read back at tool-call time / completion time.
+ *
+ * The `agent.execution.completed` source payload only carries
+ * `agentId / operationId / topicId`. Async self-iteration & memory tools need
+ * more: the originating source id, the review window / local date (for evidence
+ * re-derivation and brief/receipt writes), and the message anchors used to
+ * attach receipts back to the right assistant message. Rather than a side
+ * channel, this travels on the operation row itself.
+ */
+
+import type { AgentSignalOperationKind, AgentSignalOperationMarker } from '@lobechat/types';
+
+// The marker shape is defined in `@lobechat/types` (so `ExecAgentAppContext` can
+// carry it through `execAgent`); the runtime parser/validator helpers live here.
+export type { AgentSignalOperationKind, AgentSignalOperationMarker };
+
+const VALID_KINDS = new Set<AgentSignalOperationKind>([
+ 'memory',
+ 'nightly-review',
+ 'self-feedback-intent',
+ 'self-reflection',
+]);
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const str = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.length > 0 ? value : undefined;
+
+/**
+ * Reads the agent-signal marker from an operation `metadata` object. Returns
+ * `undefined` when the operation was not an agent-signal run.
+ */
+export const readAgentSignalMarker = (
+ metadata: unknown,
+): AgentSignalOperationMarker | undefined => {
+ if (!isRecord(metadata)) return undefined;
+ const marker = metadata.agentSignal;
+ if (!isRecord(marker)) return undefined;
+
+ const kind = marker.kind;
+ if (typeof kind !== 'string' || !VALID_KINDS.has(kind as AgentSignalOperationKind)) {
+ return undefined;
+ }
+
+ return {
+ kind: kind as AgentSignalOperationKind,
+ ...(str(marker.anchorMessageId) ? { anchorMessageId: str(marker.anchorMessageId) } : {}),
+ ...(str(marker.localDate) ? { localDate: str(marker.localDate) } : {}),
+ ...(str(marker.reviewWindowEnd) ? { reviewWindowEnd: str(marker.reviewWindowEnd) } : {}),
+ ...(str(marker.reviewWindowStart) ? { reviewWindowStart: str(marker.reviewWindowStart) } : {}),
+ ...(str(marker.sourceId) ? { sourceId: str(marker.sourceId) } : {}),
+ ...(str(marker.topicId) ? { topicId: str(marker.topicId) } : {}),
+ ...(str(marker.triggerMessageId) ? { triggerMessageId: str(marker.triggerMessageId) } : {}),
+ };
+};
+
+/** Build the `appContext.agentSignal` value to stamp at dispatch time. */
+export const buildAgentSignalMarker = (
+ marker: AgentSignalOperationMarker,
+): AgentSignalOperationMarker => marker;
+
+export const isAgentSignalKind = (value: unknown): value is AgentSignalOperationKind =>
+ typeof value === 'string' && VALID_KINDS.has(value as AgentSignalOperationKind);
diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.ts
index 56bc41bdf73..795da1d680a 100644
--- a/src/server/services/agentSignal/orchestrator.ts
+++ b/src/server/services/agentSignal/orchestrator.ts
@@ -23,7 +23,7 @@ import { createProcedurePolicyOptions } from './procedure';
import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';
import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
import { persistAgentSignalReceipts, projectAgentSignalReceipts } from './services/receiptService';
-import { createServerSelfReviewBriefWriter } from './services/selfIteration/review/brief';
+import { createSelfIterationCompletionHandler } from './services/selfIteration/completion';
import { emitSourceEvent } from './sources';
import { redisPolicyStateStore } from './store/adapters/redis/policyStateStore';
import type { AgentSignalReceiptStore, AgentSignalSourceEventStore } from './store/types';
@@ -91,46 +91,22 @@ const buildRuntimeOrchestrationResult = (
};
};
-/**
- * Adds server defaults to optional Agent Signal self-iteration policy options.
- *
- * Use when:
- * - A caller already installed nightly review options but omitted the brief writer
- * - Nightly review outcomes should persist eligible Daily Brief rows in the server runtime
- *
- * Expects:
- * - Missing `nightlyReview` still means the nightly handler is intentionally not installed
- *
- * Returns:
- * - Policy options with a server `writeDailyBrief` fallback only for nightly review
- */
-export const withServerAgentSignalPolicyDefaults = (
- policyOptions: AgentSignalEmitOptions['policyOptions'] | undefined,
- context: AgentSignalExecutionContext,
-): AgentSignalEmitOptions['policyOptions'] => {
- if (!policyOptions?.nightlyReview || policyOptions.nightlyReview.writeDailyBrief) {
- return policyOptions;
- }
-
- const briefWriter = createServerSelfReviewBriefWriter(context.db, context.userId);
-
- return {
- ...policyOptions,
- nightlyReview: {
- ...policyOptions.nightlyReview,
- writeDailyBrief: briefWriter.writeDailyBrief,
- },
- };
-};
-
const createPolicyOptions = (
context: AgentSignalExecutionContext,
options: ExecuteAgentSignalSourceEventOptions,
procedurePolicyOptions: NonNullable<CreateDefaultAgentSignalPoliciesOptions['procedure']>,
): CreateDefaultAgentSignalPoliciesOptions => {
- const policyOptions = withServerAgentSignalPolicyDefaults(options.policyOptions, context);
+ // Nightly review writes its Daily Brief in-run via the builtin review
+ // serverRuntime primitive, so the orchestrator no longer injects a brief
+ // writer default.
+ const policyOptions = options.policyOptions;
return {
+ completion: {
+ onSelfIterationCompleted: createSelfIterationCompletionHandler(
+ options.receiptStore ? { receiptStore: options.receiptStore } : {},
+ ),
+ },
feedbackDomainJudge: {
db: context.db,
...policyOptions?.feedbackDomainJudge,
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.ts
new file mode 100644
index 00000000000..23f0d57409f
--- /dev/null
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult.ts
@@ -0,0 +1,300 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
+import { LayersEnum } from '@lobechat/types';
+import { isRecord, pickTrimmedString } from '@lobechat/utils';
+
+/**
+ * Pure, dependency-light helpers that derive the durable outcome of a
+ * memory-writer agent run from its terminal {@link AgentState}.
+ *
+ * Kept free of server-runtime imports (ModelRuntime, AgentService, …) on
+ * purpose: both the synchronous memory action runner AND the async completion
+ * path import this, and the completion path runs in the lightweight agent-runtime
+ * completion lifecycle — it must not drag the heavy memory-runner module (and its
+ * env-dependent transitive imports) into its graph.
+ */
+
+export interface MemoryActionTarget {
+ id?: string;
+ memoryId?: string;
+ memoryLayer?: LayersEnum;
+ summary?: string;
+ title: string;
+ type: 'memory';
+}
+
+export interface MemoryAgentActionResult {
+ detail?: string;
+ status: 'applied' | 'failed' | 'skipped';
+ target?: MemoryActionTarget;
+}
+
+const MEMORY_WRITE_API_NAMES = [
+ MemoryApiName.addActivityMemory,
+ MemoryApiName.addContextMemory,
+ MemoryApiName.addExperienceMemory,
+ MemoryApiName.addIdentityMemory,
+ MemoryApiName.addPreferenceMemory,
+ MemoryApiName.removeIdentityMemory,
+ MemoryApiName.updateIdentityMemory,
+] as const;
+
+const MEMORY_WRITE_TOOL_NAMES = new Set(
+ MEMORY_WRITE_API_NAMES.map((apiName) => `${MemoryIdentifier}/${apiName}`),
+);
+
+const MEMORY_WRITE_API_NAME_SET = new Set<string>(MEMORY_WRITE_API_NAMES);
+const MEMORY_WRITE_TARGET_BY_API_NAME: Record<string, { idKey: string; layer: LayersEnum }> = {
+ [MemoryApiName.addActivityMemory]: { idKey: 'activityId', layer: LayersEnum.Activity },
+ [MemoryApiName.addContextMemory]: { idKey: 'contextId', layer: LayersEnum.Context },
+ [MemoryApiName.addExperienceMemory]: { idKey: 'experienceId', layer: LayersEnum.Experience },
+ [MemoryApiName.addIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
+ [MemoryApiName.addPreferenceMemory]: { idKey: 'preferenceId', layer: LayersEnum.Preference },
+ [MemoryApiName.removeIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
+ [MemoryApiName.updateIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
+};
+const TOOL_NAME_SEPARATOR = '____';
+
+const hasSuccessfulMemoryWrite = (state: AgentState) => {
+ const byTool = state.usage?.tools?.byTool ?? [];
+
+ return byTool.some(
+ (entry) => MEMORY_WRITE_TOOL_NAMES.has(entry.name) && entry.calls > entry.errors,
+ );
+};
+
+const hasFailedMemoryWrite = (state: AgentState) => {
+ const byTool = state.usage?.tools?.byTool ?? [];
+
+ return byTool.some(
+ (entry) =>
+ MEMORY_WRITE_TOOL_NAMES.has(entry.name) && entry.calls > 0 && entry.calls === entry.errors,
+ );
+};
+
+const getString = (value: unknown) => {
+ return pickTrimmedString(value);
+};
+
+const parseToolArguments = (value: unknown): Record<string, unknown> | undefined => {
+ if (isRecord(value)) return value;
+
+ if (typeof value !== 'string') return;
+
+ try {
+ const parsed: unknown = JSON.parse(value);
+
+ return isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return;
+ }
+};
+
+interface MemoryToolCallSnapshot {
+ apiName?: string;
+ arguments?: unknown;
+ id?: string;
+ identifier?: string;
+}
+
+const getToolCallsFromMessage = (message: unknown): MemoryToolCallSnapshot[] => {
+ if (!isRecord(message)) return [];
+
+ const toolCalls: MemoryToolCallSnapshot[] = [];
+ const persistedTools = Array.isArray(message.tools) ? message.tools : [];
+
+ for (const tool of persistedTools) {
+ if (!isRecord(tool)) continue;
+
+ toolCalls.push({
+ apiName: getString(tool.apiName),
+ arguments: tool.arguments,
+ id: getString(tool.id),
+ identifier: getString(tool.identifier),
+ });
+ }
+
+ const rawToolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
+
+ for (const toolCall of rawToolCalls) {
+ if (!isRecord(toolCall)) continue;
+
+ const fn = isRecord(toolCall.function) ? toolCall.function : undefined;
+ const name = getString(fn?.name);
+ if (!name) continue;
+
+ const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);
+
+ toolCalls.push({
+ apiName: apiName || name,
+ arguments: fn?.arguments,
+ id: getString(toolCall.id),
+ identifier: apiName ? identifier : undefined,
+ });
+ }
+
+ return toolCalls;
+};
+
+const isMemoryWriteToolCall = (
+ toolCall: MemoryToolCallSnapshot,
+): toolCall is MemoryToolCallSnapshot & { apiName: string } => {
+ if (!toolCall.apiName || !MEMORY_WRITE_API_NAME_SET.has(toolCall.apiName)) return false;
+
+ return !toolCall.identifier || toolCall.identifier === MemoryIdentifier;
+};
+
+const getToolMessageCallId = (message: unknown) => {
+ if (!isRecord(message)) return;
+
+ const plugin = isRecord(message.plugin) ? message.plugin : undefined;
+
+ return getString(message.tool_call_id) ?? getString(plugin?.id);
+};
+
+const getMemoryIdsFromToolMessage = (message: unknown) => {
+ if (!isRecord(message)) return;
+
+ const ids: Record<string, string> = {};
+ const addId = (key: string, value: unknown) => {
+ if (!key.endsWith('Id')) return;
+
+ const id = getString(value);
+ if (id) ids[key] = id;
+ };
+
+ const pluginState = isRecord(message.pluginState) ? message.pluginState : undefined;
+ if (pluginState) {
+ for (const [key, value] of Object.entries(pluginState)) {
+ addId(key, value);
+ }
+ }
+
+ const content = getString(message.content);
+ if (content) {
+ for (const match of content.matchAll(/([A-Za-z]\w*Id):\s*"([^"]+)"/g)) {
+ addId(match[1], match[2]);
+ }
+ }
+
+ return Object.keys(ids).length > 0 ? ids : undefined;
+};
+
+const getMemoryToolResultIds = (state: AgentState) => {
+ const resultIds = new Map<string, Record<string, string>>();
+
+ for (const message of state.messages ?? []) {
+ const callId = getToolMessageCallId(message);
+ const ids = getMemoryIdsFromToolMessage(message);
+
+ if (callId && ids) resultIds.set(callId, ids);
+ }
+
+ return resultIds;
+};
+
+const getNestedString = (payload: Record<string, unknown>, keys: string[]) => {
+ let current: unknown = payload;
+
+ for (const key of keys) {
+ if (!isRecord(current)) return;
+
+ current = current[key];
+ }
+
+ return getString(current);
+};
+
+const getToolArgumentString = (args: Record<string, unknown>, key: string) => {
+ return getString(args[key]) ?? getNestedString(args, ['set', key]);
+};
+
+const createTargetFromToolArguments = (
+ args: Record<string, unknown>,
+ toolCall: MemoryToolCallSnapshot & { apiName: string },
+ resultIds?: Record<string, string>,
+): MemoryActionTarget | undefined => {
+ const title = getToolArgumentString(args, 'title');
+ if (!title) return;
+
+ const targetConfig = MEMORY_WRITE_TARGET_BY_API_NAME[toolCall.apiName];
+ const id = targetConfig ? resultIds?.[targetConfig.idKey] : undefined;
+ const memoryId = resultIds?.memoryId;
+ const summary =
+ getToolArgumentString(args, 'summary') ??
+ getToolArgumentString(args, 'details') ??
+ getNestedString(args, ['withPreference', 'conclusionDirectives']);
+
+ return {
+ ...((id ?? memoryId) ? { id: id ?? memoryId } : {}),
+ ...(memoryId ? { memoryId } : {}),
+ ...(targetConfig ? { memoryLayer: targetConfig.layer } : {}),
+ ...(summary ? { summary } : {}),
+ title,
+ type: 'memory',
+ };
+};
+
+export const resolveMemoryActionTargetFromState = (
+ state: AgentState,
+): MemoryActionTarget | undefined => {
+ const resultIds = getMemoryToolResultIds(state);
+
+ for (const message of [...(state.messages ?? [])].reverse()) {
+ const toolCalls = getToolCallsFromMessage(message).reverse();
+
+ for (const toolCall of toolCalls) {
+ if (!isMemoryWriteToolCall(toolCall)) continue;
+ if (!toolCall.id) continue;
+
+ const confirmedResultIds = resultIds.get(toolCall.id);
+ if (!confirmedResultIds) continue;
+
+ const args = parseToolArguments(toolCall.arguments);
+ if (!args) continue;
+
+ const target = createTargetFromToolArguments(args, toolCall, confirmedResultIds);
+ if (target) return target;
+ }
+ }
+};
+
+/**
+ * Derives the memory-action outcome from a terminal memory-writer agent state.
+ *
+ * Single source of truth for "did the memory write apply / fail / skip", shared
+ * by the synchronous runner and the async completion path (which re-derives the
+ * outcome from the run's finalState to project a receipt — the memory builtin
+ * tool results are not `kind`-tagged, so the completion extractor synthesizes a
+ * `writeMemory` mutation from this result instead).
+ */
+export const resolveMemoryActionResultFromState = (state: AgentState): MemoryAgentActionResult => {
+ if (state.status === 'error') {
+ return {
+ detail: 'Memory action agent finished with an error.',
+ status: 'failed',
+ };
+ }
+
+ if (hasSuccessfulMemoryWrite(state)) {
+ const target = resolveMemoryActionTargetFromState(state);
+
+ return {
+ ...(target?.summary ? { detail: target.summary } : {}),
+ status: 'applied',
+ ...(target ? { target } : {}),
+ };
+ }
+
+ if (hasFailedMemoryWrite(state)) {
+ return {
+ detail: 'Memory tool call failed during memory action agent execution.',
+ status: 'failed',
+ };
+ }
+
+ return {
+ detail: 'Memory action agent did not issue a durable memory write.',
+ status: 'skipped',
+ };
+};
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
index e1e214cac79..0b117ee2f50 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
@@ -1,18 +1,18 @@
-import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
+import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
import type {
AgenticAttempt,
BaseAction,
ExecutorResult,
SignalAttempt,
} from '@lobechat/agent-signal';
-import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
+import { MemoryIdentifier } from '@lobechat/builtin-tool-memory';
import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';
import {
createAgentSignalMemoryWriterPrompt,
createAgentSignalMemoryWriterSystemRole,
} from '@lobechat/prompts';
-import { LayersEnum, RequestTrigger, ThreadType } from '@lobechat/types';
-import { isRecord, nanoid, pickTrimmedString } from '@lobechat/utils';
+import { RequestTrigger, ThreadType } from '@lobechat/types';
+import { nanoid } from '@lobechat/utils';
import { PluginModel } from '@/database/models/plugin';
import { ThreadModel } from '@/database/models/thread';
@@ -27,6 +27,7 @@ import {
type ServerAgentToolsContext,
} from '@/server/modules/Mecha';
import { AgentService } from '@/server/services/agent';
+import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';
import type { RuntimeProcessorContext } from '../../../runtime/context';
import { defineActionHandler } from '../../../runtime/middleware';
@@ -42,49 +43,19 @@ import type {
AgentSignalFeedbackSourceHints,
} from '../../types';
import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../types';
+import {
+ type MemoryActionTarget,
+ type MemoryAgentActionResult,
+ resolveMemoryActionResultFromState,
+ resolveMemoryActionTargetFromState,
+} from './memoryActionResult';
const MEMORY_AGENT_MAX_STEPS = 8;
-const MEMORY_WRITE_API_NAMES = [
- MemoryApiName.addActivityMemory,
- MemoryApiName.addContextMemory,
- MemoryApiName.addExperienceMemory,
- MemoryApiName.addIdentityMemory,
- MemoryApiName.addPreferenceMemory,
- MemoryApiName.removeIdentityMemory,
- MemoryApiName.updateIdentityMemory,
-] as const;
-
-const MEMORY_WRITE_TOOL_NAMES = new Set(
- MEMORY_WRITE_API_NAMES.map((apiName) => `${MemoryIdentifier}/${apiName}`),
-);
-
-const MEMORY_WRITE_API_NAME_SET = new Set<string>(MEMORY_WRITE_API_NAMES);
-const MEMORY_WRITE_TARGET_BY_API_NAME: Record<string, { idKey: string; layer: LayersEnum }> = {
- [MemoryApiName.addActivityMemory]: { idKey: 'activityId', layer: LayersEnum.Activity },
- [MemoryApiName.addContextMemory]: { idKey: 'contextId', layer: LayersEnum.Context },
- [MemoryApiName.addExperienceMemory]: { idKey: 'experienceId', layer: LayersEnum.Experience },
- [MemoryApiName.addIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
- [MemoryApiName.addPreferenceMemory]: { idKey: 'preferenceId', layer: LayersEnum.Preference },
- [MemoryApiName.removeIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
- [MemoryApiName.updateIdentityMemory]: { idKey: 'identityId', layer: LayersEnum.Identity },
-};
-const TOOL_NAME_SEPARATOR = '____';
-
-export interface MemoryActionTarget {
- id?: string;
- memoryId?: string;
- memoryLayer?: LayersEnum;
- summary?: string;
- title: string;
- type: 'memory';
-}
-
-export interface MemoryAgentActionResult {
- detail?: string;
- status: 'applied' | 'failed' | 'skipped';
- target?: MemoryActionTarget;
-}
+// Backward-compatible re-export: the memory finalState helpers + result types
+// now live in the dependency-light ./memoryActionResult module.
+export type { MemoryActionTarget, MemoryAgentActionResult };
+export { resolveMemoryActionResultFromState, resolveMemoryActionTargetFromState };
export interface UserMemoryActionHandlerOptions {
agentService?: Pick<AgentService, 'getAgentConfig'>;
@@ -161,209 +132,9 @@ const createFunctionCallSupportChecker = async () => {
};
};
-const hasSuccessfulMemoryWrite = (state: AgentState) => {
- const byTool = state.usage?.tools?.byTool ?? [];
-
- return byTool.some(
- (entry) => MEMORY_WRITE_TOOL_NAMES.has(entry.name) && entry.calls > entry.errors,
- );
-};
-
-const hasFailedMemoryWrite = (state: AgentState) => {
- const byTool = state.usage?.tools?.byTool ?? [];
-
- return byTool.some(
- (entry) =>
- MEMORY_WRITE_TOOL_NAMES.has(entry.name) && entry.calls > 0 && entry.calls === entry.errors,
- );
-};
-
-const getString = (value: unknown) => {
- return pickTrimmedString(value);
-};
-
-const parseToolArguments = (value: unknown): Record<string, unknown> | undefined => {
- if (isRecord(value)) return value;
-
- if (typeof value !== 'string') return;
-
- try {
- const parsed: unknown = JSON.parse(value);
-
- return isRecord(parsed) ? parsed : undefined;
- } catch {
- return;
- }
-};
-
-interface MemoryToolCallSnapshot {
- apiName?: string;
- arguments?: unknown;
- id?: string;
- identifier?: string;
-}
-
-const getToolCallsFromMessage = (message: unknown): MemoryToolCallSnapshot[] => {
- if (!isRecord(message)) return [];
-
- const toolCalls: MemoryToolCallSnapshot[] = [];
- const persistedTools = Array.isArray(message.tools) ? message.tools : [];
-
- for (const tool of persistedTools) {
- if (!isRecord(tool)) continue;
-
- toolCalls.push({
- apiName: getString(tool.apiName),
- arguments: tool.arguments,
- id: getString(tool.id),
- identifier: getString(tool.identifier),
- });
- }
-
- const rawToolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
-
- for (const toolCall of rawToolCalls) {
- if (!isRecord(toolCall)) continue;
-
- const fn = isRecord(toolCall.function) ? toolCall.function : undefined;
- const name = getString(fn?.name);
- if (!name) continue;
-
- const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);
-
- toolCalls.push({
- apiName: apiName || name,
- arguments: fn?.arguments,
- id: getString(toolCall.id),
- identifier: apiName ? identifier : undefined,
- });
- }
-
- return toolCalls;
-};
-
-const isMemoryWriteToolCall = (
- toolCall: MemoryToolCallSnapshot,
-): toolCall is MemoryToolCallSnapshot & { apiName: string } => {
- if (!toolCall.apiName || !MEMORY_WRITE_API_NAME_SET.has(toolCall.apiName)) return false;
-
- return !toolCall.identifier || toolCall.identifier === MemoryIdentifier;
-};
-
-const getToolMessageCallId = (message: unknown) => {
- if (!isRecord(message)) return;
-
- const plugin = isRecord(message.plugin) ? message.plugin : undefined;
-
- return getString(message.tool_call_id) ?? getString(plugin?.id);
-};
-
-const getMemoryIdsFromToolMessage = (message: unknown) => {
- if (!isRecord(message)) return;
-
- const ids: Record<string, string> = {};
- const addId = (key: string, value: unknown) => {
- if (!key.endsWith('Id')) return;
-
- const id = getString(value);
- if (id) ids[key] = id;
- };
-
- const pluginState = isRecord(message.pluginState) ? message.pluginState : undefined;
- if (pluginState) {
- for (const [key, value] of Object.entries(pluginState)) {
- addId(key, value);
- }
- }
-
- const content = getString(message.content);
- if (content) {
- for (const match of content.matchAll(/([A-Za-z]\w*Id):\s*"([^"]+)"/g)) {
- addId(match[1], match[2]);
- }
- }
-
- return Object.keys(ids).length > 0 ? ids : undefined;
-};
-
-const getMemoryToolResultIds = (state: AgentState) => {
- const resultIds = new Map<string, Record<string, string>>();
-
- for (const message of state.messages ?? []) {
- const callId = getToolMessageCallId(message);
- const ids = getMemoryIdsFromToolMessage(message);
-
- if (callId && ids) resultIds.set(callId, ids);
- }
-
- return resultIds;
-};
-
-const getNestedString = (payload: Record<string, unknown>, keys: string[]) => {
- let current: unknown = payload;
-
- for (const key of keys) {
- if (!isRecord(current)) return;
-
- current = current[key];
- }
-
- return getString(current);
-};
-
-const getToolArgumentString = (args: Record<string, unknown>, key: string) => {
- return getString(args[key]) ?? getNestedString(args, ['set', key]);
-};
-
-const createTargetFromToolArguments = (
- args: Record<string, unknown>,
- toolCall: MemoryToolCallSnapshot & { apiName: string },
- resultIds?: Record<string, string>,
-): MemoryActionTarget | undefined => {
- const title = getToolArgumentString(args, 'title');
- if (!title) return;
-
- const targetConfig = MEMORY_WRITE_TARGET_BY_API_NAME[toolCall.apiName];
- const id = targetConfig ? resultIds?.[targetConfig.idKey] : undefined;
- const memoryId = resultIds?.memoryId;
- const summary =
- getToolArgumentString(args, 'summary') ??
- getToolArgumentString(args, 'details') ??
- getNestedString(args, ['withPreference', 'conclusionDirectives']);
-
- return {
- ...((id ?? memoryId) ? { id: id ?? memoryId } : {}),
- ...(memoryId ? { memoryId } : {}),
- ...(targetConfig ? { memoryLayer: targetConfig.layer } : {}),
- ...(summary ? { summary } : {}),
- title,
- type: 'memory',
- };
-};
-
-export const resolveMemoryActionTargetFromState = (
- state: AgentState,
-): MemoryActionTarget | undefined => {
- const resultIds = getMemoryToolResultIds(state);
-
- for (const message of [...(state.messages ?? [])].reverse()) {
- const toolCalls = getToolCallsFromMessage(message).reverse();
-
- for (const toolCall of toolCalls) {
- if (!isMemoryWriteToolCall(toolCall)) continue;
- if (!toolCall.id) continue;
-
- const confirmedResultIds = resultIds.get(toolCall.id);
- if (!confirmedResultIds) continue;
-
- const args = parseToolArguments(toolCall.arguments);
- if (!args) continue;
-
- const target = createTargetFromToolArguments(args, toolCall, confirmedResultIds);
- if (target) return target;
- }
- }
-};
+// Memory finalState parsing (tool-call/result walking, target resolution) lives
+// in ./memoryActionResult — kept dependency-light so the completion path can
+// reuse it without dragging this heavy module into its graph.
export const runMemoryActionAgent = async (
input: {
@@ -386,6 +157,15 @@ export const runMemoryActionAgent = async (
topicId?: string;
},
options: UserMemoryActionHandlerOptions,
+ /**
+ * When provided, the memory writer runs as an async (queued) execAgent run
+ * instead of a blocking `executeSync`: the operation is enqueued with the
+ * agent-signal marker stamped onto `appContext`, and the durable receipt is
+ * projected later on the completion path. Returns immediately with an
+ * `applied` (enqueued) status. Absent → the legacy synchronous path (still
+ * used by the self-iteration tool primitives until they migrate in S4).
+ */
+ dispatch?: { marker: AgentSignalOperationMarker },
): Promise<MemoryAgentActionResult> => {
if (!input.agentId) {
return {
@@ -451,17 +231,8 @@ export const runMemoryActionAgent = async (
const manifestMap = toolsEngine.getEnabledPluginManifests([MemoryIdentifier]);
const operationId = `agent-signal-memory-${nanoid()}`;
const initialContext = createInitialContext(operationId);
- const streamEventManager = new InMemoryStreamEventManager();
const { AgentRuntimeService } =
await import('@/server/services/agentRuntime/AgentRuntimeService');
- const runtimeService = new AgentRuntimeService(options.db, options.userId, {
- coordinatorOptions: {
- stateManager: new InMemoryAgentStateManager(),
- streamEventManager,
- },
- queueService: null,
- streamEventManager,
- });
// Create a child thread under the triggering assistant message so that
// memory-agent messages are isolated from the main topic conversation
@@ -484,17 +255,8 @@ export const runMemoryActionAgent = async (
}
}
- await runtimeService.createOperation({
+ const createParams = {
agentConfig: memoryRuntimeAgentConfig,
- appContext: {
- agentId: input.agentId,
- scope: 'chat',
- sourceMessageId: input.sourceMessageId,
- threadId: threadId ?? null,
- topicId: input.topicId ?? null,
- trigger: RequestTrigger.AgentSignal,
- },
- autoStart: false,
initialContext,
initialMessages: [
{
@@ -515,6 +277,46 @@ export const runMemoryActionAgent = async (
tools: toolsResult.tools,
},
userId: options.userId,
+ };
+ const baseAppContext = {
+ agentId: input.agentId,
+ scope: 'chat',
+ sourceMessageId: input.sourceMessageId,
+ threadId: threadId ?? null,
+ topicId: input.topicId ?? null,
+ trigger: RequestTrigger.AgentSignal,
+ };
+
+ // Async (queued execAgent) path: enqueue the run with the marker stamped onto
+ // appContext (it lands in state.metadata.agentSignal), then return immediately.
+ // The durable receipt is projected on the completion path from the run's
+ // finalState — no blocking executeSync.
+ if (dispatch) {
+ const runtimeService = new AgentRuntimeService(options.db, options.userId);
+ await runtimeService.createOperation({
+ ...createParams,
+ appContext: { ...baseAppContext, agentSignal: dispatch.marker },
+ autoStart: true,
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+
+ return { detail: 'Memory write enqueued.', status: 'applied' };
+ }
+
+ // Legacy synchronous path (self-iteration tool primitives, until S4).
+ const streamEventManager = new InMemoryStreamEventManager();
+ const runtimeService = new AgentRuntimeService(options.db, options.userId, {
+ coordinatorOptions: {
+ stateManager: new InMemoryAgentStateManager(),
+ streamEventManager,
+ },
+ queueService: null,
+ streamEventManager,
+ });
+ await runtimeService.createOperation({
+ ...createParams,
+ appContext: baseAppContext,
+ autoStart: false,
userInterventionConfig: { approvalMode: 'headless' },
});
@@ -523,34 +325,7 @@ export const runMemoryActionAgent = async (
maxSteps: MEMORY_AGENT_MAX_STEPS,
});
- if (finalState.status === 'error') {
- return {
- detail: 'Memory action agent finished with an error.',
- status: 'failed',
- };
- }
-
- if (hasSuccessfulMemoryWrite(finalState)) {
- const target = resolveMemoryActionTargetFromState(finalState);
-
- return {
- ...(target?.summary ? { detail: target.summary } : {}),
- status: 'applied',
- ...(target ? { target } : {}),
- };
- }
-
- if (hasFailedMemoryWrite(finalState)) {
- return {
- detail: 'Memory tool call failed during memory action agent execution.',
- status: 'failed',
- };
- }
-
- return {
- detail: 'Memory action agent did not issue a durable memory write.',
- status: 'skipped',
- };
+ return resolveMemoryActionResultFromState(finalState);
};
export const handleUserMemoryAction = async (
@@ -627,7 +402,16 @@ export const handleUserMemoryAction = async (
: undefined,
topicId: typeof action.payload.topicId === 'string' ? action.payload.topicId : undefined,
};
- const runner = options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options));
+ // Stamp the run so the completion path can project the memory receipt (the
+ // memory write is now enqueued async, not resolved synchronously here).
+ const marker: AgentSignalOperationMarker = {
+ kind: 'memory',
+ ...(runnerInput.sourceMessageId ? { anchorMessageId: runnerInput.sourceMessageId } : {}),
+ sourceId: idempotencyKey ?? action.actionId,
+ ...(runnerInput.topicId ? { topicId: runnerInput.topicId } : {}),
+ };
+ const runner =
+ options.memoryActionRunner ?? ((input) => runMemoryActionAgent(input, options, { marker }));
let memoryActionResult: MemoryAgentActionResult | undefined;
const memoryService = createMemoryService({
writeMemory: async () => {
diff --git a/src/server/services/agentSignal/policies/completionPolicy.test.ts b/src/server/services/agentSignal/policies/completionPolicy.test.ts
index e165a7d2706..15b1e63b605 100644
--- a/src/server/services/agentSignal/policies/completionPolicy.test.ts
+++ b/src/server/services/agentSignal/policies/completionPolicy.test.ts
@@ -3,6 +3,7 @@ import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { describe, expect, it, vi } from 'vitest';
+import type { SelfIterationCompletionPayload } from '../services/selfIteration/completion';
import { createCompletionPolicy } from './completionPolicy';
interface CapturedHandler {
@@ -25,6 +26,13 @@ const installAndCapture = (middleware: ReturnType<typeof createCompletionPolicy>
return sourceHandlers;
};
+const selfIteration: SelfIterationCompletionPayload = {
+ artifacts: [],
+ marker: { kind: 'nightly-review', sourceId: 'src_1' },
+ mutations: [],
+ userId: 'user_1',
+};
+
describe('createCompletionPolicy', () => {
it('registers a single source handler on agent.execution.completed', () => {
const handlers = installAndCapture(createCompletionPolicy());
@@ -39,20 +47,17 @@ describe('createCompletionPolicy', () => {
await expect(
handler.handle({
- payload: {
- agentId: BUILTIN_AGENT_SLUGS.nightlyReview,
- operationId: 'op_1',
- },
+ payload: { agentId: BUILTIN_AGENT_SLUGS.nightlyReview, operationId: 'op_1', selfIteration },
}),
).resolves.toBeUndefined();
});
- it('ignores non-self-iteration agents even when a callback is provided', async () => {
+ it('ignores runs that carry no marker payload, regardless of agent', async () => {
const onSelfIterationCompleted = vi.fn();
const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
await handler.handle({
- payload: { agentId: BUILTIN_AGENT_SLUGS.inbox, operationId: 'op_2' },
+ payload: { agentId: BUILTIN_AGENT_SLUGS.nightlyReview, operationId: 'op_2' },
});
expect(onSelfIterationCompleted).not.toHaveBeenCalled();
@@ -61,38 +66,33 @@ describe('createCompletionPolicy', () => {
it.each([
[BUILTIN_AGENT_SLUGS.nightlyReview],
[BUILTIN_AGENT_SLUGS.selfReflection],
- [BUILTIN_AGENT_SLUGS.selfFeedbackIntent],
- ])('invokes the callback for %s runs and forwards the agentId', async (slug) => {
+ // A memory-writer runs as the user's own agent — not a self-iteration slug —
+ // and must still route purely on the marker payload.
+ ['agent_user_42'],
+ ])('invokes the callback for a marked %s run and forwards the payload', async (agentId) => {
const onSelfIterationCompleted = vi.fn().mockResolvedValue(undefined);
const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
await handler.handle({
- payload: {
- agentId: slug,
- operationId: 'op_3',
- topicId: 'topic_3',
- },
+ payload: { agentId, operationId: 'op_3', selfIteration, topicId: 'topic_3' },
});
expect(onSelfIterationCompleted).toHaveBeenCalledWith({
- agentId: slug,
+ agentId,
operationId: 'op_3',
+ selfIteration,
topicId: 'topic_3',
});
});
it('swallows callback errors so the worker is not blocked', async () => {
- const error = new Error('boom');
- const onSelfIterationCompleted = vi.fn().mockRejectedValue(error);
+ const onSelfIterationCompleted = vi.fn().mockRejectedValue(new Error('boom'));
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
await expect(
handler.handle({
- payload: {
- agentId: BUILTIN_AGENT_SLUGS.nightlyReview,
- operationId: 'op_4',
- },
+ payload: { agentId: BUILTIN_AGENT_SLUGS.nightlyReview, operationId: 'op_4', selfIteration },
}),
).resolves.toBeUndefined();
@@ -104,8 +104,10 @@ describe('createCompletionPolicy', () => {
const onSelfIterationCompleted = vi.fn();
const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
- await handler.handle({ payload: { operationId: 'op_5' } });
- await handler.handle({ payload: { agentId: BUILTIN_AGENT_SLUGS.nightlyReview } });
+ await handler.handle({ payload: { operationId: 'op_5', selfIteration } });
+ await handler.handle({
+ payload: { agentId: BUILTIN_AGENT_SLUGS.nightlyReview, selfIteration },
+ });
expect(onSelfIterationCompleted).not.toHaveBeenCalled();
});
diff --git a/src/server/services/agentSignal/policies/completionPolicy.ts b/src/server/services/agentSignal/policies/completionPolicy.ts
index 92560ee6b8a..caf45e655c2 100644
--- a/src/server/services/agentSignal/policies/completionPolicy.ts
+++ b/src/server/services/agentSignal/policies/completionPolicy.ts
@@ -1,31 +1,36 @@
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import type { BuiltinAgentSlug } from '@lobechat/builtin-agents';
-import { SELF_ITERATION_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import debug from 'debug';
import { defineAgentSignalHandlers, defineSourceHandler } from '../runtime/middleware';
+import type { SelfIterationCompletionPayload } from '../services/selfIteration/completion';
+
+const log = debug('lobe-server:completion-lifecycle');
/**
- * Handles `agent.execution.completed` source events emitted after every execAgent run
- * (including builtin background agents). Routes builtin self-iteration runs
- * (nightly-review / self-reflection / self-feedback-intent) to an optional
- * caller callback so side-effects (brief writing, receipt projection,
- * idempotency marker) can happen asynchronously after the agent run finishes.
+ * Handles `agent.execution.completed` source events emitted after every execAgent
+ * run. Routes runs that stamped an agent-signal marker (nightly-review /
+ * self-reflection / self-feedback-intent / memory) to an optional caller
+ * callback so side-effects (receipt projection) can happen asynchronously after
+ * the agent run finishes.
*
- * Mode is carried by `agentId` itself — each self-iteration mode is a distinct
- * builtin agent slug, so callers can dispatch on `agentId` without needing to
- * read the operation row.
+ * Routing is keyed on the marker-derived `selfIteration` payload, NOT the agent
+ * slug: a memory-writer run executes as the user's own agent, so a slug check
+ * would miss it. The marker is the authoritative "this run wants completion-side
+ * projection" signal, stamped by the dispatcher.
*
* The callback is fire-and-forget from the worker's perspective; failures are
* logged but never re-trigger the source pipeline.
- *
- * NOTE on userId: the `agent.execution.completed` source payload does not carry
- * userId, and `AgentSignalSource.scope` is not populated by renderers. Callers
- * that need userId should look it up via the operations table by `operationId`.
*/
export interface CompletionCallbackParams {
- /** Self-iteration agent slug — caller dispatches mode-specific behaviour from this. */
- agentId: BuiltinAgentSlug;
+ /** Agent that ran — a builtin self-iteration slug, or a user agent for memory. */
+ agentId: string;
operationId: string;
+ /**
+ * Compact self-iteration tool outcomes + run marker, extracted from the run's
+ * finalState by the executor and carried on the completion payload. Absent for
+ * runs that did not stamp an agent-signal marker.
+ */
+ selfIteration?: SelfIterationCompletionPayload;
/** Optional topic id forwarded from the source payload. */
topicId?: string;
}
@@ -44,15 +49,30 @@ export const createCompletionPolicy = (options: CreateCompletionPolicyOptions =
AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted,
'agent.execution.completed:completion-fanout',
async (source) => {
- const { agentId, operationId, topicId } = source.payload;
+ const { agentId, operationId, selfIteration, topicId } = source.payload;
+
+ log(
+ '[completion-policy] received agent.execution.completed agentId=%s op=%s selfIteration=%s',
+ agentId,
+ operationId,
+ selfIteration
+ ? `kind=${(selfIteration as SelfIterationCompletionPayload).marker?.kind} mutations=${(selfIteration as SelfIterationCompletionPayload).mutations?.length}`
+ : 'ABSENT',
+ );
if (!agentId || !operationId) return;
- if (!SELF_ITERATION_AGENT_SLUGS.has(agentId as BuiltinAgentSlug)) return;
- if (!options.onSelfIterationCompleted) return;
+ // Marker-driven: only runs that stamped a marker carry a selfIteration
+ // payload. Unmarked runs have nothing to project.
+ if (!selfIteration) return;
+ if (!options.onSelfIterationCompleted) {
+ log('[completion-policy] no onSelfIterationCompleted wired — skipping projection');
+ return;
+ }
const params: CompletionCallbackParams = {
- agentId: agentId as BuiltinAgentSlug,
+ agentId,
operationId,
+ selfIteration: selfIteration as SelfIterationCompletionPayload,
...(topicId ? { topicId } : {}),
};
diff --git a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
index babff292efe..c200542f9ac 100644
--- a/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
+++ b/src/server/services/agentSignal/services/__tests__/receiptService.test.ts
@@ -1,7 +1,6 @@
// @vitest-environment node
import type { BaseAction, ExecutorResult } from '@lobechat/agent-signal';
import { createSource } from '@lobechat/agent-signal';
-import { LayersEnum } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../policies/types';
@@ -53,6 +52,9 @@ const result = (input: {
});
describe('projectAgentSignalReceipts', () => {
+ // Anchoring / trigger projection is kind-agnostic; it is exercised here via a
+ // skill action because memory receipts are no longer projected synchronously
+ // (they come from the async memory run's completion path).
it('prefers anchorMessageId over assistantMessageId for receipt anchoring', () => {
const anchoredSource = createSource({
payload: {
@@ -72,12 +74,12 @@ describe('projectAgentSignalReceipts', () => {
projectAgentSignalReceipts({
actions: [
action({
- actionId: 'action-memory-1',
- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ actionId: 'action-skill-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
payload: {},
}),
],
- results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ results: [result({ actionId: 'action-skill-1', status: 'applied' })],
source: anchoredSource,
userId: 'user-1',
}),
@@ -89,12 +91,12 @@ describe('projectAgentSignalReceipts', () => {
projectAgentSignalReceipts({
actions: [
action({
- actionId: 'action-memory-1',
- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ actionId: 'action-skill-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
payload: {},
}),
],
- results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ results: [result({ actionId: 'action-skill-1', status: 'applied' })],
source,
userId: 'user-1',
}),
@@ -132,12 +134,12 @@ describe('projectAgentSignalReceipts', () => {
projectAgentSignalReceipts({
actions: [
action({
- actionId: 'action-memory-1',
- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ actionId: 'action-skill-1',
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
payload: {},
}),
],
- results: [result({ actionId: 'action-memory-1', status: 'applied' })],
+ results: [result({ actionId: 'action-skill-1', status: 'applied' })],
source: projectSource,
userId: 'user-1',
});
@@ -146,7 +148,7 @@ describe('projectAgentSignalReceipts', () => {
expect(project(legacyTriggerSource)).toMatchObject([{ triggerMessageId: 'message-legacy-1' }]);
});
- it('projects applied memory action results without unstructured feedback as target', () => {
+ it('does not project a memory action synchronously (the completion path owns it)', () => {
expect(
projectAgentSignalReceipts({
actions: [
@@ -160,70 +162,7 @@ describe('projectAgentSignalReceipts', () => {
source,
userId: 'user-1',
}),
- ).toEqual([
- {
- agentId: 'agent-1',
- anchorMessageId: 'assistant-1',
- createdAt: 1_700_000,
- detail: 'Saved this for future replies',
- id: 'source-1:action-memory-1:memory',
- kind: 'memory',
- operationId: 'op-1',
- sourceId: 'source-1',
- sourceType: 'client.gateway.runtime_end',
- status: 'applied',
- title: 'Memory saved',
- topicId: 'topic-1',
- userId: 'user-1',
- },
- ]);
- });
-
- it('prefers the memory target title from action output over the feedback message', () => {
- expect(
- projectAgentSignalReceipts({
- actions: [
- action({
- actionId: 'action-memory-1',
- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
- payload: {
- message:
- '<speaker id="833816919" username="nivra2000" nickname="Aa T" />\nEvery section is too short. Can it be longer?',
- },
- }),
- ],
- results: [
- result({
- actionId: 'action-memory-1',
- output: {
- target: {
- id: 'preference_1',
- memoryId: 'mem_1',
- memoryLayer: LayersEnum.Preference,
- summary: 'The user prefers longer, more developed answer sections.',
- title: 'Preference for detailed answer sections',
- type: 'memory',
- },
- },
- status: 'applied',
- }),
- ],
- source,
- userId: 'user-1',
- }),
- ).toMatchObject([
- {
- kind: 'memory',
- target: {
- id: 'preference_1',
- memoryId: 'mem_1',
- memoryLayer: LayersEnum.Preference,
- summary: 'The user prefers longer, more developed answer sections.',
- title: 'Preference for detailed answer sections',
- type: 'memory',
- },
- },
- ]);
+ ).toEqual([]);
});
it('projects applied skill-management results as updated skill receipts', () => {
diff --git a/src/server/services/agentSignal/services/receiptService.ts b/src/server/services/agentSignal/services/receiptService.ts
index 54f0f6eadb1..13a8fa1154f 100644
--- a/src/server/services/agentSignal/services/receiptService.ts
+++ b/src/server/services/agentSignal/services/receiptService.ts
@@ -294,15 +294,11 @@ const getReceiptTarget = (
const toReceiptKind = (
action: BaseAction,
): Pick<AgentSignalReceipt, 'detail' | 'kind' | 'status' | 'title'> | undefined => {
- if (action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle) {
- return {
- detail: 'Saved this for future replies',
- kind: 'memory',
- status: 'applied',
- title: 'Memory saved',
- };
- }
-
+ // Memory receipts are no longer projected synchronously here: the memory
+ // writer runs as an async execAgent run, so its receipt is projected on the
+ // completion path from the run's finalState (see selfIteration/completion).
+ // Projecting one here too would duplicate it — and with a premature, empty
+ // target, since at this point the write has only been enqueued.
if (action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle) {
return {
detail: 'Improved how this assistant handles similar requests',
diff --git a/src/server/services/agentSignal/services/selfIteration/__test__/execute.test.ts b/src/server/services/agentSignal/services/selfIteration/__test__/execute.test.ts
deleted file mode 100644
index 62437014b52..00000000000
--- a/src/server/services/agentSignal/services/selfIteration/__test__/execute.test.ts
+++ /dev/null
@@ -1,717 +0,0 @@
-// @vitest-environment node
-import type { ChatMethodOptions, ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
-import type * as ModelRuntimeModule from '@lobechat/model-runtime';
-import { consumeStreamUntilDone } from '@lobechat/model-runtime';
-import type { MessageToolCall, ModelUsage } from '@lobechat/types';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { AgentRunResult } from '../execute';
-import { createAgentRunner, executeSelfIteration } from '../execute';
-import type { NightlyReviewContext } from '../review/collect';
-import type { ToolSet, ToolWriteResult } from '../tools/shared';
-import { createToolSet } from '../tools/shared';
-import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../types';
-
-vi.mock('@lobechat/model-runtime', async (importOriginal) => {
- const actual = await importOriginal<typeof ModelRuntimeModule>();
-
- return {
- ...actual,
- consumeStreamUntilDone: vi.fn(async () => undefined),
- };
-});
-
-const reviewContext = {
- agentId: 'agent-1',
- documentActivity: {
- ambiguousBucket: [],
- excludedSummary: { count: 0, reasons: [] },
- generalDocumentBucket: [],
- skillBucket: [],
- },
- feedbackActivity: {
- neutralCount: 0,
- notSatisfied: [],
- satisfied: [],
- },
- selfReviewSignals: [],
- managedSkills: [],
- proposalActivity: {
- active: [],
- dismissedCount: 0,
- expiredCount: 0,
- staleCount: 0,
- supersededCount: 0,
- },
- receiptActivity: {
- appliedCount: 0,
- duplicateGroups: [],
- failedCount: 0,
- pendingProposalCount: 0,
- recentReceipts: [],
- reviewCount: 0,
- },
- relevantMemories: [],
- reviewWindowEnd: '2026-05-04T14:00:00.000Z',
- reviewWindowStart: '2026-05-03T14:00:00.000Z',
- selfFeedbackCandidates: [],
- toolActivity: [],
- topics: [],
- userId: 'user-1',
-} satisfies NightlyReviewContext;
-
-interface MockChatStep {
- content: string;
- toolCalls?: MessageToolCall[];
- usage?: ModelUsage;
-}
-
-const createMockModelRuntime = (steps: MockChatStep[]) => {
- const chat = vi.fn(async (_payload: ChatStreamPayload, options?: ChatMethodOptions) => {
- const step = steps[Math.min(chat.mock.calls.length - 1, steps.length - 1)];
-
- options?.callback?.onText?.(step.content);
- options?.callback?.onToolsCalling?.({
- chunk: [],
- toolsCalling: step.toolCalls ?? [],
- });
- options?.callback?.onCompletion?.({ text: step.content, usage: step.usage });
-
- return new Response('');
- });
-
- return {
- chat,
- modelRuntime: { chat: chat as unknown as Pick<ModelRuntime, 'chat'>['chat'] },
- };
-};
-
-const createNoopTools = () =>
- createToolSet({
- reserveOperation: vi.fn(async () => ({ reserved: true as const })),
- writeReceipt: vi.fn(async () => ({ receiptId: 'receipt-1' })),
- });
-
-const createMockTools = (writeResult?: ToolWriteResult): ToolSet => ({
- closeSelfReviewProposal: vi.fn(async () => ({
- receiptId: 'receipt-close',
- status: 'applied' as const,
- })),
- createSelfReviewProposal: vi.fn(async () => ({
- receiptId: 'receipt-proposal',
- status: 'proposed' as const,
- })),
- createSkillIfAbsent: vi.fn(
- async () =>
- writeResult || {
- receiptId: 'receipt-skill',
- resourceId: 'skill-1',
- status: 'applied' as const,
- summary: 'Created skill.',
- },
- ),
- getEvidenceDigest: vi.fn(async () => ({ evidence: [] })),
- getManagedSkill: vi.fn(async () => ({ id: 'skill-1' })),
- listSelfReviewProposals: vi.fn(async () => []),
- listManagedSkills: vi.fn(async () => []),
- readSelfReviewProposal: vi.fn(async () => undefined),
- refreshSelfReviewProposal: vi.fn(async () => ({
- receiptId: 'receipt-refresh',
- status: 'proposed' as const,
- })),
- replaceSkillContentCAS: vi.fn(async () => ({
- receiptId: 'receipt-replace',
- status: 'applied' as const,
- })),
- supersedeSelfReviewProposal: vi.fn(async () => ({
- receiptId: 'receipt-supersede',
- status: 'applied' as const,
- })),
- writeMemory: vi.fn(
- async () =>
- writeResult || {
- receiptId: 'receipt-memory',
- resourceId: 'memory-1',
- status: 'applied' as const,
- summary: 'Wrote memory.',
- },
- ),
-});
-
-describe('executeSelfIteration', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- /**
- * @example
- * expect(tools.createSkillIfAbsent).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user-1' }));
- * expect(result.writeOutcomes).toEqual([{ toolName: 'createSkillIfAbsent', result: writeResult }]);
- */
- it('invokes a write tool, records its outcome, and asks the model for a follow-up step', async () => {
- const writeResult = {
- receiptId: 'receipt-skill',
- resourceId: 'skill-1',
- status: 'applied',
- summary: 'Created skill.',
- } satisfies ToolWriteResult;
- const tools = createMockTools(writeResult);
- const { chat, modelRuntime } = createMockModelRuntime([
- {
- content: 'I will create the skill.',
- toolCalls: [
- {
- function: {
- arguments: JSON.stringify({
- bodyMarkdown: '# Skill',
- idempotencyKey: 'source-1:create-skill',
- name: 'debug-skill',
- summary: 'Create a debug skill.',
- }),
- name: 'createSkillIfAbsent',
- },
- id: 'tool-call-1',
- type: 'function',
- },
- ],
- usage: { inputTextTokens: 10, outputTextTokens: 5, totalTokens: 15 },
- },
- {
- content: 'Created the skill.',
- usage: { inputTextTokens: 5, outputTextTokens: 3, totalTokens: 8 },
- },
- ]);
-
- const result = await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 5,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- expect(tools.createSkillIfAbsent).toHaveBeenCalledWith(
- expect.objectContaining({
- bodyMarkdown: '# Skill',
- idempotencyKey: 'source-1:create-skill',
- name: 'debug-skill',
- userId: 'user-1',
- }),
- );
- expect(chat).toHaveBeenCalledTimes(2);
- expect(consumeStreamUntilDone).toHaveBeenCalledTimes(2);
- expect(result.stepCount).toBeGreaterThan(1);
- expect(result.content).toContain('Created the skill.');
- expect(result.writeOutcomes).toEqual([
- { result: writeResult, toolName: 'createSkillIfAbsent' },
- ]);
- });
-
- /**
- * @example
- * expect(tools.writeMemory).toHaveBeenCalledWith(expect.objectContaining({ content: 'User prefers concise summaries.' }));
- * expect(result.writeOutcomes[0]).toMatchObject({ toolName: 'writeMemory' });
- */
- it('exposes writeMemory as the auto-apply path for durable user preferences', async () => {
- const writeResult = {
- receiptId: 'receipt-memory',
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Wrote memory.',
- } satisfies ToolWriteResult;
- const tools = createMockTools(writeResult);
- const { modelRuntime } = createMockModelRuntime([
- {
- content: 'I will remember the durable preference.',
- toolCalls: [
- {
- function: {
- arguments: JSON.stringify({
- content: 'User prefers concise implementation summaries.',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source-1:write-memory',
- }),
- name: 'writeMemory',
- },
- id: 'tool-call-memory',
- type: 'function',
- },
- ],
- },
- {
- content: 'Saved the preference.',
- },
- ]);
-
- const result = await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 5,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- expect(tools.writeMemory).toHaveBeenCalledWith(
- expect.objectContaining({
- content: 'User prefers concise implementation summaries.',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source-1:write-memory',
- userId: 'user-1',
- }),
- );
- expect(result.writeOutcomes).toEqual([{ result: writeResult, toolName: 'writeMemory' }]);
- });
-
- /**
- * @example
- * expect(prompt).toContain('skill_document_with_tool_failure');
- * expect(prompt).toContain('createSelfReviewProposal');
- */
- it('shows deterministic proposal rules for skill document failures in the review prompt', async () => {
- const tools = createMockTools();
- const { chat, modelRuntime } = createMockModelRuntime([
- {
- content: 'No action.',
- },
- ]);
-
- await executeSelfIteration({
- agentId: 'agent-1',
- context: {
- ...reviewContext,
- documentActivity: {
- ...reviewContext.documentActivity,
- skillBucket: [
- {
- agentDocumentId: 'skill-doc-1',
- documentId: 'doc-1',
- hintIsSkill: false,
- reason: 'templateId=agent-skill',
- updatedAt: '2026-05-04T13:00:00.000Z',
- },
- ],
- },
- selfReviewSignals: [
- {
- evidenceRefs: [
- { id: 'topic-1', type: 'topic' },
- { id: 'message-1', type: 'message' },
- { id: 'skill-doc-1', type: 'agent_document' },
- ],
- features: [
- {
- apiName: 'replaceSkillContentCAS',
- failedCount: 2,
- identifier: 'agent-signal-self-iteration',
- topicCount: 1,
- totalCount: 2,
- type: 'tool_usage',
- },
- ],
- kind: 'skill_document_with_tool_failure',
- strength: 'medium',
- },
- ],
- managedSkills: [
- {
- documentId: 'skill-doc-1',
- name: 'release-note-checklist',
- readonly: false,
- },
- ],
- toolActivity: [
- {
- apiName: 'replaceSkillContentCAS',
- failedCount: 2,
- identifier: 'agent-signal-self-iteration',
- messageIds: ['message-1'],
- sampleArgs: [
- JSON.stringify({
- bodyMarkdown: '# Release note checklist',
- proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',
- skillDocumentId: 'skill-doc-1',
- }),
- ],
- sampleErrors: ['CAS snapshot failed'],
- topicIds: ['topic-1'],
- totalCount: 2,
- },
- ],
- },
- maxSteps: 1,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- const prompt = JSON.stringify(chat.mock.calls[0]?.[0].messages);
-
- expect(prompt).toContain('skill_document_with_tool_failure');
- expect(prompt).toContain('createSelfReviewProposal');
- expect(prompt).toContain('# Release note checklist');
- expect(prompt).toContain('refine_skill');
- expect(prompt).toContain('replaceSkillContentCAS');
- });
-
- /**
- * @example
- * expect(systemPrompt).toContain('getEvidenceDigest');
- * expect(systemPrompt).toContain('readSelfReviewProposal');
- */
- it('tells the model to keep evidence ids separate from self-review proposal keys', async () => {
- const tools = createMockTools();
- const { chat, modelRuntime } = createMockModelRuntime([{ content: 'No action needed.' }]);
-
- await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 1,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- const systemPrompt = chat.mock.calls[0]?.[0].messages[0]?.content;
-
- expect(systemPrompt).toContain('getEvidenceDigest');
- expect(systemPrompt).toContain('readSelfReviewProposal');
- expect(systemPrompt).toContain('Evidence ids and proposal keys are different namespaces');
- });
-
- /**
- * @example
- * expect(userPrompt).toContain('<self_iteration_review');
- * expect(userPrompt).toContain('<nightly_review_context_json>');
- */
- it('wraps the nightly review prompt in XML while keeping review labels visible', async () => {
- const tools = createMockTools();
- const { chat, modelRuntime } = createMockModelRuntime([{ content: 'No action needed.' }]);
-
- await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 1,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- const userPrompt = chat.mock.calls[0]?.[0].messages[1]?.content;
-
- expect(userPrompt).toContain('<self_iteration_review');
- expect(userPrompt).toContain('review_window_start="2026-05-03T14:00:00.000Z"');
- expect(userPrompt).toContain('review_window_end="2026-05-04T14:00:00.000Z"');
- expect(userPrompt).toContain('<nightly_review_context_json>');
- expect(userPrompt).not.toContain('Self-iteration context JSON:');
- });
-
- /**
- * @example
- * expect(userPrompt).toContain('Mode: reflection');
- * expect(tools.getEvidenceDigest).toHaveBeenCalledWith(expect.objectContaining({ reviewWindowStart: '2026-05-04T14:00:00.000Z' }));
- */
- it('exposes explicit mode and evidence window to the prompt and evidence tool fallback', async () => {
- const tools = createMockTools();
- const { chat, modelRuntime } = createMockModelRuntime([
- {
- content: 'I will inspect evidence.',
- toolCalls: [
- {
- function: {
- arguments: JSON.stringify({
- evidenceIds: ['task-1'],
- }),
- name: 'getEvidenceDigest',
- },
- id: 'tool-call-evidence',
- type: 'function',
- },
- ],
- },
- {
- content: 'Evidence inspected.',
- },
- ]);
-
- await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 2,
- mode: 'reflection',
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- window: {
- end: '2026-05-04T14:30:00.000Z',
- start: '2026-05-04T14:00:00.000Z',
- },
- });
-
- const userPrompt = chat.mock.calls[0]?.[0].messages[1]?.content;
-
- expect(userPrompt).toContain('Mode: reflection');
- expect(userPrompt).toContain(
- 'Evidence window: 2026-05-04T14:00:00.000Z to 2026-05-04T14:30:00.000Z',
- );
- expect(tools.getEvidenceDigest).toHaveBeenCalledWith(
- expect.objectContaining({
- evidenceIds: ['task-1'],
- reviewWindowEnd: '2026-05-04T14:30:00.000Z',
- reviewWindowStart: '2026-05-04T14:00:00.000Z',
- }),
- );
- });
-
- /**
- * @example
- * expect(result.writeOutcomes).toEqual([]);
- * expect(chat).toHaveBeenCalledTimes(2);
- */
- it('returns an unsupported tool result to the model without throwing the run', async () => {
- const tools = createMockTools();
- const { chat, modelRuntime } = createMockModelRuntime([
- {
- content: 'I will call an unknown tool.',
- toolCalls: [
- {
- function: {
- arguments: '{"unexpected":true}',
- name: 'missingSelfIterationTool',
- },
- id: 'tool-call-unsupported',
- type: 'function',
- },
- ],
- },
- {
- content: 'Unsupported tool noted.',
- },
- ]);
-
- const result = await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 4,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- expect(chat).toHaveBeenCalledTimes(2);
- expect(tools.createSkillIfAbsent).not.toHaveBeenCalled();
- expect(result.content).toContain('Unsupported tool noted.');
- expect(result.writeOutcomes).toEqual([]);
- });
-
- /**
- * @example
- * expect(tools.createSkillIfAbsent).toHaveBeenCalledTimes(1);
- * expect(chat).toHaveBeenCalledTimes(2);
- */
- it('allows AgentRuntime to execute a tool and final continuation when maxSteps is one', async () => {
- const tools = createMockTools();
- const { chat, modelRuntime } = createMockModelRuntime([
- {
- content: 'I will create a skill.',
- toolCalls: [
- {
- function: {
- arguments: JSON.stringify({
- bodyMarkdown: '# Skill',
- idempotencyKey: 'source-1:max-step-create',
- name: 'bounded-skill',
- }),
- name: 'createSkillIfAbsent',
- },
- id: 'tool-call-max-step',
- type: 'function',
- },
- ],
- },
- {
- content: 'Finished after the tool result.',
- },
- ]);
-
- const result = await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 1,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- expect(tools.createSkillIfAbsent).toHaveBeenCalledTimes(1);
- expect(chat).toHaveBeenCalledTimes(2);
- expect(chat.mock.calls[1]?.[0].tools).toEqual([]);
- expect(result.content).toContain('Finished after the tool result.');
- expect(result.writeOutcomes).toHaveLength(1);
- });
-
- /**
- * @example
- * expect(modelVisibleMessages).toContain('Self-review tool call failed.');
- * expect(modelVisibleMessages).not.toContain('secret-token-123');
- */
- it('sanitizes thrown tool errors before adding model-visible tool messages', async () => {
- const tools = {
- ...createMockTools(),
- createSkillIfAbsent: vi.fn(async () => {
- throw new Error('upstream secret-token-123 failed');
- }),
- } satisfies ToolSet;
- const { chat, modelRuntime } = createMockModelRuntime([
- {
- content: 'I will create a skill.',
- toolCalls: [
- {
- function: {
- arguments: JSON.stringify({
- bodyMarkdown: '# Skill',
- idempotencyKey: 'source-1:sensitive-error',
- name: 'sensitive-skill',
- }),
- name: 'createSkillIfAbsent',
- },
- id: 'tool-call-sensitive-error',
- type: 'function',
- },
- ],
- },
- {
- content: 'The tool failed safely.',
- },
- ]);
-
- await executeSelfIteration({
- agentId: 'agent-1',
- context: reviewContext,
- maxSteps: 5,
- model: 'gpt-test',
- modelRuntime,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- });
-
- const modelVisibleMessages = JSON.stringify(chat.mock.calls[1]?.[0].messages);
-
- expect(modelVisibleMessages).toContain('Self-iteration tool call failed.');
- expect(modelVisibleMessages).not.toContain('secret-token-123');
- });
-});
-
-describe('createAgentRunner', () => {
- /**
- * @example
- * expect(result.projectionPlan.actions).toHaveLength(1);
- */
- it('passes source metadata, max steps, and tools into the backend runner', async () => {
- const tools = createNoopTools();
- const run = vi.fn<() => Promise<AgentRunResult>>(async () => ({
- execution: {
- actions: [
- {
- idempotencyKey: 'source-1:noop',
- status: ActionStatus.Skipped,
- },
- ],
- status: ReviewRunStatus.Completed,
- },
- projectionPlan: {
- actions: [
- {
- actionType: 'noop',
- applyMode: ApplyMode.Skip,
- confidence: 1,
- dedupeKey: 'noop',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source-1:noop',
- rationale: 'No change needed.',
- risk: Risk.Low,
- },
- ],
- localDate: '2026-05-04',
- plannerVersion: 'test',
- reviewScope: Scope.Nightly,
- summary: 'No change needed.',
- },
- stepCount: 2,
- }));
- const runner = createAgentRunner({ maxSteps: 10, run, tools });
-
- const result = await runner.run({
- context: reviewContext,
- localDate: '2026-05-04',
- sourceId: 'source-1',
- userId: 'user-1',
- });
-
- expect(run).toHaveBeenCalledWith(
- expect.objectContaining({
- context: reviewContext,
- localDate: '2026-05-04',
- maxSteps: 10,
- reviewScope: Scope.Nightly,
- sourceId: 'source-1',
- tools,
- userId: 'user-1',
- }),
- );
- expect(result.execution.sourceId).toBe('source-1');
- expect(result.projectionPlan.actions).toHaveLength(1);
- });
-
- /**
- * @example
- * expect(result.execution.status).toBe('failed');
- */
- it('returns a conservative failed envelope when the backend runner throws', async () => {
- const runner = createAgentRunner({
- run: vi.fn(async () => {
- throw new Error('model failed');
- }),
- tools: createNoopTools(),
- });
-
- const result = await runner.run({
- context: reviewContext,
- localDate: '2026-05-04',
- sourceId: 'source-1',
- userId: 'user-1',
- });
-
- expect(result.execution).toEqual({
- actions: [],
- sourceId: 'source-1',
- status: ReviewRunStatus.Failed,
- });
- expect(result.projectionPlan).toEqual(
- expect.objectContaining({
- actions: [],
- localDate: '2026-05-04',
- reviewScope: Scope.Nightly,
- }),
- );
- expect(result.stepCount).toBe(10);
- });
-});
diff --git a/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts b/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts
index a712e333aaf..9d6f4876410 100644
--- a/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts
@@ -37,6 +37,39 @@ describe('extractFromFinalState', () => {
]);
});
+ it('recovers apiName from the result content (real persisted shape, no message-level apiName)', () => {
+ // The agent runtime persists tool messages with only content/role/tool_call_id
+ // — there is NO message-level apiName in live runs. The tool runtime stamps
+ // apiName into the content (alongside kind), so the extractor must read it from
+ // there. This guards the bug where action receipts were silently dropped.
+ const state = buildState([
+ {
+ content: JSON.stringify({
+ apiName: 'createSkillIfAbsent',
+ kind: 'mutation',
+ resourceId: 'skill_1',
+ summary: 'New skill',
+ }),
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ expect(extractFromFinalState(state, 'mutation')).toEqual([
+ {
+ apiName: 'createSkillIfAbsent',
+ data: {
+ apiName: 'createSkillIfAbsent',
+ kind: 'mutation',
+ resourceId: 'skill_1',
+ summary: 'New skill',
+ },
+ kind: 'mutation',
+ toolCallId: 'call_1',
+ },
+ ]);
+ });
+
it('falls back to pluginState.kind when content is not a JSON object', () => {
const state = buildState([
{
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.ts b/src/server/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.ts
new file mode 100644
index 00000000000..0bbb7082460
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/__test__/buildSelfIterationReceipts.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+
+import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';
+
+import type { ToolResultWithKind } from '../../finalStateExtractor';
+import { buildSelfIterationReceipts } from '../buildSelfIterationReceipts';
+
+const marker: AgentSignalOperationMarker = {
+ anchorMessageId: 'msg_anchor',
+ kind: 'nightly-review',
+ localDate: '2026-05-30',
+ sourceId: 'nightly-review:user_1:agent_1:2026-05-30',
+ triggerMessageId: 'msg_trigger',
+};
+
+const baseInput = {
+ agentId: 'agent_1',
+ artifacts: [] as ToolResultWithKind[],
+ createdAt: 1_748_600_000_000,
+ marker,
+ mutations: [] as ToolResultWithKind[],
+ operationId: 'op_1',
+ sourceId: marker.sourceId!,
+ sourceType: 'agent.execution.completed',
+ topicId: 'tpc_1',
+ userId: 'user_1',
+};
+
+describe('buildSelfIterationReceipts', () => {
+ it('always emits one summary receipt with run counts', () => {
+ const receipts = buildSelfIterationReceipts({
+ ...baseInput,
+ artifacts: [{ apiName: 'recordSelfReviewIdea', data: {}, kind: 'artifact' }],
+ });
+
+ expect(receipts).toHaveLength(1);
+ const [summary] = receipts;
+ expect(summary.id).toBe(`${marker.sourceId}:self-iteration-summary`);
+ expect(summary.kind).toBe('review');
+ expect(summary.status).toBe('completed');
+ expect(summary.title).toBe('Nightly self-review completed');
+ expect(summary.anchorMessageId).toBe('msg_anchor');
+ expect(summary.triggerMessageId).toBe('msg_trigger');
+ expect(summary.metadata?.actionCount).toBe(0);
+ });
+
+ it('projects a memory mutation into an applied memory receipt with a target', () => {
+ const [, memory] = buildSelfIterationReceipts({
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'writeMemory',
+ data: { kind: 'mutation', resourceId: 'mem_1', summary: 'Saved tone preference' },
+ kind: 'mutation',
+ toolCallId: 'call_1',
+ },
+ ],
+ });
+
+ expect(memory.kind).toBe('memory');
+ expect(memory.status).toBe('applied');
+ expect(memory.id).toBe(`${marker.sourceId}:call_1:memory`);
+ expect(memory.title).toBe('Saved tone preference');
+ expect(memory.target).toEqual({
+ id: 'mem_1',
+ summary: 'Saved tone preference',
+ title: 'Saved tone preference',
+ type: 'memory',
+ });
+ });
+
+ it('maps proposal creation to a proposed review receipt without a target', () => {
+ const [, proposal] = buildSelfIterationReceipts({
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'createSelfReviewProposal',
+ data: { proposalId: 'brf_1', resourceId: 'brf_1', summary: 'Refine skill X' },
+ kind: 'mutation',
+ toolCallId: 'call_2',
+ },
+ ],
+ });
+
+ expect(proposal.kind).toBe('review');
+ expect(proposal.status).toBe('proposed');
+ expect(proposal.target).toBeUndefined();
+ });
+
+ it('collapses a skipped tool result to a skipped receipt', () => {
+ const [, skill] = buildSelfIterationReceipts({
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'createSkillIfAbsent',
+ data: { status: 'skipped_unsupported', summary: 'name taken' },
+ kind: 'mutation',
+ toolCallId: 'call_3',
+ },
+ ],
+ });
+
+ expect(skill.kind).toBe('skill');
+ expect(skill.status).toBe('skipped');
+ });
+
+ it('is idempotent: re-projecting the same run yields the same receipt ids', () => {
+ const input = {
+ ...baseInput,
+ mutations: [
+ {
+ apiName: 'writeMemory',
+ data: { resourceId: 'mem_1' },
+ kind: 'mutation',
+ toolCallId: 'c1',
+ },
+ ] as ToolResultWithKind[],
+ };
+
+ const first = buildSelfIterationReceipts(input).map((r) => r.id);
+ const second = buildSelfIterationReceipts(input).map((r) => r.id);
+ expect(first).toEqual(second);
+ });
+});
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.ts b/src/server/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.ts
new file mode 100644
index 00000000000..d5cd374255f
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/__test__/completionLoop.integration.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment node
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createCompletionPolicy } from '../../../../policies/completionPolicy';
+import type { AgentSignalReceipt, AgentSignalReceiptStore } from '../../../receiptService';
+import type { SelfIterationCompletionPayload } from '../extractCompletionPayload';
+import { createSelfIterationCompletionHandler } from '../selfIterationCompletionHandler';
+
+/**
+ * Exercises the whole S2 completion loop in-process with the REAL wiring:
+ * completion policy source handler → onSelfIterationCompleted → receipt
+ * projection → persist. Only the finalState extraction is synthesized here (it
+ * is covered by extractCompletionPayload.test.ts); everything downstream is the
+ * production code path.
+ */
+
+interface CapturedHandler {
+ handle: (source: { payload: Record<string, unknown> }) => Promise<void>;
+ id: string;
+ listen: string;
+}
+
+const installAndCapture = (middleware: ReturnType<typeof createCompletionPolicy>) => {
+ const sourceHandlers: CapturedHandler[] = [];
+ middleware.install({
+ handleAction: vi.fn(),
+ handleSignal: vi.fn(),
+ handleSource: (handler: unknown) => {
+ sourceHandlers.push(handler as CapturedHandler);
+ },
+ } as never);
+ return sourceHandlers;
+};
+
+/** In-memory receipt store mirroring the real store's append-once dedupe. */
+const makeInMemoryReceiptStore = () => {
+ const appended: AgentSignalReceipt[] = [];
+ const seen = new Set<string>();
+ const store: AgentSignalReceiptStore = {
+ appendReceipt: async (receipt) => {
+ if (seen.has(receipt.id)) return false;
+ seen.add(receipt.id);
+ appended.push(receipt);
+ return true;
+ },
+ listReceipts: async () => ({ receipts: [] }),
+ };
+ return { appended, store };
+};
+
+const selfIteration: SelfIterationCompletionPayload = {
+ artifacts: [{ apiName: 'recordSelfReviewIdea', data: { idea: 'try x' }, kind: 'artifact' }],
+ marker: {
+ anchorMessageId: 'msg_anchor',
+ kind: 'nightly-review',
+ localDate: '2026-05-30',
+ sourceId: 'nightly-review:user_1:agent_1:2026-05-30',
+ },
+ mutations: [
+ {
+ apiName: 'writeMemory',
+ data: { resourceId: 'mem_1', summary: 'Saved tone preference' },
+ kind: 'mutation',
+ toolCallId: 'call_mem',
+ },
+ {
+ apiName: 'createSelfReviewProposal',
+ data: { proposalId: 'brf_1', summary: 'Refine skill X' },
+ kind: 'mutation',
+ toolCallId: 'call_prop',
+ },
+ ],
+ userId: 'user_1',
+};
+
+const completedPayload = {
+ agentId: BUILTIN_AGENT_SLUGS.nightlyReview,
+ operationId: 'op_1',
+ selfIteration,
+ topicId: 'topic_1',
+};
+
+describe('S2 completion loop (policy → handler → projection → persist)', () => {
+ it('projects + persists receipts for a completed self-iteration run', async () => {
+ const { appended, store } = makeInMemoryReceiptStore();
+ const [handler] = installAndCapture(
+ createCompletionPolicy({
+ onSelfIterationCompleted: createSelfIterationCompletionHandler({ receiptStore: store }),
+ }),
+ );
+
+ await handler.handle({ payload: completedPayload });
+
+ // summary + one receipt per mutation
+ expect(appended.map((r) => r.kind)).toEqual(['review', 'memory', 'review']);
+
+ const memory = appended.find((r) => r.kind === 'memory')!;
+ expect(memory.status).toBe('applied');
+ expect(memory.topicId).toBe('topic_1');
+ expect(memory.anchorMessageId).toBe('msg_anchor');
+ expect(memory.target).toMatchObject({ id: 'mem_1', type: 'memory' });
+
+ const proposal = appended.find((r) => r.id.includes('call_prop'))!;
+ expect(proposal.kind).toBe('review');
+ expect(proposal.status).toBe('proposed');
+ expect(proposal.target).toBeUndefined();
+ });
+
+ it('is idempotent: replaying the same completion adds no duplicate receipts', async () => {
+ const { appended, store } = makeInMemoryReceiptStore();
+ const [handler] = installAndCapture(
+ createCompletionPolicy({
+ onSelfIterationCompleted: createSelfIterationCompletionHandler({ receiptStore: store }),
+ }),
+ );
+
+ await handler.handle({ payload: completedPayload });
+ const countAfterFirst = appended.length;
+ await handler.handle({ payload: completedPayload });
+
+ expect(appended).toHaveLength(countAfterFirst);
+ });
+
+ it('projects a single memory receipt (no summary) with target + anchor for a memory-kind run', async () => {
+ // A memory-writer run dispatched async by handleUserMemoryAction: it carries
+ // a `memory` marker (extractMemoryMutations synthesizes the writeMemory
+ // mutation from finalState). The receipt must still appear with the right
+ // target + anchor — the async replacement for the old synchronous projection.
+ const { appended, store } = makeInMemoryReceiptStore();
+ const [handler] = installAndCapture(
+ createCompletionPolicy({
+ onSelfIterationCompleted: createSelfIterationCompletionHandler({ receiptStore: store }),
+ }),
+ );
+
+ const memoryPayload: Record<string, unknown> = {
+ // A memory run executes as the user's own agent, not a builtin slug.
+ agentId: 'agent_user_1',
+ operationId: 'op_mem',
+ selfIteration: {
+ artifacts: [],
+ marker: {
+ anchorMessageId: 'assistant_msg_1',
+ kind: 'memory',
+ sourceId: 'source_1:action-memory-1',
+ triggerMessageId: 'user_msg_1',
+ },
+ mutations: [
+ {
+ apiName: 'writeMemory',
+ data: { resourceId: 'mem_1', status: 'applied', summary: 'Saved tone preference' },
+ kind: 'mutation',
+ },
+ ],
+ userId: 'user_1',
+ },
+ topicId: 'topic_1',
+ };
+
+ await handler.handle({ payload: memoryPayload });
+
+ // A single memory write surfaces as just its action receipt — no aggregate
+ // review summary (that is only for nightly-review / reflection runs).
+ expect(appended).toHaveLength(1);
+ const memory = appended[0];
+ expect(memory.kind).toBe('memory');
+ expect(memory.status).toBe('applied');
+ expect(memory.anchorMessageId).toBe('assistant_msg_1');
+ expect(memory.triggerMessageId).toBe('user_msg_1');
+ expect(memory.topicId).toBe('topic_1');
+ expect(memory.target).toMatchObject({ id: 'mem_1', type: 'memory' });
+ });
+
+ it('no-ops when the completion carries no self-iteration payload (no marker stamped)', async () => {
+ const { appended, store } = makeInMemoryReceiptStore();
+ const [handler] = installAndCapture(
+ createCompletionPolicy({
+ onSelfIterationCompleted: createSelfIterationCompletionHandler({ receiptStore: store }),
+ }),
+ );
+
+ await handler.handle({
+ payload: {
+ agentId: BUILTIN_AGENT_SLUGS.nightlyReview,
+ operationId: 'op_2',
+ topicId: 'topic_2',
+ },
+ });
+
+ expect(appended).toHaveLength(0);
+ });
+});
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts b/src/server/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts
new file mode 100644
index 00000000000..f703492adae
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/__test__/extractCompletionPayload.test.ts
@@ -0,0 +1,107 @@
+import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
+import { describe, expect, it } from 'vitest';
+
+import { extractSelfIterationCompletionPayload } from '../extractCompletionPayload';
+
+// Real persisted shape: the agent runtime stores tool messages with only
+// content/role/tool_call_id — there is NO message-level apiName in live runs.
+// The tool runtime stamps apiName + kind INTO the content, so the extractor must
+// recover apiName from there.
+const toolMessage = (apiName: string, kind: string, data: Record<string, unknown>) => ({
+ content: JSON.stringify({ apiName, kind, ...data }),
+ role: 'tool',
+ tool_call_id: `${apiName}_call`,
+});
+
+const buildState = (metadata: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({
+ messages: [],
+ metadata,
+ ...extra,
+});
+
+const reviewMetadata = {
+ agentId: 'agent_user_1',
+ agentSignal: { kind: 'nightly-review', sourceId: 'src_1' },
+ userId: 'user_1',
+};
+
+describe('extractSelfIterationCompletionPayload', () => {
+ it('returns undefined for an unmarked run', () => {
+ expect(
+ extractSelfIterationCompletionPayload(buildState({ agentId: 'agent_x', userId: 'user_1' })),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined without a userId', () => {
+ expect(
+ extractSelfIterationCompletionPayload(
+ buildState({ agentId: 'agent_x', agentSignal: { kind: 'nightly-review' } }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it('extracts via the marker even for a user agent (no self-iteration slug)', () => {
+ const result = extractSelfIterationCompletionPayload(
+ buildState(reviewMetadata, {
+ messages: [
+ toolMessage('createSelfReviewProposal', 'mutation', { proposalId: 'brf_1' }),
+ toolMessage('recordSelfReviewIdea', 'artifact', { idea: 'x' }),
+ ],
+ }),
+ );
+
+ expect(result?.marker.kind).toBe('nightly-review');
+ expect(result?.userId).toBe('user_1');
+ expect(result?.mutations).toHaveLength(1);
+ expect(result?.mutations[0].apiName).toBe('createSelfReviewProposal');
+ expect(result?.artifacts).toHaveLength(1);
+ });
+
+ it('synthesizes a writeMemory mutation for a memory-kind run from finalState usage', () => {
+ const result = extractSelfIterationCompletionPayload(
+ buildState(
+ {
+ agentId: 'agent_user_1',
+ agentSignal: { kind: 'memory', sourceId: 'mem-src_1' },
+ userId: 'user_1',
+ },
+ {
+ status: 'finished',
+ usage: {
+ tools: {
+ byTool: [
+ {
+ calls: 1,
+ errors: 0,
+ name: `${MemoryIdentifier}/${MemoryApiName.addPreferenceMemory}`,
+ },
+ ],
+ },
+ },
+ },
+ ),
+ );
+
+ expect(result?.marker.kind).toBe('memory');
+ expect(result?.artifacts).toHaveLength(0);
+ expect(result?.mutations).toHaveLength(1);
+ expect(result?.mutations[0].apiName).toBe('writeMemory');
+ expect((result?.mutations[0].data as { status?: string }).status).toBe('applied');
+ });
+
+ it('yields no memory mutation when the memory run did not apply a write', () => {
+ const result = extractSelfIterationCompletionPayload(
+ buildState(
+ {
+ agentId: 'agent_user_1',
+ agentSignal: { kind: 'memory', sourceId: 'mem-src_2' },
+ userId: 'user_1',
+ },
+ { status: 'finished', usage: { tools: { byTool: [] } } },
+ ),
+ );
+
+ expect(result?.marker.kind).toBe('memory');
+ expect(result?.mutations).toHaveLength(0);
+ });
+});
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts b/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
new file mode 100644
index 00000000000..6b8444b4973
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
@@ -0,0 +1,186 @@
+import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/operationMarker';
+
+import type { AgentSignalReceipt } from '../../receiptService';
+import type { ToolResultWithKind } from '../finalStateExtractor';
+
+/**
+ * Maps a durable mutation tool's api name to the user-facing receipt domain.
+ * Proposal lifecycle tools surface as `review`; skill / memory writes surface as
+ * their resource domain. Any unmapped mutation is treated as a `review` outcome.
+ */
+const RECEIPT_KIND_BY_API: Record<string, AgentSignalReceipt['kind']> = {
+ closeSelfReviewProposal: 'review',
+ createSelfReviewProposal: 'review',
+ createSkillIfAbsent: 'skill',
+ refreshSelfReviewProposal: 'review',
+ replaceSkillContentCAS: 'skill',
+ supersedeSelfReviewProposal: 'review',
+ writeMemory: 'memory',
+};
+
+/**
+ * Default terminal status per api name, mirroring the legacy `createToolSet`
+ * `successStatus` so receipts read the same on the execAgent path. A tool result
+ * carrying an explicit `skipped_*` status overrides this to `skipped`.
+ */
+const SUCCESS_STATUS_BY_API: Record<string, AgentSignalReceipt['status']> = {
+ closeSelfReviewProposal: 'applied',
+ createSelfReviewProposal: 'proposed',
+ createSkillIfAbsent: 'applied',
+ refreshSelfReviewProposal: 'proposed',
+ replaceSkillContentCAS: 'applied',
+ supersedeSelfReviewProposal: 'applied',
+ writeMemory: 'applied',
+};
+
+const DEFAULT_TITLE_BY_API: Record<string, string> = {
+ closeSelfReviewProposal: 'Self-review proposal closed',
+ createSelfReviewProposal: 'Self-review proposal created',
+ createSkillIfAbsent: 'Skill created',
+ refreshSelfReviewProposal: 'Self-review proposal refreshed',
+ replaceSkillContentCAS: 'Skill updated',
+ supersedeSelfReviewProposal: 'Self-review proposal superseded',
+ writeMemory: 'Memory saved',
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const str = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.length > 0 ? value : undefined;
+
+/** A `skipped_unsupported` / `skipped_stale` tool status collapses to `skipped`. */
+const isSkippedStatus = (status: unknown): boolean =>
+ typeof status === 'string' && status.startsWith('skipped');
+
+export interface BuildSelfIterationReceiptsInput {
+ agentId: string;
+ /** Non-actionable idea / intent recorder outputs (kind: artifact). */
+ artifacts: ToolResultWithKind[];
+ /** Receipt creation timestamp (ms). */
+ createdAt: number;
+ /** The run's agent-signal marker, read from the operation. */
+ marker: AgentSignalOperationMarker;
+ /** Durable write tool outputs (kind: mutation). */
+ mutations: ToolResultWithKind[];
+ operationId: string;
+ sourceId: string;
+ sourceType: string;
+ topicId: string;
+ userId: string;
+}
+
+const SUMMARY_TITLE_BY_KIND: Record<AgentSignalOperationMarker['kind'], string> = {
+ 'memory': 'Memory write completed',
+ 'nightly-review': 'Nightly self-review completed',
+ 'self-feedback-intent': 'Self-feedback intent completed',
+ 'self-reflection': 'Self-reflection completed',
+};
+
+/**
+ * Projects the durable outcomes of a completed self-iteration run into
+ * user-visible Agent Signal receipts, driven entirely by the run's finalState
+ * (no side-channel accumulator). Produces one summary receipt per run plus one
+ * action receipt per durable mutation. Receipt ids are deterministic
+ * (`sourceId` + tool call id), so re-projecting the same run is idempotent — the
+ * receipt store dedupes by id.
+ *
+ * Mirrors the legacy `createReceipts` mapping (kind / status / target) so
+ * receipts read identically whether produced by the old runtime accumulator or
+ * the execAgent completion path.
+ */
+export const buildSelfIterationReceipts = (
+ input: BuildSelfIterationReceiptsInput,
+): AgentSignalReceipt[] => {
+ const {
+ agentId,
+ artifacts,
+ createdAt,
+ marker,
+ mutations,
+ operationId,
+ sourceId,
+ sourceType,
+ topicId,
+ userId,
+ } = input;
+
+ const base = {
+ // A self-iteration run executes under a builtin slug, so the operation's
+ // agentId is the builtin agent; attribute the receipt to the reviewed user
+ // agent carried on the marker. Memory runs (run as the user's own agent)
+ // leave marker.agentId unset and fall back to the run agentId.
+ agentId: marker.agentId ?? agentId,
+ ...(marker.anchorMessageId ? { anchorMessageId: marker.anchorMessageId } : {}),
+ createdAt,
+ operationId,
+ sourceId,
+ sourceType,
+ topicId,
+ ...(marker.triggerMessageId ? { triggerMessageId: marker.triggerMessageId } : {}),
+ userId,
+ } satisfies Partial<AgentSignalReceipt>;
+
+ // A single memory write surfaces as just its action receipt — no aggregate
+ // "review summary" (that is for nightly-review / reflection runs that capture
+ // ideas across multiple actions).
+ const includeSummary = marker.kind !== 'memory';
+
+ const summary: AgentSignalReceipt = {
+ ...base,
+ detail: `Captured ${artifacts.length} idea(s) and applied ${mutations.length} write(s).`,
+ id: `${sourceId}:self-iteration-summary`,
+ kind: 'review',
+ metadata: {
+ actionCount: mutations.length,
+ ...(marker.localDate ? { localDate: marker.localDate } : {}),
+ sourceType,
+ },
+ status: 'completed',
+ title: SUMMARY_TITLE_BY_KIND[marker.kind],
+ };
+
+ const actionReceipts = mutations.flatMap((mutation, index): AgentSignalReceipt[] => {
+ const apiName = mutation.apiName;
+ if (!apiName) return [];
+
+ const data = isRecord(mutation.data) ? mutation.data : {};
+ const kind = RECEIPT_KIND_BY_API[apiName] ?? 'review';
+ const status = isSkippedStatus(data.status)
+ ? 'skipped'
+ : (SUCCESS_STATUS_BY_API[apiName] ?? 'applied');
+
+ const summaryText = str(data.summary);
+ const resourceId = str(data.resourceId);
+ const title = summaryText ?? DEFAULT_TITLE_BY_API[apiName] ?? 'Agent Signal action';
+
+ return [
+ {
+ ...base,
+ detail: summaryText ?? title,
+ // Deterministic + idempotent: same run re-projects to the same id.
+ id: `${sourceId}:${mutation.toolCallId ?? `${apiName}:${index}`}:${kind}`,
+ kind,
+ metadata: {
+ ...(marker.localDate ? { localDate: marker.localDate } : {}),
+ sourceType,
+ },
+ status,
+ // Proposal (`review`) outcomes have no openable resource target.
+ ...(kind === 'review'
+ ? {}
+ : {
+ target: {
+ ...(resourceId ? { id: resourceId } : {}),
+ ...(summaryText ? { summary: summaryText } : {}),
+ title,
+ type: kind,
+ },
+ }),
+ title,
+ },
+ ];
+ });
+
+ return includeSummary ? [summary, ...actionReceipts] : actionReceipts;
+};
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts b/src/server/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts
new file mode 100644
index 00000000000..c23d8a241b8
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/extractCompletionPayload.ts
@@ -0,0 +1,95 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+
+import {
+ type AgentSignalOperationMarker,
+ readAgentSignalMarker,
+} from '@/server/services/agentSignal/operationMarker';
+import { resolveMemoryActionResultFromState } from '@/server/services/agentSignal/policies/analyzeIntent/actions/memoryActionResult';
+
+import {
+ extractArtifacts,
+ extractMutations,
+ type ToolResultWithKind,
+} from '../finalStateExtractor';
+
+/**
+ * Compact self-iteration completion data, extracted from the run's finalState at
+ * the one point it is in hand (the completion lifecycle) and carried on the
+ * `agent.execution.completed` source payload. Holds only the kind-tagged tool
+ * outcomes (small) + the run marker + owner — never the full message history.
+ */
+export interface SelfIterationCompletionPayload {
+ /** Non-actionable idea / intent recorder outputs. */
+ artifacts: ToolResultWithKind[];
+ /** Run marker stamped at dispatch (kind / sourceId / window / anchors). */
+ marker: AgentSignalOperationMarker;
+ /** Durable write tool outputs. */
+ mutations: ToolResultWithKind[];
+ /** Owner — the completion source payload does not carry userId. */
+ userId: string;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/**
+ * Memory-writer runs use the generic memory builtin tool, whose results are NOT
+ * `kind`-tagged, so `extractMutations` finds nothing. Re-derive the durable
+ * outcome from the run's finalState (the same logic the synchronous runner used)
+ * and synthesize a `writeMemory` mutation so the receipt projector treats it like
+ * any other durable write. Only an applied write yields a mutation; skip / fail
+ * leave the run with no durable receipt.
+ */
+const extractMemoryMutations = (finalState: AgentState): ToolResultWithKind[] => {
+ const result = resolveMemoryActionResultFromState(finalState);
+ if (result.status !== 'applied') return [];
+
+ return [
+ {
+ apiName: 'writeMemory',
+ data: {
+ kind: 'mutation',
+ resourceId: result.target?.id ?? result.target?.memoryId,
+ status: 'applied',
+ summary: result.detail,
+ },
+ kind: 'mutation',
+ },
+ ];
+};
+
+/**
+ * Extracts the compact self-iteration completion payload from a terminal agent
+ * state, or `undefined` when the run carried no agent-signal marker.
+ *
+ * Keyed on the operation marker (stamped at dispatch), NOT the agent slug — a
+ * memory-writer run executes as the user's own agent, so a slug check would miss
+ * it. Returns `undefined` (a safe no-op) for every unmarked run, keeping
+ * completion inert until a dispatcher opts in by stamping the marker.
+ */
+export const extractSelfIterationCompletionPayload = (
+ state: unknown,
+): SelfIterationCompletionPayload | undefined => {
+ if (!isRecord(state)) return undefined;
+ const metadata = isRecord(state.metadata) ? state.metadata : undefined;
+ if (!metadata) return undefined;
+
+ const marker = readAgentSignalMarker(metadata);
+ if (!marker) return undefined;
+
+ const userId = typeof metadata.userId === 'string' ? metadata.userId : undefined;
+ if (!userId) return undefined;
+
+ const finalState = state as unknown as AgentState;
+
+ if (marker.kind === 'memory') {
+ return { artifacts: [], marker, mutations: extractMemoryMutations(finalState), userId };
+ }
+
+ return {
+ artifacts: extractArtifacts(finalState),
+ marker,
+ mutations: extractMutations(finalState),
+ userId,
+ };
+};
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/index.ts b/src/server/services/agentSignal/services/selfIteration/completion/index.ts
new file mode 100644
index 00000000000..d8c9a9fa9e5
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/index.ts
@@ -0,0 +1,9 @@
+export {
+ buildSelfIterationReceipts,
+ type BuildSelfIterationReceiptsInput,
+} from './buildSelfIterationReceipts';
+export {
+ extractSelfIterationCompletionPayload,
+ type SelfIterationCompletionPayload,
+} from './extractCompletionPayload';
+export { createSelfIterationCompletionHandler } from './selfIterationCompletionHandler';
diff --git a/src/server/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts b/src/server/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts
new file mode 100644
index 00000000000..edaf57d1753
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/completion/selfIterationCompletionHandler.ts
@@ -0,0 +1,61 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import debug from 'debug';
+
+import type { CompletionCallbackParams } from '../../../policies/completionPolicy';
+import { type AgentSignalReceiptStore, persistAgentSignalReceipts } from '../../receiptService';
+import { buildSelfIterationReceipts } from './buildSelfIterationReceipts';
+
+const log = debug('lobe-server:completion-lifecycle');
+
+export interface SelfIterationCompletionHandlerOptions {
+ /** Receipt store override (defaults to the Redis store). Injected in tests. */
+ receiptStore?: AgentSignalReceiptStore;
+}
+
+/**
+ * Builds the `onSelfIterationCompleted` callback wired into the completion
+ * policy. After a background self-iteration run finishes, it projects the run's
+ * finalState tool outcomes (carried on the completion source payload) into
+ * user-visible receipts and persists them — the execAgent replacement for the
+ * old in-runtime receipt accumulator.
+ *
+ * Idempotent: `buildSelfIterationReceipts` derives deterministic receipt ids
+ * from the source id + tool call ids, and the receipt store dedupes by id, so a
+ * replayed completion event re-projects to the same receipts.
+ */
+export const createSelfIterationCompletionHandler =
+ ({ receiptStore }: SelfIterationCompletionHandlerOptions = {}) =>
+ async (params: CompletionCallbackParams): Promise<void> => {
+ const { agentId, operationId, selfIteration, topicId } = params;
+ if (!selfIteration) return;
+
+ const { artifacts, marker, mutations, userId } = selfIteration;
+ const sourceId = marker.sourceId ?? operationId;
+ const resolvedTopicId = topicId ?? marker.topicId ?? sourceId;
+
+ const receipts = buildSelfIterationReceipts({
+ agentId,
+ artifacts,
+ createdAt: Date.now(),
+ marker,
+ mutations,
+ operationId,
+ sourceId,
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted,
+ topicId: resolvedTopicId,
+ userId,
+ });
+
+ log(
+ '[completion-handler] projecting %d receipt(s) for op=%s kind=%s (artifacts=%d mutations=%d)',
+ receipts.length,
+ operationId,
+ marker.kind,
+ artifacts.length,
+ mutations.length,
+ );
+
+ await persistAgentSignalReceipts(receipts, receiptStore ? { store: receiptStore } : {});
+
+ log('[completion-handler] persisted %d receipt(s) for op=%s', receipts.length, operationId);
+ };
diff --git a/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.ts b/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.ts
new file mode 100644
index 00000000000..9e491092d31
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/dispatch/enqueueSelfIterationRun.ts
@@ -0,0 +1,109 @@
+import type { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { type AgentSignalOperationMarker, RequestTrigger, ThreadType } from '@lobechat/types';
+
+import { ThreadModel } from '@/database/models/thread';
+import type { LobeChatDatabase } from '@/database/type';
+
+/** The three builtin self-iteration agent slugs an execAgent run can dispatch to. */
+export type SelfIterationSlug =
+ | typeof BUILTIN_AGENT_SLUGS.nightlyReview
+ | typeof BUILTIN_AGENT_SLUGS.selfFeedbackIntent
+ | typeof BUILTIN_AGENT_SLUGS.selfReflection;
+
+export interface EnqueueSelfIterationRunInput {
+ /** The user agent being reviewed — owns the run, marker, and isolated thread. */
+ agentId: string;
+ db: LobeChatDatabase;
+ /**
+ * Run-scoped marker (kind / sourceId / review window / anchors). Stamped onto
+ * the operation so the S2 completion path can project receipts/briefs from
+ * finalState. `marker.sourceId` MUST be the originating source id (not the new
+ * operation id) so receipt ids stay stable / idempotent across replays.
+ */
+ marker: AgentSignalOperationMarker;
+ /** Step budget for the run; falls back to the builtin agent's own default. */
+ maxSteps?: number;
+ /** The evidence digest rendered as the user prompt (createAgentSignalSelfIterationPrompt). */
+ prompt: string;
+ slug: SelfIterationSlug;
+ /** Assistant message to anchor the isolated thread under, when one exists. */
+ sourceMessageId?: string;
+ /** Isolated-thread title (defaults to a generic self-iteration label). */
+ threadTitle?: string;
+ /** Topic the run is scoped to; a new topic is created when absent. */
+ topicId?: string;
+ userId: string;
+}
+
+export interface EnqueueSelfIterationRunResult {
+ operationId: string;
+ threadId?: string;
+ topicId: string;
+}
+
+/**
+ * Dispatches a background self-iteration run (nightly-review / self-reflection /
+ * self-feedback-intent) onto the unified async `execAgent` queue — the
+ * replacement for the hand-rolled in-memory `AgentRuntime` + `executeSelfIteration`.
+ *
+ * - The builtin `slug` resolves the self-iteration tools server-side via the S1
+ * serverRuntime bridge (`agent-signal-{review,reflection,feedback-intent}`).
+ * - `appContext.agentSignal` stamps the marker so the S2 completion handler
+ * projects receipts (and, for nightly-review, the brief is written in-run by
+ * the review tool primitive) from finalState.
+ * - `suppressSignal: true` (and the slug being in `SELF_ITERATION_AGENT_SLUGS`)
+ * stop the synthesised user message from recursing into analyzeIntent.
+ *
+ * Fire-and-forget: returns as soon as the operation is enqueued (`autoStart`).
+ * The run completes over later invocations; side effects land on completion.
+ */
+export const enqueueSelfIterationRun = async (
+ input: EnqueueSelfIterationRunInput,
+): Promise<EnqueueSelfIterationRunResult> => {
+ // Isolate the run under the triggering assistant message (when present) so its
+ // messages don't flatten into the main topic — mirrors the memory-writer path.
+ let threadId: string | undefined;
+ if (input.topicId && input.sourceMessageId) {
+ try {
+ const thread = await new ThreadModel(input.db, input.userId).create({
+ agentId: input.agentId,
+ sourceMessageId: input.sourceMessageId,
+ title: input.threadTitle ?? 'Agent Signal Self-Iteration',
+ topicId: input.topicId,
+ type: ThreadType.Isolation,
+ });
+ threadId = thread?.id;
+ } catch {
+ // Non-fatal: fall back to writing into the main topic if thread creation fails.
+ }
+ }
+
+ const { AiAgentService } = await import('@/server/services/aiAgent');
+ const result = await new AiAgentService(input.db, input.userId).execAgent({
+ appContext: {
+ // No agentId here — the run executes under the builtin `slug` (which
+ // supplies its tools / systemRole / model). The reviewed user agent
+ // travels on `marker.agentId`; execAgent prefers it for the operation +
+ // tool-execution context so resource writes (skills) and receipts both
+ // attribute to the reviewed agent, not the builtin one.
+ agentSignal: input.marker,
+ scope: 'chat',
+ ...(input.sourceMessageId ? { sourceMessageId: input.sourceMessageId } : {}),
+ suppressSignal: true,
+ ...(threadId ? { threadId } : {}),
+ ...(input.topicId ? { topicId: input.topicId } : {}),
+ },
+ autoStart: true,
+ ...(input.maxSteps ? { maxSteps: input.maxSteps } : {}),
+ prompt: input.prompt,
+ slug: input.slug,
+ trigger: RequestTrigger.AgentSignal,
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+
+ return {
+ operationId: result.operationId,
+ ...(threadId ? { threadId } : {}),
+ topicId: result.topicId,
+ };
+};
diff --git a/src/server/services/agentSignal/services/selfIteration/execute.ts b/src/server/services/agentSignal/services/selfIteration/execute.ts
deleted file mode 100644
index 7520e1cb5f8..00000000000
--- a/src/server/services/agentSignal/services/selfIteration/execute.ts
+++ /dev/null
@@ -1,1500 +0,0 @@
-import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
-import { AgentRuntime, GeneralChatAgent } from '@lobechat/agent-runtime';
-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
-import type { LobeToolManifest } from '@lobechat/context-engine';
-import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';
-import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
-import { consumeStreamUntilDone } from '@lobechat/model-runtime';
-import { SpanStatusCode } from '@lobechat/observability-otel/api';
-import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
-import {
- createAgentSignalSelfIterationPrompt,
- createAgentSignalSelfIterationSystemRole,
- createAgentSignalSelfIterationToolSystemRole,
-} from '@lobechat/prompts';
-import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';
-import { RequestTrigger } from '@lobechat/types';
-import { isTrimmedNonEmptyString, toRecord } from '@lobechat/utils';
-
-import type { NightlyReviewContext } from './review/collect';
-import type { SelfReviewIdea, SelfReviewProposalBaseSnapshot } from './review/proposal';
-import type {
- CloseSelfReviewProposalInput,
- CreateSelfReviewProposalInput,
- CreateSkillIfAbsentInput,
- RefreshSelfReviewProposalInput,
- ReplaceSkillContentCASInput,
- SupersedeSelfReviewProposalInput,
- ToolSet,
- ToolWriteInput,
- ToolWriteResult,
- WriteMemoryInput,
-} from './tools/shared';
-import type {
- ActionTarget,
- EvidenceRef,
- IterationMode,
- IterationWindow,
- Plan,
- RunResult,
- SelfFeedbackIntent,
-} from './types';
-import { ReviewRunStatus, Risk, Scope } from './types';
-
-/** Built-in tool identifier used for self-iteration AgentRuntime tool calls. */
-export const selfIterationToolIdentifier = 'agent-signal-self-iteration';
-
-/** Read-only self-iteration tools exposed to the tool-first runtime. */
-export type ReadToolName =
- | 'getEvidenceDigest'
- | 'getManagedSkill'
- | 'listSelfReviewProposals'
- | 'listManagedSkills'
- | 'readSelfReviewProposal';
-
-/** Write self-iteration tools whose terminal outcomes must be retained by the runtime. */
-export type WriteToolName =
- | 'closeSelfReviewProposal'
- | 'createSelfReviewProposal'
- | 'createSkillIfAbsent'
- | 'refreshSelfReviewProposal'
- | 'replaceSkillContentCAS'
- | 'supersedeSelfReviewProposal'
- | 'writeMemory';
-
-/** Artifact-only tools that update runtime ideas or intents without direct resource mutation. */
-export type ArtifactToolName =
- | 'recordReflectionIdea'
- | 'recordSelfFeedbackIntent'
- | 'recordSelfReviewIdea';
-
-/** Self-iteration tool names exposed to the model. */
-export type RuntimeToolName = ReadToolName | WriteToolName | ArtifactToolName;
-
-/**
- * Context accepted by the self-iteration runtime.
- */
-export interface ExecuteSelfIterationContext {
- /** Stable agent id being reviewed. */
- agentId: string;
- /** Agent document evidence serialized into the runtime prompt when available. */
- documentActivity?: unknown;
- /** User feedback evidence serialized into the runtime prompt when available. */
- feedbackActivity?: unknown;
- /** Managed skill summaries serialized into the runtime prompt when available. */
- managedSkills?: unknown;
- /** Existing proposal activity serialized into the runtime prompt when available. */
- proposalActivity?: unknown;
- /** Recent receipt evidence serialized into the runtime prompt when available. */
- receiptActivity?: unknown;
- /** Relevant memory evidence serialized into the runtime prompt when available. */
- relevantMemories?: unknown;
- /** Optional review-window end retained for nightly compatibility. */
- reviewWindowEnd?: string;
- /** Optional review-window start retained for nightly compatibility. */
- reviewWindowStart?: string;
- /** Candidate evidence from immediate self-feedback serialized into the runtime prompt when available. */
- selfFeedbackCandidates?: unknown;
- /** Derived self-review signal evidence serialized into the runtime prompt when available. */
- selfReviewSignals?: unknown;
- /** Tool activity evidence serialized into the runtime prompt when available. */
- toolActivity?: unknown;
- /** Topic activity evidence serialized into the runtime prompt when available. */
- topics?: unknown;
- /** Stable user id owning the reviewed agent. */
- userId: string;
-}
-
-/**
- * Input passed to the tool-first self-iteration AgentRuntime loop.
- */
-export interface ExecuteSelfIterationInput {
- /** Stable agent id being reviewed. */
- agentId: string;
- /** Bounded nightly review context collected before the run. */
- context: ExecuteSelfIterationContext;
- /** Maximum AgentRuntime steps allowed for the LLM/tool loop. */
- maxSteps: number;
- /**
- * Self-iteration mode for prompt and downstream trace separation.
- *
- * @default 'review'
- */
- mode?: IterationMode;
- /** Model name passed to the injected model runtime. */
- model: string;
- /** Minimal model runtime dependency used to stream chat completions. */
- modelRuntime: Pick<ModelRuntime, 'chat'>;
- /** Stable source id used for tracing and fallback idempotency keys. */
- sourceId: string;
- /** Safe read/write self-iteration tools available to this run. */
- tools: ToolSet;
- /** Stable user id owning the reviewed agent. */
- userId: string;
- /** Evidence window exposed to tools and prompts. Defaults to the review context window. */
- window?: IterationWindow;
-}
-
-/**
- * Write result captured from one supported write tool call.
- */
-export interface RuntimeWriteOutcome {
- /** Tool result returned by the safe write boundary. */
- result: ToolWriteResult;
- /** Supported write tool that produced this outcome. */
- toolName: WriteToolName;
-}
-
-/**
- * Result returned after the self-iteration AgentRuntime loop stops.
- */
-export interface ExecuteSelfIterationResult {
- /** Normalized action outcomes for downstream sink-specific projection. */
- actions: RuntimeWriteOutcome[];
- /** Concatenated assistant text streamed across LLM calls. */
- content: string;
- /** Non-actionable self-review ideas captured by the runtime. */
- ideas: SelfReviewIdea[];
- /** Immediate self-feedback intents captured by reflection/intent modes. */
- intents: SelfFeedbackIntent[];
- /** Aggregate runtime status before sink-specific projection. */
- status: ReviewRunStatus;
- /** AgentRuntime steps consumed before stopping. */
- stepCount: number;
- /** Model tool calls resolved against the self-iteration manifest. */
- toolCalls: ChatToolPayload[];
- /** Per-call model usage emitted by streaming callbacks. */
- usage: ModelUsage[];
- /** Terminal write outcomes produced by supported write tools. */
- writeOutcomes: RuntimeWriteOutcome[];
-}
-
-interface ToolExecutionResult {
- data: unknown;
- idea?: SelfReviewIdea;
- intent?: SelfFeedbackIntent;
- isWrite: boolean;
- success: boolean;
- toolName?: WriteToolName;
-}
-
-type LegacyRuntimeToolName =
- | 'closeSelfReviewProposal'
- | 'createSelfReviewProposal'
- | 'listSelfReviewProposals'
- | 'readSelfReviewProposal'
- | 'refreshSelfReviewProposal'
- | 'supersedeSelfReviewProposal';
-
-const createObjectSchema = (
- properties: Record<string, unknown>,
- required: string[] = [],
-): Record<string, unknown> => ({
- additionalProperties: false,
- properties,
- required,
- type: 'object',
-});
-
-const stringSchema = { type: 'string' };
-const stringArraySchema = { items: stringSchema, type: 'array' };
-const freeformArraySchema = { items: {}, type: 'array' };
-const freeformObjectSchema = { additionalProperties: true, type: 'object' };
-const proposalActionSchema = createObjectSchema(
- {
- actionType: {
- enum: ['create_skill', 'refine_skill', 'consolidate_skill', 'record_idea'],
- type: 'string',
- },
- applyMode: { enum: ['auto_apply', 'review_required', 'skip'], type: 'string' },
- baseSnapshot: freeformObjectSchema,
- confidence: { type: 'number' },
- dedupeKey: stringSchema,
- evidenceRefs: freeformArraySchema,
- idempotencyKey: stringSchema,
- operation: freeformObjectSchema,
- rationale: stringSchema,
- risk: { enum: ['low', 'medium', 'high'], type: 'string' },
- target: freeformObjectSchema,
- },
- ['actionType', 'rationale', 'target'],
-);
-const proposalActionsSchema = { items: proposalActionSchema, type: 'array' };
-
-const evidenceRefsSchema = freeformArraySchema;
-const ideaSchema = createObjectSchema(
- {
- evidenceRefs: evidenceRefsSchema,
- idempotencyKey: stringSchema,
- rationale: stringSchema,
- risk: { enum: ['low', 'medium', 'high'], type: 'string' },
- target: freeformObjectSchema,
- title: stringSchema,
- },
- ['idempotencyKey', 'rationale', 'evidenceRefs'],
-);
-const intentOperationSchema = freeformObjectSchema;
-const intentSchema = createObjectSchema(
- {
- actionType: stringSchema,
- confidence: { type: 'number' },
- downgradeReason: {
- enum: ['approval_required', 'low_confidence', 'unsupported_in_reflection'],
- type: 'string',
- },
- evidenceRefs: evidenceRefsSchema,
- idempotencyKey: stringSchema,
- intentType: { enum: ['memory', 'skill', 'tooling', 'workflow'], type: 'string' },
- operation: intentOperationSchema,
- rationale: stringSchema,
- risk: { enum: ['low', 'medium', 'high'], type: 'string' },
- target: freeformObjectSchema,
- title: stringSchema,
- urgency: { enum: ['immediate', 'soon', 'later'], type: 'string' },
- },
- ['idempotencyKey', 'intentType', 'confidence', 'urgency', 'rationale', 'evidenceRefs'],
-);
-
-/**
- * Tool manifest used to expose current safe read/write tools to the model.
- */
-const createToolManifest = (mode: IterationMode): LobeToolManifest => {
- const resourceTools = [
- {
- description: 'List managed skills visible in the reviewed agent scope.',
- name: 'listManagedSkills',
- parameters: createObjectSchema({}),
- },
- {
- description: 'Read one managed skill by skill document id in the reviewed agent scope.',
- name: 'getManagedSkill',
- parameters: createObjectSchema({ skillDocumentId: stringSchema }, ['skillDocumentId']),
- },
- {
- description:
- 'Read bounded evidence details for cited topic, message, tool_call, or agent_document ids in the nightly review window. Use this for evidenceRefs; do not pass evidence ids to proposal tools.',
- name: 'getEvidenceDigest',
- parameters: createObjectSchema({
- evidenceIds: stringArraySchema,
- reviewWindowEnd: stringSchema,
- reviewWindowStart: stringSchema,
- }),
- },
- {
- description:
- 'Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.',
- name: 'writeMemory',
- parameters: createObjectSchema(
- {
- content: stringSchema,
- evidenceRefs: freeformArraySchema,
- idempotencyKey: stringSchema,
- proposalKey: stringSchema,
- summary: stringSchema,
- },
- ['idempotencyKey', 'content', 'evidenceRefs'],
- ),
- },
- {
- description: 'Create one managed skill when no existing skill is selected.',
- name: 'createSkillIfAbsent',
- parameters: createObjectSchema(
- {
- bodyMarkdown: stringSchema,
- description: stringSchema,
- idempotencyKey: stringSchema,
- name: stringSchema,
- proposalKey: stringSchema,
- summary: stringSchema,
- title: stringSchema,
- },
- ['idempotencyKey', 'name', 'bodyMarkdown'],
- ),
- },
- {
- description:
- 'Replace one existing managed skill after compare-and-swap preflight. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.',
- name: 'replaceSkillContentCAS',
- parameters: createObjectSchema(
- {
- baseSnapshot: freeformObjectSchema,
- bodyMarkdown: stringSchema,
- description: stringSchema,
- idempotencyKey: stringSchema,
- proposalKey: stringSchema,
- skillDocumentId: stringSchema,
- summary: stringSchema,
- },
- ['idempotencyKey', 'skillDocumentId', 'bodyMarkdown'],
- ),
- },
- ];
-
- const reviewTools = [
- {
- description: 'List active and historical self-review proposals in the reviewed agent scope.',
- name: 'listSelfReviewProposals',
- parameters: createObjectSchema({}),
- },
- {
- description:
- 'Read one self-review proposal by proposal id or proposalKey from proposalActivity.active or listSelfReviewProposals. Never use topic, message, tool_call, or document evidence ids here.',
- name: 'readSelfReviewProposal',
- parameters: createObjectSchema({
- proposalId: stringSchema,
- proposalKey: stringSchema,
- }),
- },
- {
- description: 'Create one user-visible self-review proposal for later approval.',
- name: 'createSelfReviewProposal',
- parameters: createObjectSchema(
- {
- actions: proposalActionsSchema,
- idempotencyKey: stringSchema,
- metadata: freeformObjectSchema,
- proposalKey: stringSchema,
- summary: stringSchema,
- },
- ['idempotencyKey', 'proposalKey', 'summary', 'actions'],
- ),
- },
- {
- description: 'Refresh an existing self-review proposal after rechecking evidence.',
- name: 'refreshSelfReviewProposal',
- parameters: createObjectSchema(
- {
- idempotencyKey: stringSchema,
- proposalId: stringSchema,
- proposalKey: stringSchema,
- summary: stringSchema,
- },
- ['idempotencyKey', 'proposalId'],
- ),
- },
- {
- description: 'Supersede an existing self-review proposal with a replacement proposal key.',
- name: 'supersedeSelfReviewProposal',
- parameters: createObjectSchema(
- {
- idempotencyKey: stringSchema,
- proposalId: stringSchema,
- proposalKey: stringSchema,
- summary: stringSchema,
- supersededBy: stringSchema,
- },
- ['idempotencyKey', 'proposalId', 'supersededBy'],
- ),
- },
- {
- description: 'Close an existing self-review proposal with an optional lifecycle reason.',
- name: 'closeSelfReviewProposal',
- parameters: createObjectSchema(
- {
- idempotencyKey: stringSchema,
- proposalId: stringSchema,
- proposalKey: stringSchema,
- reason: stringSchema,
- summary: stringSchema,
- },
- ['idempotencyKey', 'proposalId'],
- ),
- },
- {
- description:
- 'Record one non-actionable self-review idea or question as a Daily Brief artifact without creating an approval proposal.',
- name: 'recordSelfReviewIdea',
- parameters: ideaSchema,
- },
- ];
-
- const reflectionTools = [
- {
- description:
- 'Record one immediate reflection idea into receipt metadata without creating a Daily Brief proposal.',
- name: 'recordReflectionIdea',
- parameters: ideaSchema,
- },
- {
- description:
- 'Record one approval-gated, structural, unsupported, or low-confidence self-feedback intent into receipt metadata for later self-review.',
- name: 'recordSelfFeedbackIntent',
- parameters: intentSchema,
- },
- ];
-
- return {
- api: [...resourceTools, ...(mode === 'review' ? reviewTools : reflectionTools)],
- identifier: selfIterationToolIdentifier,
- meta: {
- description: 'Read evidence and apply safe resource operations.',
- title: 'Agent Signal Self-Iteration',
- },
- systemRole: createAgentSignalSelfIterationToolSystemRole(mode),
- type: 'builtin',
- };
-};
-
-export const selfIterationToolManifest = createToolManifest('review');
-
-const TOOL_NAME_SEPARATOR = '____';
-const SELF_ITERATION_TOOL_ERROR_MESSAGE = 'Self-iteration tool call failed.';
-const FORCE_FINISH_EXTRA_STEPS = 4;
-
-const getIterationMode = (input: ExecuteSelfIterationInput): IterationMode =>
- input.mode ?? 'review';
-
-const getIterationWindow = (input: ExecuteSelfIterationInput): IterationWindow => ({
- end: input.window?.end ?? input.context.reviewWindowEnd ?? new Date(0).toISOString(),
- localDate: input.window?.localDate,
- start: input.window?.start ?? input.context.reviewWindowStart ?? new Date(0).toISOString(),
- timezone: input.window?.timezone,
-});
-
-const createRuntimePrompt = (input: ExecuteSelfIterationInput) =>
- createAgentSignalSelfIterationPrompt({
- agentId: input.agentId,
- context: input.context,
- mode: getIterationMode(input),
- sourceId: input.sourceId,
- userId: input.userId,
- window: getIterationWindow(input),
- });
-
-const toNullableString = (value: unknown) => (isTrimmedNonEmptyString(value) ? value : undefined);
-
-const toBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);
-
-const toRecordOrEmpty = (value: unknown) => toRecord(value) ?? {};
-
-const toUnknownArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
-
-const toStringArray = (value: unknown) =>
- Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
-
-const toEvidenceRefs = (value: unknown): EvidenceRef[] =>
- Array.isArray(value)
- ? value.flatMap((item) => {
- const record = toRecordOrEmpty(item);
- const id = toNullableString(record.id);
- const type = toNullableString(record.type);
-
- if (
- !id ||
- !(
- type === 'topic' ||
- type === 'message' ||
- type === 'operation' ||
- type === 'source' ||
- type === 'receipt' ||
- type === 'tool_call' ||
- type === 'task' ||
- type === 'agent_document' ||
- type === 'memory'
- )
- ) {
- return [];
- }
-
- return [
- {
- id,
- ...(toNullableString(record.summary)
- ? { summary: toNullableString(record.summary) }
- : {}),
- type,
- },
- ];
- })
- : [];
-
-const toRisk = (value: unknown): Risk => {
- if (value === Risk.High || value === 'high') return Risk.High;
- if (value === Risk.Low || value === 'low') return Risk.Low;
-
- return Risk.Medium;
-};
-
-const toTarget = (value: unknown): ActionTarget | undefined => {
- const record = toRecordOrEmpty(value);
- const target: ActionTarget = {
- memoryId: toNullableString(record.memoryId),
- skillDocumentId: toNullableString(record.skillDocumentId),
- skillName: toNullableString(record.skillName),
- targetReadonly: toBoolean(record.targetReadonly) ?? toBoolean(record.readonly),
- taskIds: toStringArray(record.taskIds),
- topicIds: toStringArray(record.topicIds),
- };
-
- return Object.values(target).some((item) => (Array.isArray(item) ? item.length > 0 : item))
- ? target
- : undefined;
-};
-
-const normalizeProposalActions = (value: unknown) =>
- toUnknownArray(value).map((item) => {
- const record = toRecordOrEmpty(item);
-
- return {
- ...record,
- actionType: record.actionType === 'record_idea' ? 'proposal_only' : record.actionType,
- applyMode: record.applyMode === 'review_required' ? 'proposal_only' : record.applyMode,
- };
- });
-
-const toReviewIdea = (args: Record<string, unknown>): SelfReviewIdea => ({
- evidenceRefs: toEvidenceRefs(args.evidenceRefs),
- idempotencyKey: toNullableString(args.idempotencyKey) ?? 'shared-idea',
- rationale: toNullableString(args.rationale) ?? toNullableString(args.summary) ?? 'Recorded idea.',
- risk: toRisk(args.risk),
- target: toTarget(args.target),
- title: toNullableString(args.title),
-});
-
-const toIntentType = (value: unknown): SelfFeedbackIntent['intentType'] => {
- if (value === 'memory' || value === 'skill' || value === 'tooling' || value === 'workflow') {
- return value;
- }
-
- return 'workflow';
-};
-
-const toUrgency = (value: unknown): SelfFeedbackIntent['urgency'] => {
- if (value === 'immediate' || value === 'soon' || value === 'later') return value;
-
- return 'later';
-};
-
-const toDowngradeReason = (value: unknown): SelfFeedbackIntent['downgradeReason'] => {
- if (
- value === 'approval_required' ||
- value === 'low_confidence' ||
- value === 'unsupported_in_reflection'
- ) {
- return value;
- }
-};
-
-const toSelfFeedbackIntent = (args: Record<string, unknown>): SelfFeedbackIntent => ({
- ...toReviewIdea(args),
- actionType: toNullableString(args.actionType),
- confidence: typeof args.confidence === 'number' ? args.confidence : 0.5,
- downgradeReason: toDowngradeReason(args.downgradeReason),
- intentType: toIntentType(args.intentType),
- mode: 'reflection',
- operation: toRecordOrEmpty(args.operation) as SelfFeedbackIntent['operation'],
- urgency: toUrgency(args.urgency),
-});
-
-/**
- * Normalizes model-produced tool arguments.
- *
- * Before:
- * - `"{\"name\":\"skill\"}"`
- * - `"not json"`
- *
- * After:
- * - `{ name: "skill" }`
- * - `{}`
- */
-const parseToolArguments = (value: string | undefined): Record<string, unknown> => {
- if (!value) return {};
-
- try {
- const parsed = JSON.parse(value) as unknown;
-
- return toRecordOrEmpty(parsed);
- } catch {
- return {};
- }
-};
-
-const getErrorMessage = (error: unknown) =>
- error instanceof Error ? error.message : String(error);
-
-const getApiNameFromRawToolName = (name: string) => {
- const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);
-
- return identifier === selfIterationToolIdentifier && apiName ? apiName : name;
-};
-
-const normalizeToolName = (name: string): RuntimeToolName | LegacyRuntimeToolName | string => {
- if (name === 'listSelfReviewProposals') return 'listSelfReviewProposals';
- if (name === 'readSelfReviewProposal') return 'readSelfReviewProposal';
- if (name === 'createSelfReviewProposal') return 'createSelfReviewProposal';
- if (name === 'refreshSelfReviewProposal') return 'refreshSelfReviewProposal';
- if (name === 'supersedeSelfReviewProposal') return 'supersedeSelfReviewProposal';
- if (name === 'closeSelfReviewProposal') return 'closeSelfReviewProposal';
-
- return name;
-};
-
-const resolveToolCalls = ({
- manifestMap,
- offeredToolNames,
- rawToolCalls,
- toolNameResolver,
-}: {
- manifestMap: Record<string, LobeToolManifest>;
- offeredToolNames: string[];
- rawToolCalls: MessageToolCall[];
- toolNameResolver: ToolNameResolver;
-}): ChatToolPayload[] => {
- const resolvedToolCalls = toolNameResolver.resolve(rawToolCalls, manifestMap, offeredToolNames);
- const resolvedIds = new Set(resolvedToolCalls.map((toolCall) => toolCall.id));
- const unresolvedToolCalls = rawToolCalls
- .filter((toolCall) => !resolvedIds.has(toolCall.id))
- .map(
- (toolCall): ChatToolPayload => ({
- apiName: getApiNameFromRawToolName(toolCall.function.name),
- arguments: toolCall.function.arguments,
- id: toolCall.id,
- identifier: selfIterationToolIdentifier,
- thoughtSignature: toolCall.thoughtSignature,
- type: 'builtin',
- }),
- );
-
- return [...resolvedToolCalls, ...unresolvedToolCalls];
-};
-
-const createToolError = (message: string): ToolExecutionResult => ({
- data: { error: message },
- isWrite: false,
- success: false,
-});
-
-const withUser = <TInput extends ToolWriteInput>(
- toolName: WriteToolName,
- args: Record<string, unknown>,
- input: ExecuteSelfIterationInput,
- toolCallId: string,
- fields: Omit<TInput, keyof ToolWriteInput>,
-): TInput =>
- ({
- ...fields,
- idempotencyKey:
- toNullableString(args.idempotencyKey) ?? `${input.sourceId}:${toolName}:${toolCallId}`,
- proposalKey: toNullableString(args.proposalKey),
- summary: toNullableString(args.summary),
- userId: input.userId,
- }) as TInput;
-
-const toBaseSnapshot = (value: unknown): SelfReviewProposalBaseSnapshot => {
- const record = toRecordOrEmpty(value);
-
- return {
- absent: toBoolean(record.absent),
- agentDocumentId: toNullableString(record.agentDocumentId),
- contentHash: toNullableString(record.contentHash),
- documentId: toNullableString(record.documentId),
- documentUpdatedAt: toNullableString(record.documentUpdatedAt),
- managed: toBoolean(record.managed),
- skillName: toNullableString(record.skillName),
- targetTitle: toNullableString(record.targetTitle),
- targetType: record.targetType === 'skill' ? 'skill' : undefined,
- writable: toBoolean(record.writable),
- };
-};
-
-const executeWriteTool = async (
- toolName: WriteToolName,
- operation: () => Promise<ToolWriteResult>,
-): Promise<ToolExecutionResult> => ({
- data: await operation(),
- isWrite: true,
- success: true,
- toolName,
-});
-
-const executeRuntimeTool = async (
- toolCall: ChatToolPayload,
- input: ExecuteSelfIterationInput,
-): Promise<ToolExecutionResult> => {
- const args = parseToolArguments(toolCall.arguments);
- const apiName = normalizeToolName(toolCall.apiName);
-
- if (apiName === 'listManagedSkills') {
- return {
- data: await input.tools.listManagedSkills({ agentId: input.agentId, userId: input.userId }),
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'getManagedSkill') {
- const skillDocumentId = toNullableString(args.skillDocumentId);
- if (!skillDocumentId) return createToolError('skillDocumentId is required');
-
- return {
- data: await input.tools.getManagedSkill({
- agentId: input.agentId,
- skillDocumentId,
- userId: input.userId,
- }),
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'getEvidenceDigest') {
- const window = getIterationWindow(input);
-
- return {
- data: await input.tools.getEvidenceDigest({
- agentId: input.agentId,
- evidenceIds: toStringArray(args.evidenceIds),
- reviewWindowEnd: toNullableString(args.reviewWindowEnd) ?? window.end,
- reviewWindowStart: toNullableString(args.reviewWindowStart) ?? window.start,
- userId: input.userId,
- }),
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'listSelfReviewProposals') {
- return {
- data: await input.tools.listSelfReviewProposals({
- agentId: input.agentId,
- userId: input.userId,
- }),
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'readSelfReviewProposal') {
- return {
- data: await input.tools.readSelfReviewProposal({
- proposalId: toNullableString(args.proposalId),
- proposalKey: toNullableString(args.proposalKey),
- userId: input.userId,
- }),
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'recordSelfReviewIdea' || apiName === 'recordReflectionIdea') {
- const idea = toReviewIdea(args);
-
- return {
- data: {
- idempotencyKey: idea.idempotencyKey,
- status: 'applied',
- summary: idea.title ?? idea.rationale,
- },
- idea,
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'recordSelfFeedbackIntent') {
- const intent = toSelfFeedbackIntent(args);
-
- return {
- data: {
- idempotencyKey: intent.idempotencyKey,
- status: 'applied',
- summary: intent.title ?? intent.rationale,
- },
- intent,
- isWrite: false,
- success: true,
- };
- }
-
- if (apiName === 'createSelfReviewProposal') {
- return executeWriteTool('createSelfReviewProposal', () =>
- input.tools.createSelfReviewProposal(
- withUser<CreateSelfReviewProposalInput>(
- 'createSelfReviewProposal',
- args,
- input,
- toolCall.id,
- {
- actions: normalizeProposalActions(args.actions),
- metadata: toRecordOrEmpty(args.metadata),
- },
- ),
- ),
- );
- }
-
- if (apiName === 'refreshSelfReviewProposal') {
- const proposalId = toNullableString(args.proposalId);
- if (!proposalId) return createToolError('proposalId is required');
-
- return executeWriteTool('refreshSelfReviewProposal', () =>
- input.tools.refreshSelfReviewProposal(
- withUser<RefreshSelfReviewProposalInput>(
- 'refreshSelfReviewProposal',
- args,
- input,
- toolCall.id,
- {
- proposalId,
- },
- ),
- ),
- );
- }
-
- if (apiName === 'supersedeSelfReviewProposal') {
- const proposalId = toNullableString(args.proposalId);
- const supersededBy = toNullableString(args.supersededBy);
- if (!proposalId) return createToolError('proposalId is required');
- if (!supersededBy) return createToolError('supersededBy is required');
-
- return executeWriteTool('supersedeSelfReviewProposal', () =>
- input.tools.supersedeSelfReviewProposal(
- withUser<SupersedeSelfReviewProposalInput>(
- 'supersedeSelfReviewProposal',
- args,
- input,
- toolCall.id,
- {
- proposalId,
- supersededBy,
- },
- ),
- ),
- );
- }
-
- if (apiName === 'closeSelfReviewProposal') {
- const proposalId = toNullableString(args.proposalId);
- if (!proposalId) return createToolError('proposalId is required');
-
- return executeWriteTool('closeSelfReviewProposal', () =>
- input.tools.closeSelfReviewProposal(
- withUser<CloseSelfReviewProposalInput>(
- 'closeSelfReviewProposal',
- args,
- input,
- toolCall.id,
- {
- proposalId,
- reason: toNullableString(args.reason),
- },
- ),
- ),
- );
- }
-
- if (apiName === 'writeMemory') {
- const content = toNullableString(args.content);
- if (!content) return createToolError('content is required');
-
- const evidenceRefs = toEvidenceRefs(args.evidenceRefs);
- if (evidenceRefs.length === 0) return createToolError('evidenceRefs are required');
-
- return executeWriteTool('writeMemory', () =>
- input.tools.writeMemory(
- withUser<WriteMemoryInput>('writeMemory', args, input, toolCall.id, {
- content,
- evidenceRefs,
- }),
- ),
- );
- }
-
- if (apiName === 'createSkillIfAbsent') {
- return executeWriteTool('createSkillIfAbsent', () =>
- input.tools.createSkillIfAbsent(
- withUser<CreateSkillIfAbsentInput>('createSkillIfAbsent', args, input, toolCall.id, {
- bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',
- description: toNullableString(args.description),
- name: toNullableString(args.name) ?? '',
- title: toNullableString(args.title),
- }),
- ),
- );
- }
-
- if (apiName === 'replaceSkillContentCAS') {
- const skillDocumentId = toNullableString(args.skillDocumentId);
- if (!skillDocumentId) return createToolError('skillDocumentId is required');
-
- return executeWriteTool('replaceSkillContentCAS', () =>
- input.tools.replaceSkillContentCAS(
- withUser<ReplaceSkillContentCASInput>('replaceSkillContentCAS', args, input, toolCall.id, {
- baseSnapshot: toBaseSnapshot(args.baseSnapshot),
- bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',
- description: toNullableString(args.description),
- skillDocumentId,
- }),
- ),
- );
- }
-
- return createToolError(`Unsupported self-iteration tool: ${apiName}`);
-};
-
-const createInitialState = ({
- input,
- manifestMap,
- runtimeTools,
-}: {
- input: ExecuteSelfIterationInput;
- manifestMap: Record<string, LobeToolManifest>;
- runtimeTools: ReturnType<typeof generateToolsFromManifest>;
-}): AgentState => {
- const createdAt = new Date().toISOString();
- const operationId = `agent-signal-self-iteration:${input.sourceId}`;
- const messages: ChatStreamPayload['messages'] = [
- { content: createAgentSignalSelfIterationSystemRole(), role: 'system' },
- { content: createRuntimePrompt(input), role: 'user' },
- ];
-
- return {
- cost: {
- calculatedAt: createdAt,
- currency: 'USD',
- llm: { byModel: [], currency: 'USD', total: 0 },
- tools: { byTool: [], currency: 'USD', total: 0 },
- total: 0,
- },
- createdAt,
- lastModified: createdAt,
- maxSteps: Math.max(1, input.maxSteps),
- messages,
- metadata: {
- agentId: input.agentId,
- sourceId: input.sourceId,
- trigger: RequestTrigger.AgentSignal,
- userId: input.userId,
- },
- modelRuntimeConfig: {
- model: input.model,
- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
- },
- operationId,
- operationToolSet: {
- enabledToolIds: [selfIterationToolIdentifier],
- manifestMap,
- sourceMap: { [selfIterationToolIdentifier]: 'builtin' },
- tools: runtimeTools,
- },
- status: 'idle',
- stepCount: 0,
- toolManifestMap: manifestMap,
- toolSourceMap: { [selfIterationToolIdentifier]: 'builtin' },
- tools: runtimeTools,
- usage: {
- humanInteraction: {
- approvalRequests: 0,
- promptRequests: 0,
- selectRequests: 0,
- totalWaitingTimeMs: 0,
- },
- llm: {
- apiCalls: 0,
- processingTimeMs: 0,
- tokens: { input: 0, output: 0, total: 0 },
- },
- tools: {
- byTool: [],
- totalCalls: 0,
- totalTimeMs: 0,
- },
- },
- userInterventionConfig: { approvalMode: 'headless' },
- };
-};
-
-/**
- * Runs the tool-first self-iteration agent with a bounded AgentRuntime LLM/tool loop.
- *
- * Triggering workflow:
- *
- * createAgentRunner
- * -> future server runtime backend
- * -> `agent_signal.self_iteration_agent.run`
- * -> {@link executeSelfIteration}
- *
- * Upstream:
- * - {@link createInitialState}
- *
- * Downstream:
- * - {@link executeRuntimeTool}
- *
- * Use when:
- * - Nightly self-review needs real LLM -> tool -> LLM behavior
- * - The caller already has scoped safe self-iteration tools and a model runtime
- *
- * Expects:
- * - Tools enforce their own idempotency, preflight, and receipt contracts
- * - `maxSteps` is a positive finite loop budget
- *
- * Returns:
- * - Final streamed assistant content, step count, model usage, tool calls, and write outcomes
- */
-export const executeSelfIteration = async (
- input: ExecuteSelfIterationInput,
-): Promise<ExecuteSelfIterationResult> =>
- tracer.startActiveSpan(
- 'agent_signal.self_iteration_agent.run',
- {
- attributes: {
- 'agent.signal.agent_id': input.agentId,
- 'agent.signal.self_iteration.mode': getIterationMode(input),
- 'agent.signal.self_iteration_agent.max_steps': input.maxSteps,
- 'agent.signal.source_id': input.sourceId,
- 'agent.signal.user_id': input.userId,
- },
- },
- async (runSpan) => {
- const maxSteps = Math.max(1, input.maxSteps);
- const toolNameResolver = new ToolNameResolver();
- const manifest = createToolManifest(getIterationMode(input));
- const manifestMap = {
- [selfIterationToolIdentifier]: manifest,
- };
- const runtimeTools = generateToolsFromManifest(manifest);
- const offeredToolNames = runtimeTools.map((tool) => tool.function.name);
- const contentParts: string[] = [];
- const ideas: SelfReviewIdea[] = [];
- const intents: SelfFeedbackIntent[] = [];
- const toolCalls: ChatToolPayload[] = [];
- const usage: ModelUsage[] = [];
- const writeOutcomes: RuntimeWriteOutcome[] = [];
- const runtime = new AgentRuntime(
- new GeneralChatAgent({
- compressionConfig: { enabled: false },
- modelRuntimeConfig: {
- model: input.model,
- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
- },
- operationId: `agent-signal-self-iteration:${input.sourceId}`,
- userId: input.userId,
- }),
- {
- executors: {
- call_llm: async (instruction, state) => {
- const payload = (
- instruction as { payload: { messages: ChatStreamPayload['messages'] } }
- ).payload;
- let content = '';
- let modelUsage: ModelUsage | undefined;
- let rawToolCalls: MessageToolCall[] = [];
-
- const response = await input.modelRuntime.chat(
- {
- messages: payload.messages,
- model: input.model,
- stream: true,
- tools: state.forceFinish ? [] : runtimeTools,
- },
- {
- callback: {
- onCompletion: (data) => {
- modelUsage = data.usage;
- },
- onText: (text) => {
- content += text;
- },
- onToolsCalling: ({ toolsCalling }) => {
- rawToolCalls = toolsCalling;
- },
- },
- metadata: { trigger: RequestTrigger.AgentSignal },
- },
- );
- await consumeStreamUntilDone(response);
-
- if (content) contentParts.push(content);
- if (modelUsage) usage.push(modelUsage);
-
- const assistantMessageId = `shared-assistant-${state.stepCount}`;
- const resolvedToolCalls = resolveToolCalls({
- manifestMap,
- offeredToolNames,
- rawToolCalls,
- toolNameResolver,
- });
- toolCalls.push(...resolvedToolCalls);
-
- const newState = structuredClone(state);
- newState.messages.push({
- content,
- id: assistantMessageId,
- role: 'assistant',
- ...(rawToolCalls.length > 0 ? { tool_calls: rawToolCalls } : {}),
- });
-
- return {
- events: [
- {
- result: { content, tool_calls: rawToolCalls, usage: modelUsage },
- type: 'llm_result',
- },
- ],
- newState,
- nextContext: {
- payload: {
- hasToolsCalling: resolvedToolCalls.length > 0,
- parentMessageId: assistantMessageId,
- result: { content, tool_calls: rawToolCalls },
- toolsCalling: resolvedToolCalls,
- },
- phase: 'llm_result',
- session: {
- messageCount: newState.messages.length,
- sessionId: newState.operationId,
- status: newState.status,
- stepCount: newState.stepCount,
- },
- stepUsage: modelUsage,
- } satisfies AgentRuntimeContext,
- };
- },
- call_tool: async (instruction, state) => {
- const payload = (
- instruction as {
- payload: {
- parentMessageId: string;
- toolCalling: ChatToolPayload;
- };
- }
- ).payload;
- const startedAt = Date.now();
- let execution: ToolExecutionResult;
-
- try {
- execution = await executeRuntimeTool(payload.toolCalling, input);
- } catch {
- execution = {
- data: { error: SELF_ITERATION_TOOL_ERROR_MESSAGE },
- isWrite: false,
- success: false,
- };
- }
-
- if (execution.isWrite && execution.toolName && execution.success) {
- writeOutcomes.push({
- result: execution.data as ToolWriteResult,
- toolName: execution.toolName,
- });
- }
- if (execution.idea && execution.success) ideas.push(execution.idea);
- if (execution.intent && execution.success) intents.push(execution.intent);
-
- const content = JSON.stringify(execution.data);
- const newState = structuredClone(state);
- newState.messages.push({
- content,
- role: 'tool',
- tool_call_id: payload.toolCalling.id,
- });
-
- return {
- events: [
- {
- id: payload.toolCalling.id,
- result: { content, success: execution.success },
- type: 'tool_result',
- },
- ],
- newState,
- nextContext: {
- payload: {
- data: execution.data,
- executionTime: Date.now() - startedAt,
- isSuccess: execution.success,
- parentMessageId: payload.parentMessageId,
- toolCall: payload.toolCalling,
- toolCallId: payload.toolCalling.id,
- },
- phase: 'tool_result',
- session: {
- messageCount: newState.messages.length,
- sessionId: newState.operationId,
- status: newState.status,
- stepCount: newState.stepCount,
- },
- } satisfies AgentRuntimeContext,
- };
- },
- },
- },
- );
- let state = createInitialState({ input, manifestMap, runtimeTools });
- let context: AgentRuntimeContext = {
- payload: {
- model: input.model,
- provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
- tools: runtimeTools,
- },
- phase: 'user_input',
- session: {
- messageCount: state.messages.length,
- sessionId: state.operationId,
- status: state.status,
- stepCount: state.stepCount,
- },
- };
-
- try {
- // NOTICE:
- // The public maxSteps policy lives in AgentRuntime via state.maxSteps.
- // The outer loop is only a hard safety cap so force-finish and the final
- // tool-result continuation can run after AgentRuntime crosses maxSteps.
- // Source/context: packages/agent-runtime/src/core/runtime.ts forceFinish handling.
- // Removal condition: AgentRuntime exposes a bounded run-until-done API.
- const hardSafetyStepCap = maxSteps + FORCE_FINISH_EXTRA_STEPS;
-
- for (let stepIndex = 0; stepIndex < hardSafetyStepCap; stepIndex += 1) {
- if (
- state.status === 'done' ||
- state.status === 'error' ||
- state.status === 'interrupted'
- ) {
- break;
- }
-
- const result = await tracer.startActiveSpan(
- 'agent_signal.self_iteration_agent.step',
- {
- attributes: {
- 'agent.signal.agent_id': input.agentId,
- 'agent.signal.self_iteration.mode': getIterationMode(input),
- 'agent.signal.self_iteration_agent.max_steps': maxSteps,
- 'agent.signal.self_iteration_agent.step_count': state.stepCount + 1,
- 'agent.signal.source_id': input.sourceId,
- 'agent.signal.user_id': input.userId,
- },
- },
- async (stepSpan) => {
- try {
- const stepResult = await runtime.step(state, context);
- stepSpan.setAttribute(
- 'agent.signal.self_iteration_agent.step_count',
- stepResult.newState.stepCount,
- );
-
- if (stepResult.newState.status === 'error') {
- stepSpan.setStatus({ code: SpanStatusCode.ERROR });
- } else {
- stepSpan.setStatus({ code: SpanStatusCode.OK });
- }
-
- return stepResult;
- } catch (error) {
- stepSpan.recordException(error as Error);
- stepSpan.setStatus({
- code: SpanStatusCode.ERROR,
- message: getErrorMessage(error),
- });
-
- throw error;
- } finally {
- stepSpan.end();
- }
- },
- );
-
- state = result.newState;
-
- if (!result.nextContext) break;
- context = result.nextContext;
- }
-
- runSpan.setAttribute('agent.signal.self_iteration_agent.step_count', state.stepCount);
- runSpan.setStatus({
- code: state.status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,
- });
-
- return {
- actions: writeOutcomes,
- content: contentParts.join(''),
- ideas,
- intents,
- status: state.status === 'error' ? ReviewRunStatus.Failed : ReviewRunStatus.Completed,
- stepCount: state.stepCount,
- toolCalls,
- usage,
- writeOutcomes,
- };
- } catch (error) {
- runSpan.recordException(error as Error);
- runSpan.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });
-
- throw error;
- } finally {
- runSpan.end();
- }
- },
- );
-
-/** Default step budget for one self-iteration agent run. */
-const DEFAULT_MAX_SELF_ITERATION_AGENT_STEPS = 10;
-
-/**
- * Result envelope returned by the bounded self-iteration agent runner.
- */
-export interface AgentRunResult {
- /** Executed tool or legacy executor result to persist as receipts. */
- execution: RunResult;
- /** Non-actionable ideas collected during the run. */
- ideas?: SelfReviewIdea[];
- /** Frozen deterministic plan used for Daily Brief proposal projection. */
- projectionPlan: Plan;
- /** Optional number of agent/tool steps consumed by the backend runner. */
- stepCount?: number;
-}
-
-/**
- * Input passed to a shared runner backend.
- */
-export interface AgentRunnerRunInput {
- /** Bounded digest context collected for one nightly review window. */
- context: NightlyReviewContext;
- /** User-local nightly date used in projected self-iteration plans. */
- localDate?: string;
- /** Maximum backend agent/tool steps allowed for this run. */
- maxSteps: number;
- /** Review scope attached to projected plans and tracing. */
- reviewScope: Scope;
- /** Stable source id used to generate action idempotency keys. */
- sourceId: string;
- /** Safe read/write tools available to the backend runner. */
- tools: ToolSet;
- /** Stable user id owning this run. */
- userId: string;
-}
-
-/**
- * Options for creating a bounded self-iteration agent runner.
- */
-export interface AgentRunnerOptions {
- /**
- * Maximum backend agent/tool steps.
- *
- * @default 10
- */
- maxSteps?: number;
- /** Backend implementation that may call tools and must return a projected plan. */
- run: (input: AgentRunnerRunInput) => Promise<AgentRunResult>;
- /** Safe tools exposed to the backend implementation. */
- tools: ToolSet;
-}
-
-/**
- * Input for one bounded nightly shared run.
- */
-export interface AgentRunnerInput {
- /** Bounded digest context collected for one nightly review window. */
- context: NightlyReviewContext;
- /** User-local nightly date used in projected self-iteration plans. */
- localDate?: string;
- /** Stable source id used to generate action idempotency keys. */
- sourceId: string;
- /** Stable user id owning this run. */
- userId: string;
-}
-
-const createFailedProjectionPlan = (input: AgentRunnerInput): Plan => ({
- actions: [],
- localDate: input.localDate,
- plannerVersion: 'shared-agent-runner-fallback-v1',
- reviewScope: Scope.Nightly,
- summary: 'Self-iteration review runner failed before producing a valid plan.',
-});
-
-/**
- * Creates a bounded runner for nightly self-iteration agent execution.
- *
- * Call stack:
- *
- * createNightlyReviewSourceHandler
- * -> {@link createAgentRunner}
- * -> injected `run`
- * -> safe self-iteration tools
- *
- * Use when:
- * - Nightly self-review should execute through one bounded runner boundary
- * - Tests need to verify fallback and source-id normalization without DB or LLMs
- *
- * Expects:
- * - `sourceId` is stable for idempotency
- * - The backend `run` returns both execution output and the frozen projection plan
- *
- * Returns:
- * - A runner that traces the run, injects tools, enforces the configured step budget, and
- * returns a conservative failed result if the backend cannot produce a result
- */
-export const createAgentRunner = (options: AgentRunnerOptions) => {
- const maxSteps = Math.max(1, options.maxSteps ?? DEFAULT_MAX_SELF_ITERATION_AGENT_STEPS);
-
- return {
- run: async (input: AgentRunnerInput): Promise<AgentRunResult> =>
- tracer.startActiveSpan(
- 'agent_signal.self_iteration_agent.runner.run',
- {
- attributes: {
- 'agent.signal.agent_id': input.context.agentId,
- 'agent.signal.review_scope': Scope.Nightly,
- 'agent.signal.self_iteration_agent.max_steps': maxSteps,
- 'agent.signal.source_id': input.sourceId,
- 'agent.signal.user_id': input.userId,
- },
- },
- async (span) => {
- try {
- const result = await options.run({
- ...input,
- maxSteps,
- reviewScope: Scope.Nightly,
- tools: options.tools,
- });
- const execution = {
- ...result.execution,
- sourceId: result.execution.sourceId ?? input.sourceId,
- };
-
- span.setAttribute(
- 'agent.signal.self_iteration_agent.plan_action_count',
- result.projectionPlan.actions.length,
- );
- span.setAttribute(
- 'agent.signal.self_iteration_agent.execution_action_count',
- execution.actions.length,
- );
- if (typeof result.stepCount === 'number') {
- span.setAttribute('agent.signal.self_iteration_agent.step_count', result.stepCount);
- }
- span.setStatus({ code: SpanStatusCode.OK });
-
- return {
- ...result,
- execution,
- };
- } catch (error) {
- span.setStatus({
- code: SpanStatusCode.ERROR,
- message:
- error instanceof Error
- ? error.message
- : 'AgentSignal self-iteration agent runner failed',
- });
- span.recordException(error as Error);
-
- return {
- execution: {
- actions: [],
- sourceId: input.sourceId,
- status: ReviewRunStatus.Failed,
- },
- projectionPlan: createFailedProjectionPlan(input),
- stepCount: maxSteps,
- };
- } finally {
- span.end();
- }
- },
- ),
- };
-};
diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.ts b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.ts
index a5e3b610ee7..8ea206fc9ad 100644
--- a/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/handler.test.ts
@@ -2,6 +2,7 @@
import { createSource } from '@lobechat/agent-signal';
import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { describe, expect, it, vi } from 'vitest';
import { createDefaultAgentSignalPolicies } from '../../../../policies';
@@ -11,7 +12,6 @@ import type {
AgentSignalSignalHandlerDefinition,
AgentSignalSourceHandlerDefinition,
} from '../../../../runtime/middleware';
-import type { ExecuteSelfIterationResult } from '../../execute';
import type { EvidenceRef } from '../../types';
import { ReviewRunStatus } from '../../types';
import type { CreateSelfFeedbackIntentSourceHandlerDependencies } from '../handler';
@@ -47,61 +47,6 @@ const topicEvidence = {
type: 'topic',
} satisfies EvidenceRef;
-const runtimeResult = {
- actions: [
- {
- result: {
- receiptId: 'runtime-memory-receipt',
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Memory written.',
- },
- toolName: 'writeMemory',
- },
- ],
- content: 'Runtime intent wrote one memory.',
- ideas: [],
- intents: [
- {
- confidence: 0.94,
- evidenceRefs: [intentPayload.evidenceRefs[0]],
- idempotencyKey: `${intentSourceId}:intent:memory`,
- intentType: 'memory',
- mode: 'reflection',
- rationale: 'The user gave a durable preference.',
- risk: 'low',
- urgency: 'immediate',
- },
- ],
- status: ReviewRunStatus.Completed,
- stepCount: 2,
- toolCalls: [
- {
- apiName: 'writeMemory',
- arguments: JSON.stringify({
- content: 'User prefers concise release summaries.',
- evidenceRefs: [intentPayload.evidenceRefs[0]],
- idempotencyKey: `${intentSourceId}:writeMemory:tool-call-1`,
- }),
- id: 'tool-call-1',
- identifier: 'agent-signal-self-iteration',
- type: 'builtin',
- },
- ],
- usage: [],
- writeOutcomes: [
- {
- result: {
- receiptId: 'runtime-memory-receipt',
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Memory written.',
- },
- toolName: 'writeMemory',
- },
- ],
-} satisfies ExecuteSelfIterationResult;
-
const runtimeContext = {
now: () => 100,
runtimeState: {
@@ -130,25 +75,18 @@ const createDependencies = (
): CreateSelfFeedbackIntentSourceHandlerDependencies => ({
acquireReviewGuard: vi.fn(async () => true),
canRunReview: vi.fn(async () => true),
+ db: {} as never,
+ dispatch: vi.fn(async () => ({ operationId: 'op-self-iter-1', topicId: 'topic-1' })),
enrichEvidence: vi.fn(async () => ({
evidenceRefs: [topicEvidence],
})),
- executeSelfIteration: vi.fn(async () => runtimeResult),
maxSteps: 3,
- model: 'gpt-test',
- modelRuntime: { chat: vi.fn() },
- tools: {} as never,
- writeReceipt: vi.fn(async () => {}),
...overrides,
});
describe('self-feedback intent source handler', () => {
- /**
- * @example
- * expect(deps.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'feedback' }));
- */
- it('runs self-iteration executor for declared intent and records intent metadata on receipts', async () => {
- const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });
+ it('enriches evidence then dispatches an async run under the builtin self-feedback-intent slug', async () => {
+ const deps = createDependencies();
const handler = createSelfFeedbackIntentSourceHandler(deps);
const result = await handler.handle(createIntentSource());
@@ -157,99 +95,47 @@ describe('self-feedback intent source handler', () => {
action: 'write',
agentId: 'agent-1',
kind: 'memory',
- operationId: undefined,
scopeId: 'topic-1',
scopeType: 'topic',
toolCallId: 'tool-call-1',
topicId: 'topic-1',
userId: 'user-1',
});
- expect(deps.executeSelfIteration).toHaveBeenCalledWith(
+ expect(deps.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'agent-1',
- context: expect.objectContaining({
- evidenceRefs: [intentPayload.evidenceRefs[0], topicEvidence],
- intent: expect.objectContaining({ summary: intentPayload.summary }),
+ db: deps.db,
+ marker: {
+ agentId: 'agent-1',
+ kind: 'self-feedback-intent',
sourceId: intentSourceId,
- }),
+ topicId: 'topic-1',
+ },
maxSteps: 3,
- mode: 'feedback',
- sourceId: intentSourceId,
+ // The intent + enrichment evidence is rendered into the prompt.
+ prompt: expect.stringContaining(intentSourceId),
+ slug: BUILTIN_AGENT_SLUGS.selfFeedbackIntent,
+ topicId: 'topic-1',
userId: 'user-1',
}),
);
- expect(deps.writeReceipts).toHaveBeenCalledWith([
- expect.objectContaining({
- id: `${intentSourceId}:review-summary`,
- metadata: expect.objectContaining({
- selfIteration: expect.objectContaining({
- intents: runtimeResult.intents,
- mode: 'feedback',
- sourceId: intentSourceId,
- toolCallId: 'tool-call-1',
- }),
- }),
- }),
- expect.objectContaining({ id: `${intentSourceId}:writeMemory:tool-call-1:action` }),
- ]);
- expect(result).toEqual(
- expect.objectContaining({
- plannedActionCount: 1,
- planSummary: 'Runtime intent wrote one memory.',
- status: ReviewRunStatus.Completed,
- }),
- );
- });
-
- /**
- * @example
- * expect(runtimeFactory.createRuntime).toHaveBeenCalledWith(expect.objectContaining({ enrichment }));
- */
- it('builds self-iteration executor dependencies through the per-source runtime factory', async () => {
- const executeSelfIteration = vi.fn(async () => runtimeResult);
- const modelRuntime = { chat: vi.fn() };
- const tools = {} as never;
- const runtimeFactory = {
- createRuntime: vi.fn(async () => ({
- executeSelfIteration,
- maxSteps: 4,
- model: 'gpt-factory',
- modelRuntime,
- tools,
- })),
- };
- const deps = createDependencies({
- executeSelfIteration: undefined,
- model: undefined,
- modelRuntime: undefined,
- runtimeFactory,
- tools: undefined,
- writeReceipts: vi.fn(async () => {}),
- });
- const handler = createSelfFeedbackIntentSourceHandler(deps);
-
- await handler.handle(createIntentSource());
+ // The combined evidence (declared + enrichment) rides in the prompt JSON.
+ const dispatchArg = (deps.dispatch as ReturnType<typeof vi.fn>).mock.calls[0][0];
+ expect(dispatchArg.prompt).toContain('topic-1');
+ expect(dispatchArg.prompt).toContain('msg-1');
- expect(runtimeFactory.createRuntime).toHaveBeenCalledWith({
- enrichment: { evidenceRefs: [topicEvidence] },
- payload: expect.objectContaining(intentPayload),
- source: expect.objectContaining({ sourceId: intentSourceId }),
- });
- expect(executeSelfIteration).toHaveBeenCalledWith(
+ expect(result).toEqual(
expect.objectContaining({
- maxSteps: 4,
- model: 'gpt-factory',
- modelRuntime,
- mode: 'feedback',
- tools,
+ agentId: 'agent-1',
+ operationId: 'op-self-iter-1',
+ sourceId: intentSourceId,
+ status: ReviewRunStatus.Dispatched,
+ toolCallId: 'tool-call-1',
+ userId: 'user-1',
}),
);
});
- /**
- * @example
- * await handler.handle(operationSource);
- */
it('validates operation-scoped source ids and forwards operation context', async () => {
const deps = createDependencies();
const handler = createSelfFeedbackIntentSourceHandler(deps);
@@ -274,49 +160,14 @@ describe('self-feedback intent source handler', () => {
topicId: 'topic-1',
}),
);
- expect(deps.executeSelfIteration).toHaveBeenCalledWith(
- expect.objectContaining({
- context: expect.objectContaining({
- sourceId: operationSourceId,
- }),
- sourceId: operationSourceId,
- }),
- );
- });
-
- /**
- * @example
- * expect(deps.writeReceipt).toHaveBeenCalledTimes(1);
- */
- it('keeps completed runs completed when receipt writing fails', async () => {
- const receiptError = new Error('receipt store unavailable');
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- const deps = createDependencies({
- writeReceipt: vi.fn(async () => {
- throw receiptError;
- }),
- });
- const handler = createSelfFeedbackIntentSourceHandler(deps);
-
- const result = await handler.handle(createIntentSource());
-
- expect(result).toEqual(
+ expect(deps.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
- execution: expect.objectContaining({ status: ReviewRunStatus.Completed }),
- status: ReviewRunStatus.Completed,
+ marker: expect.objectContaining({ sourceId: operationSourceId }),
+ prompt: expect.stringContaining(operationSourceId),
}),
);
- expect(consoleError).toHaveBeenCalledWith(
- '[AgentSignal] Failed to write self-feedback intent receipt:',
- receiptError,
- );
- consoleError.mockRestore();
});
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
it('requires the service-emitted tool call id for stable source verification', async () => {
const deps = createDependencies();
const handler = createSelfFeedbackIntentSourceHandler(deps);
@@ -335,14 +186,10 @@ describe('self-feedback intent source handler', () => {
}),
);
expect(deps.canRunReview).not.toHaveBeenCalled();
- expect(deps.executeSelfIteration).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.status).toBe('skipped');
- */
- it('skips without enrichment or execution when the review gate is disabled', async () => {
+ it('skips without enrichment or dispatch when the review gate is disabled', async () => {
const deps = createDependencies({
canRunReview: vi.fn(async () => false),
});
@@ -358,14 +205,10 @@ describe('self-feedback intent source handler', () => {
);
expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
expect(deps.enrichEvidence).not.toHaveBeenCalled();
- expect(deps.executeSelfIteration).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.status).toBe('deduped');
- */
- it('dedupes without enrichment or execution when the declaration guard already exists', async () => {
+ it('dedupes without enrichment or dispatch when the declaration guard already exists', async () => {
const deps = createDependencies({
acquireReviewGuard: vi.fn(async () => false),
});
@@ -380,13 +223,9 @@ describe('self-feedback intent source handler', () => {
}),
);
expect(deps.enrichEvidence).not.toHaveBeenCalled();
- expect(deps.executeSelfIteration).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
it('returns skipped invalid when source id does not match the expected declaration key', async () => {
const deps = createDependencies();
const handler = createSelfFeedbackIntentSourceHandler(deps);
@@ -403,13 +242,9 @@ describe('self-feedback intent source handler', () => {
}),
);
expect(deps.canRunReview).not.toHaveBeenCalled();
- expect(deps.executeSelfIteration).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(sourceHandlers[0].listen).toBe('agent.self_feedback_intent.declared');
- */
it('installs an optional self-feedback intent source policy through default policy composition', async () => {
const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];
const deps = createDependencies();
@@ -459,7 +294,7 @@ describe('self-feedback intent source handler', () => {
expect(runtimeResult).toEqual(
expect.objectContaining({
- concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),
+ concluded: expect.objectContaining({ status: ReviewRunStatus.Dispatched }),
status: 'conclude',
}),
);
@@ -467,10 +302,6 @@ describe('self-feedback intent source handler', () => {
});
describe('self-feedback intent source policy handler', () => {
- /**
- * @example
- * expect(handler.listen).toBe('agent.self_feedback_intent.declared');
- */
it('listens to the self-feedback intent declared source type', () => {
const handler = createSelfFeedbackIntentSourcePolicyHandler(createDependencies());
diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.ts b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.ts
index dd924a25557..a4cdf603afa 100644
--- a/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/feedback/__test__/server.test.ts
@@ -1,171 +1,80 @@
// @vitest-environment node
-import { createSource } from '@lobechat/agent-signal';
-import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';
-import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import type { LobeChatDatabase } from '@/database/type';
-import type * as ExecuteModule from '../../execute';
-import { ActionStatus, ReviewRunStatus } from '../../types';
-import { createSelfFeedbackIntentSourceHandler } from '../handler';
+import type { SelfFeedbackIntentSourceGuardInput } from '../handler';
import { createServerSelfFeedbackIntentPolicyOptions } from '../server';
-const mocks = vi.hoisted(() => ({
- executeSelfIteration: vi.fn(),
- initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),
- persistAgentSignalReceipts: vi.fn(async () => {}),
- redisTryDedupe: vi.fn(async () => true),
-}));
-
-vi.mock('@/server/modules/ModelRuntime', () => ({
- initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
-}));
-
-vi.mock('@/database/models/agentSignal/reviewContext', () => ({
- AgentSignalReviewContextModel: class {
- canAgentRunSelfIteration = vi.fn(async () => true);
- },
-}));
-
-vi.mock('@/server/services/agentSignal/store/adapters/redis/sourceEventStore', () => ({
- redisSourceEventStore: {
- readWindow: vi.fn(async () => undefined),
- tryDedupe: mocks.redisTryDedupe,
- writeWindow: vi.fn(async () => undefined),
- },
-}));
-
-vi.mock('../../../receiptService', () => ({
- createSelfFeedbackReceipts: vi.fn(({ plan, result, selfIteration, sourceId }) => [
- {
- agentId: 'agent-1',
- detail: plan.summary,
- id: `${sourceId}:review-summary`,
- kind: 'review',
- metadata: { selfIteration },
- sourceId,
- status: result.status,
- title: plan.summary,
- userId: 'user-1',
- },
- ]),
- persistAgentSignalReceipts: mocks.persistAgentSignalReceipts,
-}));
-
-vi.mock('../../execute', async (importOriginal) => ({
- ...(await importOriginal<typeof ExecuteModule>()),
- executeSelfIteration: mocks.executeSelfIteration,
-}));
-
-const intentPayload = {
+const baseGuardInput: SelfFeedbackIntentSourceGuardInput = {
action: 'write',
agentId: 'agent-1',
- confidence: 0.94,
- evidenceRefs: [{ id: 'msg-1', summary: 'Remember concise release summaries.', type: 'message' }],
+ confidence: 0.9,
+ evidenceRefs: [],
+ guardKey: 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1',
kind: 'memory',
- reason: 'The user gave a durable preference.',
- summary: 'User prefers concise release summaries.',
+ reason: 'durable preference',
+ scopeId: 'topic-1',
+ scopeType: 'topic',
+ sourceId: 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1',
+ summary: 'concise summaries',
toolCallId: 'tool-call-1',
topicId: 'topic-1',
userId: 'user-1',
-} as const;
-
-const intentSourceId = 'self-feedback-intent:user-1:agent-1:topic:topic-1:tool-call-1';
-
-const createIntentSource = (): SourceAgentSelfFeedbackIntentDeclared =>
- createSource({
- payload: intentPayload,
- scope: { agentId: 'agent-1', userId: 'user-1' },
- scopeKey: 'topic:topic-1',
- sourceId: intentSourceId,
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,
- timestamp: 100,
- }) as SourceAgentSelfFeedbackIntentDeclared;
+};
describe('createServerSelfFeedbackIntentPolicyOptions', () => {
- /**
- * @example
- * expect(mocks.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'feedback' }));
- * expect(mocks.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'feedback' }));
- */
- it('runs declared intent through the self-iteration executor', async () => {
- mocks.executeSelfIteration.mockResolvedValue({
- actions: [
- {
- result: {
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Memory written.',
- },
- toolName: 'writeMemory',
- },
- ],
- content: 'Runtime intent wrote one memory.',
- ideas: [],
- intents: [],
- status: ReviewRunStatus.Completed,
- stepCount: 1,
- toolCalls: [],
- usage: [],
- writeOutcomes: [
- {
- result: {
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Memory written.',
- },
- toolName: 'writeMemory',
- },
- ],
+ it('exposes dispatch-shaped handler deps (gate, guard, enricher, db) without legacy runtime/receipt wiring', () => {
+ const options = createServerSelfFeedbackIntentPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
});
+ expect(options.acquireReviewGuard).toEqual(expect.any(Function));
+ expect(options.canRunReview).toEqual(expect.any(Function));
+ expect(options.enrichEvidence).toEqual(expect.any(Function));
+ expect(options.db).toBeDefined();
+ expect('runtimeFactory' in options).toBe(false);
+ expect('executeSelfIteration' in options).toBe(false);
+ expect('writeReceipt' in options).toBe(false);
+ expect('writeReceipts' in options).toBe(false);
+ });
+
+ it('enriches with the scope evidence ref so it rides in the run prompt', async () => {
const options = createServerSelfFeedbackIntentPolicyOptions({
agentId: 'agent-1',
db: {} as unknown as LobeChatDatabase,
selfIterationEnabled: true,
userId: 'user-1',
});
- const handler = createSelfFeedbackIntentSourceHandler(options);
- const result = await handler.handle(createIntentSource());
- expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledTimes(1);
- expect(mocks.executeSelfIteration).toHaveBeenCalledWith(
- expect.objectContaining({
+ await expect(
+ options.enrichEvidence?.({
+ action: 'write',
agentId: 'agent-1',
- mode: 'feedback',
- sourceId: intentSourceId,
+ kind: 'memory',
+ scopeId: 'topic-1',
+ scopeType: 'topic',
+ toolCallId: 'tool-call-1',
+ topicId: 'topic-1',
userId: 'user-1',
}),
- );
- expect(mocks.executeSelfIteration.mock.calls[0]?.[0].tools).toEqual(
- expect.objectContaining({
- getEvidenceDigest: expect.any(Function),
- writeMemory: expect.any(Function),
- }),
- );
- expect(mocks.persistAgentSignalReceipts).toHaveBeenCalledWith([
- expect.objectContaining({
- id: `${intentSourceId}:review-summary`,
- metadata: expect.objectContaining({
- selfIteration: expect.objectContaining({
- mode: 'feedback',
- sourceId: intentSourceId,
- }),
- }),
- }),
- ]);
- expect(result).toEqual(
- expect.objectContaining({
- plannedActionCount: 1,
- status: ReviewRunStatus.Completed,
- }),
- );
- expect(result.execution?.actions[0]).toEqual(
- expect.objectContaining({
- resourceId: 'memory-1',
- status: ActionStatus.Applied,
- }),
- );
+ ).resolves.toEqual({ evidenceRefs: [{ id: 'topic-1', type: 'topic' }] });
+ });
+
+ it('rejects declarations whose payload user id does not match the policy owner', async () => {
+ const options = createServerSelfFeedbackIntentPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
+ });
+
+ // userId mismatch short-circuits before any DB access.
+ await expect(
+ options.canRunReview({ ...baseGuardInput, userId: 'user-2' }),
+ ).resolves.toBe(false);
});
});
diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts b/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts
index 16cdacbb637..1ba04a2d12a 100644
--- a/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts
+++ b/src/server/services/agentSignal/services/selfIteration/feedback/handler.ts
@@ -1,16 +1,15 @@
import type { SourceAgentSelfFeedbackIntentDeclared } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import type { ModelRuntime } from '@lobechat/model-runtime';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { createAgentSignalSelfIterationPrompt } from '@lobechat/prompts';
import { isNonEmptyString } from '@lobechat/utils';
+import type { LobeChatDatabase } from '@/database/type';
+
import { defineSourceHandler } from '../../../runtime/middleware';
-import type { AgentSignalReceipt } from '../../receiptService';
-import { createSelfFeedbackReceipts } from '../../receiptService';
-import type { ExecuteSelfIterationInput, ExecuteSelfIterationResult } from '../execute';
-import { projectRun } from '../projection';
-import type { ToolSet } from '../tools/shared';
-import type { EvidenceRef, Idea, Plan, RunResult, SelfFeedbackIntent } from '../types';
-import { buildSelfFeedbackIntentSourceId, ReviewRunStatus, Scope } from '../types';
+import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';
+import type { EvidenceRef } from '../types';
+import { buildSelfFeedbackIntentSourceId, ReviewRunStatus } from '../types';
/** Source scope supported by self-feedback intent declarations. */
export type SelfFeedbackIntentSourceScopeType = 'operation' | 'topic';
@@ -106,85 +105,17 @@ export interface SelfFeedbackIntentEvidenceEnrichment {
hasUserInstructionConflict?: boolean;
}
-/**
- * Per-run runtime dependencies for the self-iteration executor.
- */
-export interface SelfFeedbackIntentRuntimeConfig {
- /** Runs the self-iteration executor. */
- executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;
- /**
- * Maximum self-iteration runtime steps.
- *
- * @default 10
- */
- maxSteps?: number;
- /** Model name used by the self-iteration runtime. */
- model: string;
- /** Model runtime used by the self-iteration runtime. */
- modelRuntime: Pick<ModelRuntime, 'chat'>;
- /** Source-scoped safe tools exposed to the self-iteration runtime. */
- tools: ToolSet;
-}
-
-/**
- * Input used to create source-scoped runtime dependencies for declared intent handling.
- */
-export interface SelfFeedbackIntentRuntimeFactoryInput {
- /** Evidence enrichment already collected for this declaration source. */
- enrichment: SelfFeedbackIntentEvidenceEnrichment;
- /** Validated declaration payload. */
- payload: SelfFeedbackIntentSourcePayload;
- /** Source event that triggered the handler. */
- source: SourceAgentSelfFeedbackIntentDeclared;
-}
-
-/**
- * Class-backed boundary that creates source-scoped runtime dependencies.
- */
-export interface SelfFeedbackIntentRuntimeFactory {
- /** Builds the model/runtime/tools bundle for one declared intent source. */
- createRuntime: (
- input: SelfFeedbackIntentRuntimeFactoryInput,
- ) => Promise<SelfFeedbackIntentRuntimeConfig> | SelfFeedbackIntentRuntimeConfig;
-}
-
-/**
- * Receipt input emitted after one self-feedback execution.
- */
-export interface SelfFeedbackIntentReceiptInput {
- /** Executor result for the completed declaration run. */
- execution: RunResult;
- /** Non-actionable ideas captured by the self-iteration runtime. */
- ideas?: Idea[];
- /** Immediate intents captured by the self-iteration runtime. */
- intents?: SelfFeedbackIntent[];
- /** Normalized self-iteration plan sent to the executor. */
- plan: Plan;
- /** Runtime scope id reviewed by the run. */
- scopeId: string;
- /** Runtime scope family reviewed by the run. */
- scopeType: SelfFeedbackIntentSourceScopeType;
- /** Source id that triggered the run. */
- sourceId: string;
- /** Tool-call id that produced the declaration. */
- toolCallId: string;
-}
-
/**
* Result returned by the self-feedback intent source handler.
*/
export interface SelfFeedbackIntentSourceHandlerResult extends Record<string, unknown> {
/** Stable agent id being reviewed when payload validation succeeds. */
agentId?: string;
- /** Executor result for completed runs. */
- execution?: RunResult;
/** Stable guard key used for idempotency when payload validation succeeds. */
guardKey?: string;
- /** Number of planned self-review actions before execution. */
- plannedActionCount?: number;
- /** Planner summary for receipt construction. */
- planSummary?: string;
- /** Machine-readable skip reason for non-completed runs. */
+ /** Operation id of the enqueued background self-iteration run, when dispatched. */
+ operationId?: string;
+ /** Machine-readable skip reason for non-dispatched runs. */
reason?: 'gate_disabled' | 'invalid_payload';
/** Runtime scope id reviewed by the run. */
scopeId?: string;
@@ -208,30 +139,20 @@ export interface CreateSelfFeedbackIntentSourceHandlerDependencies {
acquireReviewGuard: (input: SelfFeedbackIntentSourceGuardInput) => Promise<boolean>;
/** Re-checks runtime gates before doing reviewer work. */
canRunReview: (input: SelfFeedbackIntentSourceGuardInput) => Promise<boolean>;
+ /** Postgres handle used by the dispatch helper to enqueue the execAgent run. */
+ db: LobeChatDatabase;
+ /** Enqueues the async self-iteration run. Overridable for tests. */
+ dispatch?: typeof enqueueSelfIterationRun;
/** Adds topic or operation evidence without mutating shared resources. */
enrichEvidence?: (
input: EnrichSelfFeedbackIntentEvidenceInput,
) => Promise<SelfFeedbackIntentEvidenceEnrichment>;
- /** Runs the self-iteration runtime when no source-scoped factory is injected. */
- executeSelfIteration?: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;
/**
* Maximum self-iteration runtime steps.
*
- * @default 10
+ * @default builtin agent default
*/
maxSteps?: number;
- /** Model name used by the self-iteration runtime. */
- model?: string;
- /** Model runtime used by the self-iteration runtime. */
- modelRuntime?: Pick<ModelRuntime, 'chat'>;
- /** Builds source-scoped shared-runtime dependencies for intent mode. */
- runtimeFactory?: SelfFeedbackIntentRuntimeFactory;
- /** Safe tools exposed to the self-iteration runtime. */
- tools?: ToolSet;
- /** Writes durable receipt metadata for the declaration run. */
- writeReceipt: (input: SelfFeedbackIntentReceiptInput) => Promise<void>;
- /** Writes durable receipt records for the review summary and action outcomes. */
- writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;
}
const isValidConfidence = (value: unknown): value is number =>
@@ -369,61 +290,11 @@ const toBaseResult = (
userId: guardInput.userId,
});
-const writeSelfFeedbackIntentReceipt = async (
- deps: CreateSelfFeedbackIntentSourceHandlerDependencies,
- input: SelfFeedbackIntentReceiptInput,
-) => {
- try {
- await deps.writeReceipt(input);
- } catch (error) {
- console.error('[AgentSignal] Failed to write self-feedback intent receipt:', error);
- }
-};
-
-const writeSelfFeedbackIntentReceipts = async (
- deps: CreateSelfFeedbackIntentSourceHandlerDependencies,
- receipts: AgentSignalReceipt[],
-) => {
- if (!deps.writeReceipts || receipts.length === 0) return;
-
- try {
- await deps.writeReceipts(receipts);
- } catch (error) {
- console.error('[AgentSignal] Failed to write self-feedback intent receipts:', error);
- }
-};
-
-const applyReceiptIdsToExecution = (
- execution: RunResult,
- receipts: AgentSignalReceipt[],
-): RunResult => {
- const receiptByActionKey = new Map(
- receipts
- .filter((receipt) => receipt.id.endsWith(':action'))
- .map((receipt) => [receipt.id.slice(0, -':action'.length), receipt.id]),
- );
-
- return {
- ...execution,
- actions: execution.actions.map((action) => ({
- ...action,
- ...(receiptByActionKey.get(action.idempotencyKey)
- ? { receiptId: receiptByActionKey.get(action.idempotencyKey) }
- : {}),
- })),
- summaryReceiptId: `${execution.sourceId ?? receipts[0]?.sourceId}:review-summary`,
- };
-};
-
-const canExecuteSharedSelfIteration = (
- deps: CreateSelfFeedbackIntentSourceHandlerDependencies,
-): deps is CreateSelfFeedbackIntentSourceHandlerDependencies & {
- executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;
- model: string;
- modelRuntime: Pick<ModelRuntime, 'chat'>;
- tools: ToolSet;
-} => Boolean(deps.executeSelfIteration && deps.model && deps.modelRuntime && deps.tools);
-
+/**
+ * Builds the bounded self-iteration context embedded in the run prompt. Combines
+ * the declared intent with any enrichment evidence, mirroring the old in-runtime
+ * context — the builtin agent reads it from the prompt (no run-time collector).
+ */
const createIntentRuntimeContext = ({
enrichment,
payload,
@@ -440,82 +311,6 @@ const createIntentRuntimeContext = ({
userId: payload.userId,
});
-const runSharedSelfFeedbackIntent = async ({
- deps,
- enrichment,
- payload,
- runtime,
- source,
-}: {
- deps: CreateSelfFeedbackIntentSourceHandlerDependencies;
- enrichment: SelfFeedbackIntentEvidenceEnrichment;
- payload: SelfFeedbackIntentSourcePayload;
- runtime: SelfFeedbackIntentRuntimeConfig;
- source: SourceAgentSelfFeedbackIntentDeclared;
-}) => {
- const timestamp = new Date(source.timestamp).toISOString();
- const runtimeResult = await runtime.executeSelfIteration({
- agentId: payload.agentId,
- context: createIntentRuntimeContext({ enrichment, payload, sourceId: source.sourceId }),
- maxSteps: runtime.maxSteps ?? deps.maxSteps ?? 10,
- mode: 'feedback',
- model: runtime.model,
- modelRuntime: runtime.modelRuntime,
- sourceId: source.sourceId,
- tools: runtime.tools,
- userId: payload.userId,
- window: {
- end: timestamp,
- start: timestamp,
- },
- });
- const projected = projectRun({
- content: runtimeResult.content,
- outcomes: runtimeResult.writeOutcomes.map((outcome) => ({
- ...outcome.result,
- toolName: outcome.toolName,
- })),
- reviewScope: Scope.SelfFeedback,
- sourceId: source.sourceId,
- toolCalls: runtimeResult.toolCalls,
- userId: payload.userId,
- });
-
- return {
- execution: projected.execution,
- ideas: runtimeResult.ideas,
- plan: projected.projectionPlan,
- runtimeIntents: runtimeResult.intents,
- window: { end: timestamp, start: timestamp },
- };
-};
-
-const resolveSharedSelfFeedbackIntentRuntime = async ({
- deps,
- enrichment,
- payload,
- source,
-}: {
- deps: CreateSelfFeedbackIntentSourceHandlerDependencies;
- enrichment: SelfFeedbackIntentEvidenceEnrichment;
- payload: SelfFeedbackIntentSourcePayload;
- source: SourceAgentSelfFeedbackIntentDeclared;
-}): Promise<SelfFeedbackIntentRuntimeConfig | undefined> => {
- if (deps.runtimeFactory) {
- return deps.runtimeFactory.createRuntime({ enrichment, payload, source });
- }
-
- if (!canExecuteSharedSelfIteration(deps)) return;
-
- return {
- executeSelfIteration: deps.executeSelfIteration,
- maxSteps: deps.maxSteps,
- model: deps.model,
- modelRuntime: deps.modelRuntime,
- tools: deps.tools,
- };
-};
-
/**
* Creates the DI-friendly handler for self-feedback intent declaration sources.
*
@@ -525,23 +320,18 @@ const resolveSharedSelfFeedbackIntentRuntime = async ({
* -> `agent.self_feedback_intent.declared`
* -> {@link createSelfFeedbackIntentSourceHandler}
*
- * Upstream:
- * - `agent.self_feedback_intent.declared`
- *
- * Downstream:
- * - injected self-iteration executor
- * - injected `writeReceipt`
- *
- * Use when:
- * - Tests need to run declared-intent orchestration without DB or LLM dependencies
- * - Runtime policy composition needs a side-effect boundary before executing self-iteration plans
+ * The handler validates the declaration, re-checks gates + idempotency, enriches
+ * bounded evidence, then enqueues an async `execAgent` run under the builtin
+ * `self-feedback-intent` agent. Receipts are projected by the completion path —
+ * this handler does not run the model or write receipts inline.
*
* Expects:
* - `source` is an `agent.self_feedback_intent.declared` source with service-produced payload
- * - Dependencies enforce gates, idempotency, executor persistence, and receipts
+ * - Dependencies enforce gates, idempotency, and provide a db handle for dispatch
*
* Returns:
- * - A run result with status and enough plan metadata for self-feedback intent receipts
+ * - A run result with `Dispatched` status + the enqueued operation id, or a
+ * `Skipped` / `Deduped` status when gates / idempotency reject the run
*/
export const createSelfFeedbackIntentSourceHandler = (
deps: CreateSelfFeedbackIntentSourceHandlerDependencies,
@@ -588,76 +378,38 @@ export const createSelfFeedbackIntentSourceHandler = (
const enrichment = (await deps.enrichEvidence?.(toEnrichEvidenceInput(payload))) ?? {
evidenceRefs: [],
};
- const runtime = await resolveSharedSelfFeedbackIntentRuntime({
- deps,
- enrichment,
- payload,
- source,
- });
- if (!runtime) throw new Error('Self-iteration intent self-iteration runtime is required.');
-
- const runtimeRun = await runSharedSelfFeedbackIntent({
- deps,
- enrichment,
- payload,
- runtime,
- source,
+ const timestamp = new Date(source.timestamp).toISOString();
+ const prompt = createAgentSignalSelfIterationPrompt({
+ agentId: payload.agentId,
+ context: createIntentRuntimeContext({ enrichment, payload, sourceId: source.sourceId }),
+ mode: 'feedback',
+ sourceId: source.sourceId,
+ userId: payload.userId,
+ window: { end: timestamp, start: timestamp },
});
- const plan: Plan = runtimeRun.plan;
- const execution: RunResult = runtimeRun.execution;
- const receipts = createSelfFeedbackReceipts({
+ const dispatch = deps.dispatch ?? enqueueSelfIterationRun;
+ const { operationId } = await dispatch({
agentId: payload.agentId,
- createdAt: source.timestamp,
- plan,
- result: {
- ...execution,
- sourceId: source.sourceId,
- },
- selfIteration: {
- ideas: runtimeRun.ideas,
- intents: runtimeRun.runtimeIntents,
- mode: 'feedback',
- scope: { id: payload.scopeId, type: payload.scopeType },
+ db: deps.db,
+ marker: {
+ agentId: payload.agentId,
+ kind: 'self-feedback-intent',
sourceId: source.sourceId,
- toolCallId: payload.toolCallId,
- window: runtimeRun.window,
+ ...(payload.topicId ? { topicId: payload.topicId } : {}),
},
- scopeId: payload.scopeId,
- scopeType: payload.scopeType,
- sourceId: source.sourceId,
- sourceType: source.sourceType,
+ ...(deps.maxSteps ? { maxSteps: deps.maxSteps } : {}),
+ prompt,
+ slug: BUILTIN_AGENT_SLUGS.selfFeedbackIntent,
...(payload.topicId ? { topicId: payload.topicId } : {}),
userId: payload.userId,
});
- const executionWithReceipts = applyReceiptIdsToExecution(
- {
- ...execution,
- sourceId: source.sourceId,
- },
- receipts,
- );
-
- await writeSelfFeedbackIntentReceipts(deps, receipts);
-
- await writeSelfFeedbackIntentReceipt(deps, {
- execution: executionWithReceipts,
- ideas: runtimeRun?.ideas,
- intents: runtimeRun?.runtimeIntents,
- plan,
- scopeId: payload.scopeId,
- scopeType: payload.scopeType,
- sourceId: source.sourceId,
- toolCallId: payload.toolCallId,
- });
return {
...baseResult,
- execution: executionWithReceipts,
- plannedActionCount: plan.actions.length,
- planSummary: plan.summary,
- status: execution.status,
+ operationId,
+ status: ReviewRunStatus.Dispatched,
};
},
});
@@ -671,21 +423,12 @@ export const createSelfFeedbackIntentSourceHandler = (
* -> `agent.self_feedback_intent.declared`
* -> {@link createSelfFeedbackIntentSourcePolicyHandler}
*
- * Upstream:
- * - `agent.self_feedback_intent.declared`
- *
- * Downstream:
- * - {@link createSelfFeedbackIntentSourceHandler}
- *
* Use when:
* - Default Agent Signal policies are composed with self-feedback intent dependencies
* - The runtime source registry needs an installable source handler definition
*
- * Expects:
- * - All server-only dependencies are injected by the caller
- *
* Returns:
- * - A source handler that concludes the runtime chain with the review run metadata
+ * - A source handler that concludes the runtime chain with the dispatch metadata
*/
export const createSelfFeedbackIntentSourcePolicyHandler = (
deps: CreateSelfFeedbackIntentSourceHandlerDependencies,
diff --git a/src/server/services/agentSignal/services/selfIteration/feedback/server.ts b/src/server/services/agentSignal/services/selfIteration/feedback/server.ts
index ca28543e35a..d7d36d16ebf 100644
--- a/src/server/services/agentSignal/services/selfIteration/feedback/server.ts
+++ b/src/server/services/agentSignal/services/selfIteration/feedback/server.ts
@@ -1,458 +1,30 @@
-import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
-
import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
-import type { LobeChatDatabase } from '@/database/type';
-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';
-import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';
import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';
-import { SkillManagementDocumentService } from '@/server/services/skillManagement';
-import { persistAgentSignalReceipts } from '../../receiptService';
-import { executeSelfIteration } from '../execute';
-import { createSelfReviewProposalPreflightService } from '../review/proposalPreflight';
-import { createSelfReviewProposalSnapshotService } from '../review/proposalSnapshot';
import type { CreateServerSelfIterationPolicyOptions } from '../server';
import { canRunSelfIterationSource } from '../server';
-import type {
- OperationReservation,
- ReplaceSkillContentCASInput,
- ToolReceiptInput,
- ToolWriteResult,
-} from '../tools/shared';
-import { createMemoryService, createSkillManagementService, createToolSet } from '../tools/shared';
-import { Risk } from '../types';
-import type {
- CreateSelfFeedbackIntentSourceHandlerDependencies,
- SelfFeedbackIntentEvidenceEnrichment,
- SelfFeedbackIntentRuntimeFactory,
-} from './handler';
-
-const SELF_FEEDBACK_INTENT_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;
-
-const selfFeedbackIntentOperationScopeKey = (idempotencyKey: string) =>
- `self-feedback-intent-operation:${idempotencyKey}`;
-
-const selfFeedbackIntentOperationReserveKey = (idempotencyKey: string) =>
- `self-feedback-intent-operation-reserve:${idempotencyKey}`;
-
-const parseStoredOperationResult = (
- payload: Record<string, string> | undefined,
-): ToolWriteResult | undefined => {
- if (!payload?.result) return;
-
- try {
- const result = JSON.parse(payload.result) as ToolWriteResult;
-
- if (
- result.status === 'applied' ||
- result.status === 'deduped' ||
- result.status === 'failed' ||
- result.status === 'proposed' ||
- result.status === 'skipped_stale' ||
- result.status === 'skipped_unsupported'
- ) {
- return result;
- }
- } catch {
- return;
- }
-};
-
-const reserveSelfFeedbackIntentOperation = async (
- idempotencyKey: string,
-): Promise<OperationReservation> => {
- const scopeKey = selfFeedbackIntentOperationScopeKey(idempotencyKey);
- const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));
-
- if (existing) return { existing, reserved: false };
-
- const reserved = await redisSourceEventStore.tryDedupe(
- selfFeedbackIntentOperationReserveKey(idempotencyKey),
- SELF_FEEDBACK_INTENT_OPERATION_STATE_TTL_SECONDS,
- );
-
- if (reserved) return { reserved: true };
-
- return {
- existing: parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ?? {
- status: 'skipped_unsupported',
- summary:
- 'Self-iteration intent operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',
- },
- reserved: false,
- };
-};
-
-const completeSelfFeedbackIntentOperation = async (input: ToolReceiptInput) => {
- await redisSourceEventStore.writeWindow(
- selfFeedbackIntentOperationScopeKey(input.idempotencyKey),
- {
- result: JSON.stringify({
- ...(input.receiptId ? { receiptId: input.receiptId } : {}),
- ...(input.resourceId ? { resourceId: input.resourceId } : {}),
- status: input.status,
- ...(input.summary ? { summary: input.summary } : {}),
- } satisfies ToolWriteResult),
- },
- SELF_FEEDBACK_INTENT_OPERATION_STATE_TTL_SECONDS,
- );
-};
-
-const getToolReceiptStatus = (
- status: ToolReceiptInput['status'],
-): 'applied' | 'failed' | 'proposed' | 'skipped' => {
- if (status === 'applied') return 'applied';
- if (status === 'failed') return 'failed';
- if (status === 'proposed') return 'proposed';
-
- return 'skipped';
-};
-
-const writeSelfFeedbackIntentToolReceipt = async ({
- agentId,
- input,
- sourceId,
- userId,
-}: {
- agentId: string;
- input: ToolReceiptInput;
- sourceId: string;
- userId: string;
-}) => {
- await persistAgentSignalReceipts([
- {
- agentId,
- createdAt: Date.now(),
- detail:
- input.summary ??
- `Self-iteration intent tool ${input.toolName} finished with ${input.status}.`,
- id: input.idempotencyKey,
- kind:
- input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'
- ? 'skill'
- : 'review',
- metadata: {
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,
- },
- sourceId,
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,
- status: getToolReceiptStatus(input.status),
- ...(input.resourceId &&
- (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')
- ? {
- target: {
- id: input.resourceId,
- ...(input.summary ? { summary: input.summary } : {}),
- title: input.summary ?? input.resourceId,
- type: 'skill',
- },
- }
- : {}),
- title: input.summary ?? 'Self-iteration intent tool outcome',
- topicId: sourceId,
- userId,
- },
- ]);
-
- return { receiptId: input.idempotencyKey };
-};
-
-const createIntentEvidenceDigest = ({
- enrichment,
- payload,
- sourceId,
-}: {
- enrichment: SelfFeedbackIntentEvidenceEnrichment;
- payload: Parameters<SelfFeedbackIntentRuntimeFactory['createRuntime']>[0]['payload'];
- sourceId: string;
-}) => ({
- evidenceRefs: [...payload.evidenceRefs, ...enrichment.evidenceRefs],
- intent: payload,
- scope: {
- id: payload.scopeId,
- type: payload.scopeType,
- },
- sourceId,
-});
-
-const createIntentRuntimeTools = ({
- agentId,
- db,
- enrichment,
- payload,
- skillDocumentService,
- sourceId,
- userId,
-}: {
- agentId: string;
- db: LobeChatDatabase;
- enrichment: SelfFeedbackIntentEvidenceEnrichment;
- payload: Parameters<SelfFeedbackIntentRuntimeFactory['createRuntime']>[0]['payload'];
- skillDocumentService: SkillManagementDocumentService;
- sourceId: string;
- userId: string;
-}) => {
- const evidenceRefs = createIntentEvidenceDigest({ enrichment, payload, sourceId }).evidenceRefs;
- const proposalPreflight = createSelfReviewProposalPreflightService({
- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
-
- return !skills.some((skill) => skill.name === name);
- },
- readSkillTargetSnapshot: (skillDocumentId) =>
- skillDocumentService.readSkillTargetSnapshot({
- agentDocumentId: skillDocumentId,
- agentId,
- }),
- });
- const proposalSnapshot = createSelfReviewProposalSnapshotService({
- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
-
- return !skills.some((skill) => skill.name === name);
- },
- readSkillTargetSnapshot: (skillDocumentId) =>
- skillDocumentService.readSkillTargetSnapshot({
- agentDocumentId: skillDocumentId,
- agentId,
- }),
- });
- const skillService = createSkillManagementService({
- createSkill: async ({ input }) => {
- const result = await skillDocumentService.createSkill({
- agentId,
- bodyMarkdown: input.bodyMarkdown ?? '',
- description: input.description ?? 'Agent Signal managed skill.',
- name: input.name ?? input.title ?? 'agent-signal-skill',
- title: input.title ?? input.name ?? 'Agent Signal skill',
- });
-
- return {
- skillDocumentId: result.bundle.agentDocumentId,
- summary: `Created managed skill ${result.name}.`,
- };
- },
- refineSkill: async ({ input }) => {
- const result = await skillDocumentService.replaceSkillIndex({
- agentDocumentId: input.skillDocumentId,
- agentId,
- bodyMarkdown: input.bodyMarkdown ?? '',
- });
-
- if (!result) throw new Error('Skill target not found');
-
- return {
- skillDocumentId: result.bundle.agentDocumentId,
- summary: `Refined managed skill ${result.name}.`,
- };
- },
- });
-
- return createToolSet({
- completeOperation: completeSelfFeedbackIntentOperation,
- completeReplaceSkillInput: async (input: ReplaceSkillContentCASInput) => {
- const baseSnapshot = await proposalSnapshot.captureActionSnapshot({
- actionType: 'refine_skill',
- agentId,
- input: { skillDocumentId: input.skillDocumentId },
- userId,
- });
-
- return {
- ...input,
- baseSnapshot,
- skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,
- };
- },
- createSkill: async (input) => {
- const result = await skillService.createSkill({
- evidenceRefs,
- idempotencyKey: input.idempotencyKey,
- input,
- });
-
- return {
- resourceId: result.skillDocumentId,
- summary: result.summary,
- };
- },
- getEvidenceDigest: async () =>
- createIntentEvidenceDigest({
- enrichment,
- payload,
- sourceId,
- }),
- getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>
- skillDocumentService.getSkill({
- agentDocumentId: skillDocumentId,
- agentId: targetAgentId,
- includeContent: true,
- }),
- listManagedSkills: ({ agentId: targetAgentId }) =>
- skillDocumentService.listSkills({ agentId: targetAgentId }),
- preflight: async (input) => {
- if ('skillDocumentId' in input) {
- const preflight = await proposalPreflight.checkAction({
- actionType: 'refine_skill',
- baseSnapshot: input.baseSnapshot,
- evidenceRefs: [],
- idempotencyKey: input.idempotencyKey,
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: input.bodyMarkdown,
- patch: input.summary,
- skillDocumentId: input.skillDocumentId,
- userId: input.userId,
- },
- operation: 'refine',
- },
- rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,
- risk: Risk.Low,
- target: { skillDocumentId: input.skillDocumentId },
- });
-
- return preflight.allowed ? { allowed: true } : { allowed: false, reason: preflight.reason };
- }
-
- return { allowed: true };
- },
- replaceSkill: async (input) => {
- const result = await skillService.refineSkill({
- evidenceRefs,
- idempotencyKey: input.idempotencyKey,
- input,
- });
-
- return {
- resourceId: result.skillDocumentId,
- summary: result.summary,
- };
- },
- reserveOperation: reserveSelfFeedbackIntentOperation,
- writeMemory: async (input) => {
- const memoryService = createMemoryService({
- writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
- const result = await runMemoryActionAgent(
- {
- agentId,
- message: content,
- reason: `Agent Signal self-feedback intent memory candidate from ${evidenceRefs.length} evidence refs.`,
- },
- {
- db,
- userId,
- },
- );
-
- if (result.status !== 'applied') {
- throw new Error(
- result.detail ?? 'Memory action agent did not apply a durable memory write.',
- );
- }
-
- return {
- memoryId: idempotencyKey,
- summary: result.detail ?? content,
- };
- },
- });
- const result = await memoryService.writeMemory({
- evidenceRefs: input.evidenceRefs,
- idempotencyKey: input.idempotencyKey,
- input: {
- content: input.content,
- userId: input.userId,
- },
- });
-
- return {
- resourceId: result.memoryId,
- summary: result.summary,
- };
- },
- writeReceipt: (input) =>
- writeSelfFeedbackIntentToolReceipt({ agentId, input, sourceId, userId }),
- });
-};
-
-/**
- * Creates source-scoped runtime dependencies for server self-feedback intent runs.
- *
- * Call stack:
- *
- * createServerSelfFeedbackIntentPolicyOptions
- * -> {@link SelfFeedbackIntentServerRuntimeFactory.createRuntime}
- * -> {@link executeSelfIteration}
- * -> self-feedback intent tools and receipt persistence
- *
- * Use when:
- * - The Agent Signal workflow consumes `agent.self_feedback_intent.declared`
- * - Declared agent feedback must use the self-iteration executor instead of legacy planner/executor
- *
- * Expects:
- * - The handler has already validated the source payload and guard
- * - Tools are scoped to one user/agent/source id
- *
- * Returns:
- * - Model runtime, toolset, and executor callback for one intent run
- */
-export class SelfFeedbackIntentServerRuntimeFactory implements SelfFeedbackIntentRuntimeFactory {
- constructor(
- private readonly input: {
- db: LobeChatDatabase;
- skillDocumentService: SkillManagementDocumentService;
- userId: string;
- },
- ) {}
-
- async createRuntime({
- enrichment,
- payload,
- source,
- }: Parameters<SelfFeedbackIntentRuntimeFactory['createRuntime']>[0]) {
- const modelRuntime = await initModelRuntimeFromDB(
- this.input.db,
- this.input.userId,
- DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
- );
-
- return {
- executeSelfIteration,
- model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,
- modelRuntime,
- tools: createIntentRuntimeTools({
- agentId: payload.agentId,
- db: this.input.db,
- enrichment,
- payload,
- skillDocumentService: this.input.skillDocumentService,
- sourceId: source.sourceId,
- userId: this.input.userId,
- }),
- };
- }
-}
+import type { CreateSelfFeedbackIntentSourceHandlerDependencies } from './handler';
/**
- * Creates server runtime handlers for agent-declared self-feedback intent sources.
+ * Creates server self-feedback intent policy options for the Agent Signal workflow.
*
* Call stack:
*
* runAgentSignalWorkflow
* -> {@link createServerSelfFeedbackIntentPolicyOptions}
* -> intent source handler dependencies
- * -> {@link SelfFeedbackIntentServerRuntimeFactory}
+ * -> {@link enqueueSelfIterationRun} (async execAgent under the builtin slug)
*
- * Use when:
- * - The Agent Signal workflow consumes `agent.self_feedback_intent.declared`
- * - Runtime policy composition needs scoped shared execution and receipts
+ * The handler only gates, dedupes, enriches bounded evidence, and dispatches an
+ * async run. The self-iteration tools are resolved server-side from
+ * `plugins: ['agent-signal-feedback-intent']` by the builtin self-feedback-intent
+ * agent's serverRuntime — there is no inline model runtime, toolset, or receipt
+ * writer here anymore.
*
* Expects:
* - The source was emitted by `declareSelfFeedbackIntent`
- * - The handler will re-check gates and idempotency before reviewer work
+ * - The handler will re-check gates and idempotency before dispatch
*
* Returns:
* - Intent handler options ready for `createDefaultAgentSignalPolicies`
@@ -464,7 +36,6 @@ export const createServerSelfFeedbackIntentPolicyOptions = ({
userId,
}: CreateServerSelfIterationPolicyOptions): CreateSelfFeedbackIntentSourceHandlerDependencies => {
const reviewContextModel = new AgentSignalReviewContextModel(db, userId);
- const skillDocumentService = new SkillManagementDocumentService(db, userId);
return {
acquireReviewGuard: (input) =>
@@ -482,6 +53,7 @@ export const createServerSelfFeedbackIntentPolicyOptions = ({
selfIterationEnabled,
});
},
+ db,
enrichEvidence: async (input) => ({
evidenceRefs: [
{
@@ -490,12 +62,5 @@ export const createServerSelfFeedbackIntentPolicyOptions = ({
},
],
}),
- runtimeFactory: new SelfFeedbackIntentServerRuntimeFactory({
- db,
- skillDocumentService,
- userId,
- }),
- writeReceipt: async () => {},
- writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),
};
};
diff --git a/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts b/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts
index 1c9b2b361e8..1e33c786f96 100644
--- a/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts
+++ b/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts
@@ -73,8 +73,19 @@ export const extractFromFinalState = (
if (resultKind !== kind) continue;
+ // `apiName` rides in the result content (stamped alongside `kind` by the tool
+ // runtime), because the agent runtime persists tool messages without a
+ // message-level `apiName`. Fall back to `message.apiName` for any producer
+ // that does set it.
+ const apiName =
+ typeof contentRecord?.apiName === 'string'
+ ? contentRecord.apiName
+ : typeof message.apiName === 'string'
+ ? message.apiName
+ : undefined;
+
results.push({
- apiName: typeof message.apiName === 'string' ? message.apiName : undefined,
+ apiName,
data: contentRecord ?? content,
kind,
toolCallId: typeof message.tool_call_id === 'string' ? message.tool_call_id : undefined,
diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts
index f2e7d76bd10..1332988a1e5 100644
--- a/src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/handler.test.ts
@@ -2,6 +2,7 @@
import { createSource } from '@lobechat/agent-signal';
import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { describe, expect, it, vi } from 'vitest';
import { createDefaultAgentSignalPolicies } from '../../../../policies';
@@ -11,8 +12,7 @@ import type {
AgentSignalSignalHandlerDefinition,
AgentSignalSourceHandlerDefinition,
} from '../../../../runtime/middleware';
-import type { ExecuteSelfIterationResult } from '../../execute';
-import { ReviewRunStatus, Scope } from '../../types';
+import { ReviewRunStatus } from '../../types';
import type {
CreateSelfReflectionSourceHandlerDependencies,
SelfReflectionReviewContext,
@@ -73,190 +73,25 @@ const reflectionContext = {
windowStart: reflectionPayload.windowStart,
} satisfies SelfReflectionReviewContext;
-const runtimeResult = {
- actions: [
- {
- result: {
- receiptId: 'runtime-receipt-1',
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Memory written.',
- },
- toolName: 'writeMemory',
- },
- ],
- content: 'Runtime reflection wrote one memory.',
- ideas: [],
- intents: [
- {
- confidence: 0.82,
- evidenceRefs: [{ id: 'task-1', type: 'task' }],
- idempotencyKey: `${reflectionSourceId}:intent:memory`,
- intentType: 'memory',
- mode: 'reflection',
- rationale: 'Capture the same-turn preference.',
- risk: 'low',
- urgency: 'soon',
- },
- ],
- status: ReviewRunStatus.Completed,
- stepCount: 2,
- toolCalls: [
- {
- apiName: 'writeMemory',
- arguments: JSON.stringify({
- content: 'User prefers scoped task follow-up.',
- evidenceRefs: [{ id: 'task-1', type: 'task' }],
- idempotencyKey: `${reflectionSourceId}:writeMemory:tool-call-1`,
- }),
- id: 'tool-call-1',
- identifier: 'agent-signal-self-iteration',
- type: 'builtin',
- },
- ],
- usage: [],
- writeOutcomes: [
- {
- result: {
- receiptId: 'runtime-receipt-1',
- resourceId: 'memory-1',
- status: 'applied',
- summary: 'Memory written.',
- },
- toolName: 'writeMemory',
- },
- ],
-} satisfies ExecuteSelfIterationResult;
-
const createDependencies = (
overrides: Partial<CreateSelfReflectionSourceHandlerDependencies> = {},
): CreateSelfReflectionSourceHandlerDependencies => ({
acquireReviewGuard: vi.fn(async () => true),
canRunReview: vi.fn(async () => true),
collectContext: vi.fn(async () => reflectionContext),
- executeSelfIteration: vi.fn(async () => runtimeResult),
+ db: {} as never,
+ dispatch: vi.fn(async () => ({ operationId: 'op-self-iter-1', topicId: 'topic-1' })),
maxSteps: 3,
- model: 'gpt-test',
- modelRuntime: { chat: vi.fn() },
- tools: {} as never,
- writeReceipt: vi.fn(async () => {}),
...overrides,
});
describe('self-reflection source handler', () => {
- /**
- * @example
- * expect(deps.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'reflection' }));
- * expect(deps.executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ mode: 'reflection' }));
- */
- it('runs self-iteration executor for reflection and records reflection metadata on receipts', async () => {
- const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });
- const handler = createSelfReflectionSourceHandler(deps);
-
- const result = await handler.handle(createReflectionSource());
-
- expect(deps.executeSelfIteration).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'agent-1',
- context: reflectionContext,
- maxSteps: 3,
- mode: 'reflection',
- sourceId: reflectionSourceId,
- userId: 'user-1',
- window: {
- end: reflectionPayload.windowEnd,
- start: reflectionPayload.windowStart,
- },
- }),
- );
- expect(deps.writeReceipts).toHaveBeenCalledWith([
- expect.objectContaining({
- id: `${reflectionSourceId}:review-summary`,
- metadata: expect.objectContaining({
- selfIteration: expect.objectContaining({
- intents: runtimeResult.intents,
- mode: 'reflection',
- reason: 'failed_tool_count',
- sourceId: reflectionSourceId,
- }),
- }),
- }),
- expect.objectContaining({ id: `${reflectionSourceId}:writeMemory:tool-call-1:action` }),
- ]);
- expect(result).toEqual(
- expect.objectContaining({
- plannedActionCount: 1,
- planSummary: 'Runtime reflection wrote one memory.',
- status: ReviewRunStatus.Completed,
- }),
- );
- });
-
- /**
- * @example
- * expect(runtimeFactory.createRuntime).toHaveBeenCalledWith(expect.objectContaining({ context }));
- * expect(executeSelfIteration).toHaveBeenCalledWith(expect.objectContaining({ tools }));
- */
- it('builds self-iteration executor dependencies through the per-source runtime factory', async () => {
- const executeSelfIteration = vi.fn(async () => runtimeResult);
- const modelRuntime = { chat: vi.fn() };
- const tools = {} as never;
- const runtimeFactory = {
- createRuntime: vi.fn(async () => ({
- executeSelfIteration,
- maxSteps: 4,
- model: 'gpt-factory',
- modelRuntime,
- tools,
- })),
- };
- const deps = createDependencies({
- runtimeFactory,
- writeReceipts: vi.fn(async () => {}),
- });
- const handler = createSelfReflectionSourceHandler(deps);
-
- await handler.handle(createReflectionSource());
-
- expect(runtimeFactory.createRuntime).toHaveBeenCalledWith({
- context: reflectionContext,
- payload: reflectionPayload,
- source: expect.objectContaining({ sourceId: reflectionSourceId }),
- });
- expect(executeSelfIteration).toHaveBeenCalledWith(
- expect.objectContaining({
- maxSteps: 4,
- model: 'gpt-factory',
- modelRuntime,
- mode: 'reflection',
- tools,
- }),
- );
- });
-
- /**
- * @example
- * expect(result.status).toBe('completed');
- */
- it('orchestrates scoped collector self-iteration executor and receipt writer', async () => {
+ it('dispatches an async self-iteration run under the builtin self-reflection slug', async () => {
const deps = createDependencies();
const handler = createSelfReflectionSourceHandler(deps);
const result = await handler.handle(createReflectionSource());
- expect(deps.canRunReview).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'agent-1',
- guardKey: reflectionSourceId,
- reason: 'failed_tool_count',
- scopeId: 'task-1',
- scopeType: 'task',
- userId: 'user-1',
- }),
- );
- expect(deps.acquireReviewGuard).toHaveBeenCalledWith(
- expect.objectContaining({ guardKey: reflectionSourceId }),
- );
expect(deps.collectContext).toHaveBeenCalledWith({
agentId: 'agent-1',
operationId: 'operation-1',
@@ -268,99 +103,57 @@ describe('self-reflection source handler', () => {
windowEnd: reflectionPayload.windowEnd,
windowStart: reflectionPayload.windowStart,
});
- expect(deps.executeSelfIteration).toHaveBeenCalledWith(
+ expect(deps.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
- context: reflectionContext,
- mode: 'reflection',
- sourceId: reflectionSourceId,
- }),
- );
- expect(deps.writeReceipt).toHaveBeenCalledWith(
- expect.objectContaining({
- execution: expect.objectContaining({
- status: runtimeResult.status,
- summaryReceiptId: `${reflectionSourceId}:review-summary`,
- }),
- intents: runtimeResult.intents,
- plan: expect.objectContaining({
- reviewScope: Scope.SelfReflection,
- summary: runtimeResult.content,
- }),
- reason: 'failed_tool_count',
- scopeId: 'task-1',
- scopeType: 'task',
- sourceId: reflectionSourceId,
+ agentId: 'agent-1',
+ db: deps.db,
+ marker: {
+ agentId: 'agent-1',
+ kind: 'self-reflection',
+ sourceId: reflectionSourceId,
+ topicId: 'topic-1',
+ },
+ maxSteps: 3,
+ // The bounded evidence is rendered into the prompt (no collector at run time).
+ prompt: expect.stringContaining(reflectionSourceId),
+ slug: BUILTIN_AGENT_SLUGS.selfReflection,
+ topicId: 'topic-1',
+ userId: 'user-1',
}),
);
expect(result).toEqual(
expect.objectContaining({
agentId: 'agent-1',
- execution: expect.objectContaining({ status: runtimeResult.status }),
- plannedActionCount: 1,
- planSummary: 'Runtime reflection wrote one memory.',
+ operationId: 'op-self-iter-1',
sourceId: reflectionSourceId,
- status: ReviewRunStatus.Completed,
+ status: ReviewRunStatus.Dispatched,
userId: 'user-1',
}),
);
});
- /**
- * @example
- * expect(deps.writeReceipt).toHaveBeenCalledTimes(1);
- */
- it('emits receipts without requiring a daily brief dependency', async () => {
- const deps = createDependencies({ writeReceipts: vi.fn(async () => {}) });
+ it('re-checks the gate then acquires the idempotency guard before dispatching', async () => {
+ const deps = createDependencies();
const handler = createSelfReflectionSourceHandler(deps);
await handler.handle(createReflectionSource());
- expect(deps.writeReceipts).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({ id: `${reflectionSourceId}:review-summary` }),
- expect.objectContaining({
- id: `${reflectionSourceId}:writeMemory:tool-call-1:action`,
- }),
- ]),
- );
- expect(deps.writeReceipt).toHaveBeenCalledTimes(1);
- expect('writeDailyBrief' in deps).toBe(false);
- });
-
- /**
- * @example
- * expect(result.status).toBe('completed');
- */
- it('keeps applied self-reflection runs completed when receipt writing fails', async () => {
- const receiptError = new Error('receipt store unavailable');
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- const deps = createDependencies({
- writeReceipt: vi.fn(async () => {
- throw receiptError;
- }),
- });
- const handler = createSelfReflectionSourceHandler(deps);
-
- const result = await handler.handle(createReflectionSource());
-
- expect(result).toEqual(
+ expect(deps.canRunReview).toHaveBeenCalledWith(
expect.objectContaining({
- execution: expect.objectContaining({ status: runtimeResult.status }),
- status: ReviewRunStatus.Completed,
+ agentId: 'agent-1',
+ guardKey: reflectionSourceId,
+ reason: 'failed_tool_count',
+ scopeId: 'task-1',
+ scopeType: 'task',
+ userId: 'user-1',
}),
);
- expect(consoleError).toHaveBeenCalledWith(
- '[AgentSignal] Failed to write self-reflection receipt:',
- receiptError,
+ expect(deps.acquireReviewGuard).toHaveBeenCalledWith(
+ expect.objectContaining({ guardKey: reflectionSourceId }),
);
- consoleError.mockRestore();
});
- /**
- * @example
- * expect(result.status).toBe('deduped');
- */
- it('returns deduped without collecting when the review guard is already held', async () => {
+ it('returns deduped without collecting or dispatching when the review guard is held', async () => {
const deps = createDependencies({
acquireReviewGuard: vi.fn(async () => false),
});
@@ -375,14 +168,9 @@ describe('self-reflection source handler', () => {
}),
);
expect(deps.collectContext).not.toHaveBeenCalled();
- expect(deps.executeSelfIteration).not.toHaveBeenCalled();
- expect(deps.writeReceipt).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('gate_disabled');
- */
it('returns skipped without acquiring the guard when gates reject the review', async () => {
const deps = createDependencies({
canRunReview: vi.fn(async () => false),
@@ -399,12 +187,9 @@ describe('self-reflection source handler', () => {
);
expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
expect(deps.collectContext).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
it('returns skipped invalid without throwing for invalid payloads', async () => {
const deps = createDependencies();
const handler = createSelfReflectionSourceHandler(deps);
@@ -422,12 +207,9 @@ describe('self-reflection source handler', () => {
expect(deps.canRunReview).not.toHaveBeenCalled();
expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
expect(deps.collectContext).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
it('returns skipped invalid when scope type is outside the supported set', async () => {
const deps = createDependencies();
const handler = createSelfReflectionSourceHandler(deps);
@@ -448,10 +230,6 @@ describe('self-reflection source handler', () => {
expect(deps.canRunReview).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
it('returns skipped invalid when source id does not match the expected self-reflection key', async () => {
const deps = createDependencies();
const handler = createSelfReflectionSourceHandler(deps);
@@ -476,10 +254,6 @@ describe('self-reflection source handler', () => {
expect(deps.collectContext).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(sourceHandlers[0].listen).toBe('agent.self_reflection.requested');
- */
it('installs an optional self-reflection source policy through default policy composition', async () => {
const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];
const deps = createDependencies();
@@ -529,16 +303,12 @@ describe('self-reflection source handler', () => {
expect(runtimeResult).toEqual(
expect.objectContaining({
- concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),
+ concluded: expect.objectContaining({ status: ReviewRunStatus.Dispatched }),
status: 'conclude',
}),
);
});
- /**
- * @example
- * expect(selfReflectionHandler).toBeUndefined();
- */
it('does not install self-reflection source handlers without self-reflection dependencies', async () => {
const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];
const policies = createDefaultAgentSignalPolicies({
@@ -577,10 +347,6 @@ describe('self-reflection source handler', () => {
});
describe('self-reflection source policy handler', () => {
- /**
- * @example
- * expect(handler.listen).toBe('agent.self_reflection.requested');
- */
it('listens to the self-reflection requested source type', () => {
const handler = createSelfReflectionSourcePolicyHandler(createDependencies());
diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.ts b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.ts
index afedb7ff753..813ef224e03 100644
--- a/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/reflection/__test__/server.test.ts
@@ -1,54 +1,12 @@
// @vitest-environment node
-import { createSource } from '@lobechat/agent-signal';
-import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';
-import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import type { LobeChatDatabase } from '@/database/type';
-import type { SelfReflectionReviewContext } from '../handler';
import { createServerSelfReflectionPolicyOptions } from '../server';
-const mocks = vi.hoisted(() => ({
- initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),
-}));
-
-vi.mock('@/server/modules/ModelRuntime', () => ({
- initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
-}));
-
-const payload = {
- agentId: 'agent-1',
- reason: 'tool_failed',
- scopeId: 'topic-1',
- scopeType: 'topic',
- topicId: 'topic-1',
- userId: 'user-1',
- windowEnd: '2026-05-11T01:00:00.000Z',
- windowStart: '2026-05-11T00:00:00.000Z',
-} as const;
-
-const source = createSource({
- payload,
- scope: { agentId: 'agent-1', userId: 'user-1' },
- scopeKey: 'topic:topic-1',
- sourceId: 'self-reflection:user-1:agent-1:topic:topic-1',
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,
- timestamp: 100,
-}) as SourceAgentSelfReflectionRequested;
-
-const context = {
- ...payload,
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- topics: [],
-} satisfies SelfReflectionReviewContext;
-
describe('createServerSelfReflectionPolicyOptions', () => {
- /**
- * @example
- * expect(runtime.tools).toEqual(expect.objectContaining({ writeMemory: expect.any(Function) }));
- */
- it('builds source-scoped self-iteration executor runtime and disables legacy planner execution', async () => {
+ it('exposes dispatch-shaped handler deps (gate, guard, collector, db) without legacy runtime/receipt wiring', () => {
const options = createServerSelfReflectionPolicyOptions({
agentId: 'agent-1',
db: {} as unknown as LobeChatDatabase,
@@ -56,21 +14,40 @@ describe('createServerSelfReflectionPolicyOptions', () => {
userId: 'user-1',
});
- const runtime = await options.runtimeFactory?.createRuntime({ context, payload, source });
+ expect(options.acquireReviewGuard).toEqual(expect.any(Function));
+ expect(options.canRunReview).toEqual(expect.any(Function));
+ expect(options.collectContext).toEqual(expect.any(Function));
+ // The dispatch helper enqueues the run; the handler needs the db handle.
+ expect(options.db).toBeDefined();
+ // Self-iteration now runs via execAgent + the builtin serverRuntime — the old
+ // inline runtime factory / receipt writers must be gone.
+ expect('runtimeFactory' in options).toBe(false);
+ expect('executeSelfIteration' in options).toBe(false);
+ expect('writeReceipt' in options).toBe(false);
+ expect('writeReceipts' in options).toBe(false);
+ });
+
+ it('rejects reviews whose payload user id does not match the policy owner', async () => {
+ const options = createServerSelfReflectionPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
+ });
- expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledOnce();
- expect(runtime).toEqual(
- expect.objectContaining({
- executeSelfIteration: expect.any(Function),
- model: expect.any(String),
- modelRuntime: expect.objectContaining({ chat: expect.any(Function) }),
- tools: expect.objectContaining({
- getEvidenceDigest: expect.any(Function),
- writeMemory: expect.any(Function),
- }),
+ // userId mismatch short-circuits before any DB access.
+ await expect(
+ options.canRunReview({
+ agentId: 'agent-1',
+ guardKey: 'self-reflection:user-2:agent-1:topic:topic-1',
+ reason: 'tool_failed',
+ scopeId: 'topic-1',
+ scopeType: 'topic',
+ sourceId: 'self-reflection:user-2:agent-1:topic:topic-1',
+ userId: 'user-2',
+ windowEnd: '2026-05-11T01:00:00.000Z',
+ windowStart: '2026-05-11T00:00:00.000Z',
}),
- );
- expect('planReviewOutput' in options).toBe(false);
- expect('executePlan' in options).toBe(false);
+ ).resolves.toBe(false);
});
});
diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts b/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts
index 4803db6bd6d..d75951083e0 100644
--- a/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts
+++ b/src/server/services/agentSignal/services/selfIteration/reflection/handler.ts
@@ -1,16 +1,14 @@
import type { SourceAgentSelfReflectionRequested } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import type { ModelRuntime } from '@lobechat/model-runtime';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { createAgentSignalSelfIterationPrompt } from '@lobechat/prompts';
import { isNonEmptyString } from '@lobechat/utils';
+import type { LobeChatDatabase } from '@/database/type';
+
import { defineSourceHandler } from '../../../runtime/middleware';
-import type { AgentSignalReceipt } from '../../receiptService';
-import { createSelfFeedbackReceipts } from '../../receiptService';
-import type { ExecuteSelfIterationInput, ExecuteSelfIterationResult } from '../execute';
-import { projectRun } from '../projection';
-import type { ToolSet } from '../tools/shared';
-import type { Idea, Plan, RunResult, SelfFeedbackIntent } from '../types';
-import { buildSelfReflectionSourceId, ReviewRunStatus, Scope } from '../types';
+import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';
+import { buildSelfReflectionSourceId, ReviewRunStatus } from '../types';
/** Runtime scope supported by self-reflection source handlers. */
export type SelfReflectionSourceScopeType = 'operation' | 'task' | 'topic';
@@ -83,85 +81,17 @@ export interface SelfReflectionReviewContext extends CollectSelfReflectionContex
[key: string]: unknown;
}
-/**
- * Receipt input emitted after one self-reflection shared execution.
- */
-export interface SelfReflectionReceiptInput {
- /** Executor result for the completed self-reflection run. */
- execution: RunResult;
- /** Non-actionable ideas captured by the self-iteration runtime. */
- ideas?: Idea[];
- /** Immediate intents captured by the self-iteration runtime. */
- intents?: SelfFeedbackIntent[];
- /** Normalized self-iteration plan sent to the executor. */
- plan: Plan;
- /** Stable reason that requested reflection. */
- reason: string;
- /** Runtime scope id reviewed by the run. */
- scopeId: string;
- /** Runtime scope family reviewed by the run. */
- scopeType: SelfReflectionSourceScopeType;
- /** Source id that triggered the run. */
- sourceId: string;
-}
-
-/**
- * Input passed to a reflection runtime factory before one self-iteration run.
- */
-export interface SelfReflectionRuntimeFactoryInput {
- /** Source-scoped evidence context collected for this reflection. */
- context: SelfReflectionReviewContext;
- /** Validated source payload that requested reflection. */
- payload: SelfReflectionSourcePayload;
- /** Original source event being handled. */
- source: SourceAgentSelfReflectionRequested;
-}
-
-/**
- * Per-run runtime dependencies for the self-iteration executor.
- */
-export interface SelfReflectionRuntimeConfig {
- /** Runs the self-iteration executor. */
- executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;
- /**
- * Maximum self-iteration runtime steps.
- *
- * @default 10
- */
- maxSteps?: number;
- /** Model name used by the self-iteration runtime. */
- model: string;
- /** Model runtime used by the self-iteration runtime. */
- modelRuntime: Pick<ModelRuntime, 'chat'>;
- /** Source-scoped safe tools exposed to the self-iteration runtime. */
- tools: ToolSet;
-}
-
-/**
- * Class-backed boundary that creates source-scoped runtime dependencies.
- */
-export interface SelfReflectionRuntimeFactory {
- /** Builds the model/runtime/tools bundle for one reflection source. */
- createRuntime: (
- input: SelfReflectionRuntimeFactoryInput,
- ) => Promise<SelfReflectionRuntimeConfig> | SelfReflectionRuntimeConfig;
-}
-
/**
* Result returned by the self-reflection source handler.
*/
export interface SelfReflectionSourceHandlerResult extends Record<string, unknown> {
/** Stable agent id being reviewed when payload validation succeeds. */
agentId?: string;
- /** Executor result for completed runs. */
- execution?: RunResult;
/** Stable guard key used for idempotency when payload validation succeeds. */
guardKey?: string;
- /** Number of planned self-review actions before execution. */
- plannedActionCount?: number;
- /** Planner summary for receipt construction. */
- planSummary?: string;
- /** Machine-readable skip reason for non-completed runs. */
+ /** Operation id of the enqueued background self-iteration run, when dispatched. */
+ operationId?: string;
+ /** Machine-readable skip reason for non-dispatched runs. */
reason?: 'gate_disabled' | 'invalid_payload';
/** Topic, task, or operation id selected for bounded evidence collection. */
scopeId?: string;
@@ -191,26 +121,16 @@ export interface CreateSelfReflectionSourceHandlerDependencies {
collectContext: (
input: CollectSelfReflectionContextInput,
) => Promise<SelfReflectionReviewContext>;
- /** Runs the self-iteration runtime when no source-scoped factory is injected. */
- executeSelfIteration?: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;
+ /** Postgres handle used by the dispatch helper to enqueue the execAgent run. */
+ db: LobeChatDatabase;
+ /** Enqueues the async self-iteration run. Overridable for tests. */
+ dispatch?: typeof enqueueSelfIterationRun;
/**
* Maximum self-iteration runtime steps.
*
- * @default 10
+ * @default builtin agent default
*/
maxSteps?: number;
- /** Model name used by the self-iteration runtime. */
- model?: string;
- /** Model runtime used by the self-iteration runtime. */
- modelRuntime?: Pick<ModelRuntime, 'chat'>;
- /** Builds source-scoped shared-runtime dependencies for reflection mode. */
- runtimeFactory?: SelfReflectionRuntimeFactory;
- /** Safe tools exposed to the self-iteration runtime. */
- tools?: ToolSet;
- /** Writes durable receipt metadata for the self-reflection run. */
- writeReceipt: (input: SelfReflectionReceiptInput) => Promise<void>;
- /** Writes durable receipt records for the review summary and action outcomes. */
- writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;
}
const isSelfReflectionScopeType = (value: unknown): value is SelfReflectionSourceScopeType =>
@@ -294,133 +214,6 @@ const toBaseResult = (
windowStart: guardInput.windowStart,
});
-const writeSelfReflectionReceipt = async (
- deps: CreateSelfReflectionSourceHandlerDependencies,
- input: SelfReflectionReceiptInput,
-) => {
- try {
- await deps.writeReceipt(input);
- } catch (error) {
- console.error('[AgentSignal] Failed to write self-reflection receipt:', error);
- }
-};
-
-const writeSelfReflectionReceipts = async (
- deps: CreateSelfReflectionSourceHandlerDependencies,
- receipts: AgentSignalReceipt[],
-) => {
- if (!deps.writeReceipts || receipts.length === 0) return;
-
- try {
- await deps.writeReceipts(receipts);
- } catch (error) {
- console.error('[AgentSignal] Failed to write self-reflection receipts:', error);
- }
-};
-
-const applyReceiptIdsToExecution = (
- execution: RunResult,
- receipts: AgentSignalReceipt[],
-): RunResult => {
- const receiptByActionKey = new Map(
- receipts
- .filter((receipt) => receipt.id.endsWith(':action'))
- .map((receipt) => [receipt.id.slice(0, -':action'.length), receipt.id]),
- );
-
- return {
- ...execution,
- actions: execution.actions.map((action) => ({
- ...action,
- ...(receiptByActionKey.get(action.idempotencyKey)
- ? { receiptId: receiptByActionKey.get(action.idempotencyKey) }
- : {}),
- })),
- summaryReceiptId: `${execution.sourceId ?? receipts[0]?.sourceId}:review-summary`,
- };
-};
-
-const canExecuteSharedSelfIteration = (
- deps: CreateSelfReflectionSourceHandlerDependencies,
-): deps is CreateSelfReflectionSourceHandlerDependencies & {
- executeSelfIteration: (input: ExecuteSelfIterationInput) => Promise<ExecuteSelfIterationResult>;
- model: string;
- modelRuntime: Pick<ModelRuntime, 'chat'>;
- tools: ToolSet;
-} => Boolean(deps.executeSelfIteration && deps.model && deps.modelRuntime && deps.tools);
-
-const runSharedSelfReflection = async ({
- context,
- payload,
- runtime,
- source,
-}: {
- context: SelfReflectionReviewContext;
- payload: SelfReflectionSourcePayload;
- runtime: SelfReflectionRuntimeConfig;
- source: SourceAgentSelfReflectionRequested;
-}) => {
- const runtimeResult = await runtime.executeSelfIteration({
- agentId: payload.agentId,
- context,
- maxSteps: runtime.maxSteps ?? 10,
- mode: 'reflection',
- model: runtime.model,
- modelRuntime: runtime.modelRuntime,
- sourceId: source.sourceId,
- tools: runtime.tools,
- userId: payload.userId,
- window: {
- end: payload.windowEnd,
- start: payload.windowStart,
- },
- });
- const projected = projectRun({
- content: runtimeResult.content,
- outcomes: runtimeResult.writeOutcomes.map((outcome) => ({
- ...outcome.result,
- toolName: outcome.toolName,
- })),
- reviewScope: Scope.SelfReflection,
- sourceId: source.sourceId,
- toolCalls: runtimeResult.toolCalls,
- userId: payload.userId,
- });
-
- return {
- execution: projected.execution,
- ideas: runtimeResult.ideas,
- plan: projected.projectionPlan,
- runtimeIntents: runtimeResult.intents,
- };
-};
-
-const resolveSharedSelfReflectionRuntime = async ({
- context,
- deps,
- payload,
- source,
-}: {
- context: SelfReflectionReviewContext;
- deps: CreateSelfReflectionSourceHandlerDependencies;
- payload: SelfReflectionSourcePayload;
- source: SourceAgentSelfReflectionRequested;
-}): Promise<SelfReflectionRuntimeConfig | undefined> => {
- if (deps.runtimeFactory) {
- return deps.runtimeFactory.createRuntime({ context, payload, source });
- }
-
- if (!canExecuteSharedSelfIteration(deps)) return;
-
- return {
- executeSelfIteration: deps.executeSelfIteration,
- maxSteps: deps.maxSteps,
- model: deps.model,
- modelRuntime: deps.modelRuntime,
- tools: deps.tools,
- };
-};
-
/**
* Creates the DI-friendly handler for self-reflection request sources.
*
@@ -430,23 +223,20 @@ const resolveSharedSelfReflectionRuntime = async ({
* -> `agent.self_reflection.requested`
* -> {@link createSelfReflectionSourceHandler}
*
- * Upstream:
- * - `agent.self_reflection.requested`
- *
- * Downstream:
- * - injected self-iteration executor
- * - injected `writeReceipt`
- *
- * Use when:
- * - Tests need to run scoped self-reflection orchestration without DB or LLM dependencies
- * - Runtime policy composition needs a side-effect boundary before executing self-iteration plans
+ * The handler validates the request, re-checks gates + idempotency, collects
+ * bounded evidence, then enqueues an async `execAgent` run under the builtin
+ * `self-reflection` agent (slug `agent-signal-reflection` tools). The run's
+ * outcome (memory / skill writes, feedback intents) is projected into receipts
+ * by the completion path — this handler does not run the model or write receipts
+ * inline.
*
* Expects:
* - `source` is an `agent.self_reflection.requested` source with service-produced payload
- * - Dependencies enforce gates, idempotency, executor persistence, and receipts
+ * - Dependencies enforce gates, idempotency, and provide a db handle for dispatch
*
* Returns:
- * - A run result with status and enough plan metadata for self-reflection receipts
+ * - A run result with `Dispatched` status + the enqueued operation id, or a
+ * `Skipped` / `Deduped` status when gates / idempotency reject the run
*/
export const createSelfReflectionSourceHandler = (
deps: CreateSelfReflectionSourceHandlerDependencies,
@@ -491,65 +281,37 @@ export const createSelfReflectionSourceHandler = (
}
const context = await deps.collectContext(toCollectContextInput(payload));
- const runtime = await resolveSharedSelfReflectionRuntime({ context, deps, payload, source });
-
- if (!runtime) throw new Error('Self-reflection self-iteration runtime is required.');
- const runtimeRun = await runSharedSelfReflection({ context, payload, runtime, source });
- const plan: Plan = runtimeRun.plan;
- const execution: RunResult = runtimeRun.execution;
-
- const receipts = createSelfFeedbackReceipts({
+ const prompt = createAgentSignalSelfIterationPrompt({
agentId: payload.agentId,
- createdAt: source.timestamp,
- plan,
- result: {
- ...execution,
- sourceId: source.sourceId,
- },
- selfIteration: {
- ideas: runtimeRun.ideas,
- intents: runtimeRun.runtimeIntents,
- mode: 'reflection',
- reason: payload.reason,
- scope: { id: payload.scopeId, type: payload.scopeType },
- sourceId: source.sourceId,
- window: { end: payload.windowEnd, start: payload.windowStart },
- },
- scopeId: payload.scopeId,
- scopeType: payload.scopeType,
+ context,
+ mode: 'reflection',
sourceId: source.sourceId,
- sourceType: source.sourceType,
- ...(payload.topicId ? { topicId: payload.topicId } : {}),
userId: payload.userId,
+ window: { end: payload.windowEnd, start: payload.windowStart },
});
- const executionWithReceipts = applyReceiptIdsToExecution(
- {
- ...execution,
+
+ const dispatch = deps.dispatch ?? enqueueSelfIterationRun;
+ const { operationId } = await dispatch({
+ agentId: payload.agentId,
+ db: deps.db,
+ marker: {
+ agentId: payload.agentId,
+ kind: 'self-reflection',
sourceId: source.sourceId,
+ ...(payload.topicId ? { topicId: payload.topicId } : {}),
},
- receipts,
- );
-
- await writeSelfReflectionReceipts(deps, receipts);
-
- await writeSelfReflectionReceipt(deps, {
- execution: executionWithReceipts,
- ideas: runtimeRun?.ideas,
- intents: runtimeRun?.runtimeIntents,
- plan,
- reason: payload.reason,
- scopeId: payload.scopeId,
- scopeType: payload.scopeType,
- sourceId: source.sourceId,
+ ...(deps.maxSteps ? { maxSteps: deps.maxSteps } : {}),
+ prompt,
+ slug: BUILTIN_AGENT_SLUGS.selfReflection,
+ ...(payload.topicId ? { topicId: payload.topicId } : {}),
+ userId: payload.userId,
});
return {
...baseResult,
- execution: executionWithReceipts,
- plannedActionCount: plan.actions.length,
- planSummary: plan.summary,
- status: execution.status,
+ operationId,
+ status: ReviewRunStatus.Dispatched,
};
},
});
@@ -563,21 +325,12 @@ export const createSelfReflectionSourceHandler = (
* -> `agent.self_reflection.requested`
* -> {@link createSelfReflectionSourcePolicyHandler}
*
- * Upstream:
- * - `agent.self_reflection.requested`
- *
- * Downstream:
- * - {@link createSelfReflectionSourceHandler}
- *
* Use when:
* - Default Agent Signal policies are composed with self-reflection dependencies
* - The runtime source registry needs an installable source handler definition
*
- * Expects:
- * - All server-only dependencies are injected by the caller
- *
* Returns:
- * - A source handler that concludes the runtime chain with the review run metadata
+ * - A source handler that concludes the runtime chain with the dispatch metadata
*/
export const createSelfReflectionSourcePolicyHandler = (
deps: CreateSelfReflectionSourceHandlerDependencies,
diff --git a/src/server/services/agentSignal/services/selfIteration/reflection/server.ts b/src/server/services/agentSignal/services/selfIteration/reflection/server.ts
index 9677a704608..7534c400a41 100644
--- a/src/server/services/agentSignal/services/selfIteration/reflection/server.ts
+++ b/src/server/services/agentSignal/services/selfIteration/reflection/server.ts
@@ -1,171 +1,21 @@
-import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
-
import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
-import { BriefModel } from '@/database/models/brief';
-import type { LobeChatDatabase } from '@/database/type';
-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';
-import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';
import {
createDurableSelfReflectionAccumulator,
createProcedurePolicyOptions,
} from '@/server/services/agentSignal/procedure';
import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';
import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';
-import { SkillManagementDocumentService } from '@/server/services/skillManagement';
-import { persistAgentSignalReceipts } from '../../receiptService';
import { createSelfReflectionService } from '../../selfReflection';
-import { executeSelfIteration } from '../execute';
-import { createSelfReviewProposalPreflightService } from '../review/proposalPreflight';
-import { createSelfReviewProposalSnapshotService } from '../review/proposalSnapshot';
import type { CreateServerSelfIterationPolicyOptions } from '../server';
-import { canRunSelfIterationSource, listServerSelfReviewProposalActivity } from '../server';
-import type {
- OperationReservation,
- ReplaceSkillContentCASInput,
- ToolReceiptInput,
- ToolWriteResult,
-} from '../tools/shared';
-import { createMemoryService, createSkillManagementService, createToolSet } from '../tools/shared';
-import { Risk } from '../types';
+import { canRunSelfIterationSource } from '../server';
import type {
CollectSelfReflectionContextInput,
CreateSelfReflectionSourceHandlerDependencies,
SelfReflectionReviewContext,
- SelfReflectionRuntimeFactory,
} from './handler';
-const SELF_REFLECTION_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;
-
-const selfReflectionOperationScopeKey = (idempotencyKey: string) =>
- `self-reflection-operation:${idempotencyKey}`;
-
-const selfReflectionOperationReserveKey = (idempotencyKey: string) =>
- `self-reflection-operation-reserve:${idempotencyKey}`;
-
-const parseStoredOperationResult = (
- payload: Record<string, string> | undefined,
-): ToolWriteResult | undefined => {
- if (!payload?.result) return;
-
- try {
- const result = JSON.parse(payload.result) as ToolWriteResult;
-
- if (
- result.status === 'applied' ||
- result.status === 'deduped' ||
- result.status === 'failed' ||
- result.status === 'proposed' ||
- result.status === 'skipped_stale' ||
- result.status === 'skipped_unsupported'
- ) {
- return result;
- }
- } catch {
- return;
- }
-};
-
-const reserveSelfReflectionOperation = async (
- idempotencyKey: string,
-): Promise<OperationReservation> => {
- const scopeKey = selfReflectionOperationScopeKey(idempotencyKey);
- const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));
-
- if (existing) return { existing, reserved: false };
-
- const reserved = await redisSourceEventStore.tryDedupe(
- selfReflectionOperationReserveKey(idempotencyKey),
- SELF_REFLECTION_OPERATION_STATE_TTL_SECONDS,
- );
-
- if (reserved) return { reserved: true };
-
- return {
- existing: parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ?? {
- status: 'skipped_unsupported',
- summary:
- 'Self-reflection operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',
- },
- reserved: false,
- };
-};
-
-const completeSelfReflectionOperation = async (input: ToolReceiptInput) => {
- await redisSourceEventStore.writeWindow(
- selfReflectionOperationScopeKey(input.idempotencyKey),
- {
- result: JSON.stringify({
- ...(input.receiptId ? { receiptId: input.receiptId } : {}),
- ...(input.resourceId ? { resourceId: input.resourceId } : {}),
- status: input.status,
- ...(input.summary ? { summary: input.summary } : {}),
- } satisfies ToolWriteResult),
- },
- SELF_REFLECTION_OPERATION_STATE_TTL_SECONDS,
- );
-};
-
-const getToolReceiptStatus = (
- status: ToolReceiptInput['status'],
-): 'applied' | 'failed' | 'proposed' | 'skipped' => {
- if (status === 'applied') return 'applied';
- if (status === 'failed') return 'failed';
- if (status === 'proposed') return 'proposed';
-
- return 'skipped';
-};
-
-const writeSelfReflectionToolReceipt = async ({
- agentId,
- input,
- sourceId,
- userId,
-}: {
- agentId: string;
- input: ToolReceiptInput;
- sourceId: string;
- userId: string;
-}) => {
- await persistAgentSignalReceipts([
- {
- agentId,
- createdAt: Date.now(),
- detail:
- input.summary ?? `Self-reflection tool ${input.toolName} finished with ${input.status}.`,
- id: input.idempotencyKey,
- kind:
- input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'
- ? 'skill'
- : 'review',
- metadata: {
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,
- },
- sourceId,
- sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,
- status: getToolReceiptStatus(input.status),
- ...(input.resourceId &&
- (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')
- ? {
- target: {
- id: input.resourceId,
- ...(input.summary ? { summary: input.summary } : {}),
- title: input.summary ?? input.resourceId,
- type: 'skill',
- },
- }
- : {}),
- title: input.summary ?? 'Self-reflection tool outcome',
- topicId: sourceId,
- userId,
- },
- ]);
-
- return { receiptId: input.idempotencyKey };
-};
-
const collectSelfReflectionContext = async (
reviewContextModel: AgentSignalReviewContextModel,
input: CollectSelfReflectionContextInput,
@@ -204,329 +54,25 @@ const collectSelfReflectionContext = async (
};
};
-const toReadonlyArray = (value: unknown): readonly unknown[] => (Array.isArray(value) ? value : []);
-
-const createReflectionEvidenceDigest = ({
- context,
- evidenceIds,
-}: {
- context: SelfReflectionReviewContext;
- evidenceIds?: string[];
-}) => {
- const selectedEvidenceIds = new Set(evidenceIds ?? []);
- const includeAll = selectedEvidenceIds.size === 0;
- const topics = toReadonlyArray(context.topics).filter((topic) => {
- if (includeAll) return true;
- if (!topic || typeof topic !== 'object') return false;
-
- const refs = 'evidenceRefs' in topic ? toReadonlyArray(topic.evidenceRefs) : [];
-
- return refs.some(
- (ref) =>
- ref &&
- typeof ref === 'object' &&
- 'id' in ref &&
- typeof ref.id === 'string' &&
- selectedEvidenceIds.has(ref.id),
- );
- });
-
- return {
- evidenceRefs: context.evidenceRefs,
- scope: {
- id: context.scopeId,
- type: context.scopeType,
- },
- topics,
- };
-};
-
-const createReflectionRuntimeTools = ({
- agentId,
- briefModel,
- context,
- db,
- skillDocumentService,
- sourceId,
- userId,
-}: {
- agentId: string;
- briefModel: BriefModel;
- context: SelfReflectionReviewContext;
- db: LobeChatDatabase;
- skillDocumentService: SkillManagementDocumentService;
- sourceId: string;
- userId: string;
-}) => {
- const proposalPreflight = createSelfReviewProposalPreflightService({
- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
-
- return !skills.some((skill) => skill.name === name);
- },
- readSkillTargetSnapshot: (skillDocumentId) =>
- skillDocumentService.readSkillTargetSnapshot({
- agentDocumentId: skillDocumentId,
- agentId,
- }),
- });
- const proposalSnapshot = createSelfReviewProposalSnapshotService({
- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
-
- return !skills.some((skill) => skill.name === name);
- },
- readSkillTargetSnapshot: (skillDocumentId) =>
- skillDocumentService.readSkillTargetSnapshot({
- agentDocumentId: skillDocumentId,
- agentId,
- }),
- });
- const skillService = createSkillManagementService({
- createSkill: async ({ input }) => {
- const result = await skillDocumentService.createSkill({
- agentId,
- bodyMarkdown: input.bodyMarkdown ?? '',
- description: input.description ?? 'Agent Signal managed skill.',
- name: input.name ?? input.title ?? 'agent-signal-skill',
- title: input.title ?? input.name ?? 'Agent Signal skill',
- });
-
- return {
- skillDocumentId: result.bundle.agentDocumentId,
- summary: `Created managed skill ${result.name}.`,
- };
- },
- refineSkill: async ({ input }) => {
- const result = await skillDocumentService.replaceSkillIndex({
- agentDocumentId: input.skillDocumentId,
- agentId,
- bodyMarkdown: input.bodyMarkdown ?? '',
- });
-
- if (!result) throw new Error('Skill target not found');
-
- return {
- skillDocumentId: result.bundle.agentDocumentId,
- summary: `Refined managed skill ${result.name}.`,
- };
- },
- });
-
- return createToolSet({
- completeOperation: completeSelfReflectionOperation,
- completeReplaceSkillInput: async (input: ReplaceSkillContentCASInput) => {
- const baseSnapshot = await proposalSnapshot.captureActionSnapshot({
- actionType: 'refine_skill',
- agentId,
- input: { skillDocumentId: input.skillDocumentId },
- userId,
- });
-
- return {
- ...input,
- baseSnapshot,
- skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,
- };
- },
- createSkill: async (input) => {
- const result = await skillService.createSkill({
- evidenceRefs: [],
- idempotencyKey: input.idempotencyKey,
- input,
- });
-
- return {
- resourceId: result.skillDocumentId,
- summary: result.summary,
- };
- },
- getEvidenceDigest: async ({ evidenceIds }) =>
- createReflectionEvidenceDigest({ context, evidenceIds }),
- getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>
- skillDocumentService.getSkill({
- agentDocumentId: skillDocumentId,
- agentId: targetAgentId,
- includeContent: true,
- }),
- listSelfReviewProposals: ({ agentId: targetAgentId }) =>
- listServerSelfReviewProposalActivity({
- agentId: targetAgentId,
- briefModel,
- userId,
- }).then((digest) => [digest]),
- listManagedSkills: ({ agentId: targetAgentId }) =>
- skillDocumentService.listSkills({ agentId: targetAgentId }),
- preflight: async (input) => {
- if ('skillDocumentId' in input) {
- const preflight = await proposalPreflight.checkAction({
- actionType: 'refine_skill',
- baseSnapshot: input.baseSnapshot,
- evidenceRefs: [],
- idempotencyKey: input.idempotencyKey,
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: input.bodyMarkdown,
- patch: input.summary,
- skillDocumentId: input.skillDocumentId,
- userId: input.userId,
- },
- operation: 'refine',
- },
- rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,
- risk: Risk.Low,
- target: { skillDocumentId: input.skillDocumentId },
- });
-
- return preflight.allowed ? { allowed: true } : { allowed: false, reason: preflight.reason };
- }
-
- return { allowed: true };
- },
- readProposal: async ({ proposalId, proposalKey }) => {
- const digest = await listServerSelfReviewProposalActivity({ agentId, briefModel, userId });
-
- return digest.active.find(
- (proposal) =>
- (proposalId && proposal.proposalId === proposalId) ||
- (proposalKey && proposal.proposalKey === proposalKey),
- );
- },
- replaceSkill: async (input) => {
- const result = await skillService.refineSkill({
- evidenceRefs: [],
- idempotencyKey: input.idempotencyKey,
- input,
- });
-
- return {
- resourceId: result.skillDocumentId,
- summary: result.summary,
- };
- },
- reserveOperation: reserveSelfReflectionOperation,
- writeMemory: async (input) => {
- const memoryService = createMemoryService({
- writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
- const result = await runMemoryActionAgent(
- {
- agentId,
- message: content,
- reason: `Agent Signal self-reflection memory candidate from ${evidenceRefs.length} evidence refs.`,
- },
- {
- db,
- userId,
- },
- );
-
- if (result.status !== 'applied') {
- throw new Error(
- result.detail ?? 'Memory action agent did not apply a durable memory write.',
- );
- }
-
- return {
- memoryId: idempotencyKey,
- summary: result.detail ?? content,
- };
- },
- });
- const result = await memoryService.writeMemory({
- evidenceRefs: input.evidenceRefs,
- idempotencyKey: input.idempotencyKey,
- input: {
- content: input.content,
- userId: input.userId,
- },
- });
-
- return {
- resourceId: result.memoryId,
- summary: result.summary,
- };
- },
- writeReceipt: (input) => writeSelfReflectionToolReceipt({ agentId, input, sourceId, userId }),
- });
-};
-
-/**
- * Creates source-scoped runtime dependencies for server self-reflection runs.
- *
- * Call stack:
- *
- * createServerSelfReflectionPolicyOptions
- * -> {@link SelfReflectionServerRuntimeFactory.createRuntime}
- * -> {@link executeSelfIteration}
- * -> self-reflection tools and receipt persistence
- *
- * Use when:
- * - The Agent Signal workflow consumes `agent.self_reflection.requested`
- * - Reflection needs source-scoped evidence tools rather than nightly brief proposal tools
- *
- * Expects:
- * - `context` was collected for the same source payload
- * - Tools are scoped to one user/agent/source id
- *
- * Returns:
- * - Model runtime, toolset, and executor callback for one reflection run
- */
-export class SelfReflectionServerRuntimeFactory implements SelfReflectionRuntimeFactory {
- constructor(
- private readonly input: {
- agentId: string;
- briefModel: BriefModel;
- db: LobeChatDatabase;
- skillDocumentService: SkillManagementDocumentService;
- userId: string;
- },
- ) {}
-
- async createRuntime({
- context,
- source,
- }: Parameters<SelfReflectionRuntimeFactory['createRuntime']>[0]) {
- const modelRuntime = await initModelRuntimeFromDB(
- this.input.db,
- this.input.userId,
- DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
- );
-
- return {
- executeSelfIteration,
- model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,
- modelRuntime,
- tools: createReflectionRuntimeTools({
- agentId: this.input.agentId,
- briefModel: this.input.briefModel,
- context,
- db: this.input.db,
- skillDocumentService: this.input.skillDocumentService,
- sourceId: source.sourceId,
- userId: this.input.userId,
- }),
- };
- }
-}
-
/**
- * Creates server runtime handlers for immediate self-feedback reflection sources.
+ * Creates server self-reflection policy options for the Agent Signal workflow.
*
* Call stack:
*
* runAgentSignalWorkflow
* -> {@link createServerSelfReflectionPolicyOptions}
* -> reflection source handler dependencies
- * -> {@link SelfReflectionServerRuntimeFactory}
+ * -> {@link enqueueSelfIterationRun} (async execAgent under the builtin slug)
*
- * Use when:
- * - The Agent Signal workflow consumes `agent.self_reflection.requested`
- * - Runtime policy composition needs scoped collection, self-iteration executor, and receipts
+ * The handler only gates, dedupes, collects bounded evidence, and dispatches an
+ * async run. The self-iteration tools (resource skill/memory writes + artifact
+ * recorders) are resolved server-side from `plugins: ['agent-signal-reflection']`
+ * by the builtin self-reflection agent's serverRuntime — there is no inline
+ * model runtime, toolset, or receipt writer here anymore.
*
* Expects:
* - The source was emitted by the self-reflection request service
- * - The handler will re-check gates and idempotency before reviewer work
+ * - The handler will re-check gates and idempotency before dispatch
*
* Returns:
* - Self-reflection handler options ready for `createDefaultAgentSignalPolicies`
@@ -538,9 +84,6 @@ export const createServerSelfReflectionPolicyOptions = ({
userId,
}: CreateServerSelfIterationPolicyOptions): CreateSelfReflectionSourceHandlerDependencies => {
const reviewContextModel = new AgentSignalReviewContextModel(db, userId);
- const briefModel = new BriefModel(db, userId);
- const skillDocumentService = new SkillManagementDocumentService(db, userId);
- const targetAgentId = agentId ?? '';
return {
acquireReviewGuard: (input) =>
@@ -559,15 +102,7 @@ export const createServerSelfReflectionPolicyOptions = ({
});
},
collectContext: (input) => collectSelfReflectionContext(reviewContextModel, input),
- runtimeFactory: new SelfReflectionServerRuntimeFactory({
- agentId: targetAgentId,
- briefModel,
- db,
- skillDocumentService,
- userId,
- }),
- writeReceipt: async () => {},
- writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),
+ db,
};
};
diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
index 56fa7488c4f..25c970fd5df 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
@@ -2,6 +2,7 @@
import { createSource } from '@lobechat/agent-signal';
import type { SourceAgentNightlyReviewRequested } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { describe, expect, it, vi } from 'vitest';
import { createDefaultAgentSignalPolicies } from '../../../../policies';
@@ -10,16 +11,15 @@ import type {
AgentSignalSignalHandlerDefinition,
AgentSignalSourceHandlerDefinition,
} from '../../../../runtime/middleware';
-import type { AgentRunResult } from '../../execute';
-import type { Plan, RunResult } from '../../types';
-import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../../types';
+import { ReviewRunStatus } from '../../types';
import type { NightlyReviewContext } from '../collect';
import type { CreateNightlyReviewSourceHandlerDependencies } from '../handler';
import {
createNightlyReviewSourceHandler,
createNightlyReviewSourcePolicyHandler,
} from '../handler';
-import type { SelfReviewProposalPlan } from '../proposal';
+
+const reviewSourceId = 'nightly-review:user-1:agent-1:2026-05-04';
const reviewPayload = {
agentId: 'agent-1',
@@ -39,7 +39,7 @@ const createReviewSource = (
payload,
scope: { agentId: 'agent-1', userId: 'user-1' },
scopeKey: 'agent:agent-1',
- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
+ sourceId: reviewSourceId,
sourceType,
timestamp: 100,
}) as SourceAgentNightlyReviewRequested;
@@ -83,71 +83,19 @@ const reviewContext = {
userId: 'user-1',
} satisfies NightlyReviewContext;
-const reviewPlan = {
- actions: [
- {
- actionType: 'noop',
- applyMode: ApplyMode.Skip,
- confidence: 0.9,
- dedupeKey: 'noop:quiet',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',
- rationale: 'No self-iteration needed.',
- risk: Risk.Low,
- },
- ],
- localDate: reviewPayload.localDate,
- plannerVersion: 'test-planner',
- reviewScope: Scope.Nightly,
- summary: 'Quiet night.',
-} satisfies Plan;
-
-const executionResult = {
- actions: [
- {
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',
- status: ActionStatus.Skipped,
- summary: 'No self-iteration needed.',
- },
- ],
- status: ReviewRunStatus.Completed,
-} satisfies RunResult;
-
-const reviewAgentResult = {
- execution: executionResult,
- projectionPlan: reviewPlan,
- stepCount: 1,
-} satisfies AgentRunResult;
-
-const zhCNBriefText = {
- 'brief.agentSignal.selfReview.proposal.heading': '建议',
- 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条夜间回顾建议需要你确认。',
- 'brief.agentSignal.selfReview.proposal.summary_plural': '有 {{count}} 条夜间回顾建议需要你确认。',
- 'brief.agentSignal.selfReview.proposal.title': '有夜间回顾建议需要确认',
-};
-
-const t = (key: string, options: Record<string, string> = {}) =>
- Object.entries(options).reduce(
- (content, [name, value]) => content.replace(`{{${name}}}`, value),
- zhCNBriefText[key as keyof typeof zhCNBriefText] ?? key,
- );
-
const createDependencies = (
overrides: Partial<CreateNightlyReviewSourceHandlerDependencies> = {},
): CreateNightlyReviewSourceHandlerDependencies => ({
acquireReviewGuard: vi.fn(async () => true),
canRunReview: vi.fn(async () => true),
collectContext: vi.fn(async () => reviewContext),
- runSelfReviewAgent: vi.fn(async () => reviewAgentResult),
+ db: {} as never,
+ dispatch: vi.fn(async () => ({ operationId: 'op-nightly-1', topicId: 'tpc-nightly-1' })),
...overrides,
});
describe('nightly review source handler', () => {
- /**
- * @example
- * expect(result.status).toBe('completed');
- */
- it('orchestrates collector and bounded agent runner for a valid nightly source', async () => {
+ it('collects context then dispatches an async run under the builtin nightly-review slug', async () => {
const deps = createDependencies();
const handler = createNightlyReviewSourceHandler(deps);
@@ -156,13 +104,13 @@ describe('nightly review source handler', () => {
expect(deps.canRunReview).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'agent-1',
- guardKey: 'nightly-review:user-1:agent-1:2026-05-04',
+ guardKey: reviewSourceId,
localDate: '2026-05-04',
userId: 'user-1',
}),
);
expect(deps.acquireReviewGuard).toHaveBeenCalledWith(
- expect.objectContaining({ guardKey: 'nightly-review:user-1:agent-1:2026-05-04' }),
+ expect.objectContaining({ guardKey: reviewSourceId }),
);
expect(deps.collectContext).toHaveBeenCalledWith({
agentId: 'agent-1',
@@ -170,378 +118,40 @@ describe('nightly review source handler', () => {
reviewWindowStart: reviewPayload.reviewWindowStart,
userId: 'user-1',
});
- expect(deps.runSelfReviewAgent).toHaveBeenCalledWith({
- context: reviewContext,
- localDate: '2026-05-04',
- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
- userId: 'user-1',
- });
- expect(result).toEqual(
+ expect(deps.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'agent-1',
- execution: expect.objectContaining({ status: executionResult.status }),
- plannedActionCount: 1,
- planSummary: 'Quiet night.',
- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
- status: ReviewRunStatus.Completed,
+ db: deps.db,
+ // The review window + local date ride on the marker so the builtin
+ // agent-signal-review serverRuntime can re-derive them.
+ marker: {
+ agentId: 'agent-1',
+ kind: 'nightly-review',
+ localDate: '2026-05-04',
+ reviewWindowEnd: reviewPayload.reviewWindowEnd,
+ reviewWindowStart: reviewPayload.reviewWindowStart,
+ sourceId: reviewSourceId,
+ },
+ prompt: expect.stringContaining(reviewSourceId),
+ slug: BUILTIN_AGENT_SLUGS.nightlyReview,
userId: 'user-1',
}),
);
- });
-
- /**
- * @example
- * expect(deps.writeReceipts).toHaveBeenCalledBefore(deps.writeDailyBrief).
- */
- it('writes review receipts before creating an eligible nightly brief', async () => {
- const calls: string[] = [];
- const deps = createDependencies({
- runSelfReviewAgent: vi.fn(async () => ({
- execution: {
- actions: [
- {
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
- status: ActionStatus.Proposed,
- summary: 'Review the skill refinement proposal.',
- },
- ],
- status: ReviewRunStatus.Completed,
- },
- projectionPlan: {
- ...reviewPlan,
- actions: [
- {
- ...reviewPlan.actions[0],
- actionType: 'refine_skill',
- applyMode: ApplyMode.ProposalOnly,
- baseSnapshot: {
- agentDocumentId: 'skill-doc-1',
- contentHash: 'sha256:workflow-summary',
- documentId: 'doc-skill-doc-1',
- managed: true,
- targetType: 'skill',
- writable: true,
- },
- dedupeKey: 'refine_skill:skill-doc-1',
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: 'Use the updated workflow summary wording.',
- skillDocumentId: 'skill-doc-1',
- userId: 'user-1',
- },
- operation: 'refine',
- },
- rationale: 'Review the skill refinement proposal.',
- risk: Risk.Medium,
- target: { skillDocumentId: 'skill-doc-1' },
- },
- ],
- } satisfies SelfReviewProposalPlan,
- })),
- resolveBriefTextTranslator: vi.fn(async () => t),
- writeDailyBrief: vi.fn(async () => {
- calls.push('brief');
-
- return { id: 'brief-1' };
- }),
- writeReceipts: vi.fn(async () => {
- calls.push('receipts');
- }),
- });
- const handler = createNightlyReviewSourceHandler(deps);
-
- const result = await handler.handle(createReviewSource());
-
- expect(calls).toEqual(['receipts', 'brief']);
- expect(deps.writeReceipts).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),
- expect.objectContaining({
- id: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1:action',
- }),
- ]);
- expect(deps.writeDailyBrief).toHaveBeenCalledWith(
+ expect(result).toEqual(
expect.objectContaining({
agentId: 'agent-1',
- metadata: expect.objectContaining({
- agentSignal: expect.objectContaining({
- nightlySelfReview: expect.objectContaining({
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- selfReviewProposal: expect.objectContaining({
- actions: [
- expect.objectContaining({
- actionType: 'refine_skill',
- baseSnapshot: expect.objectContaining({
- contentHash: 'sha256:workflow-summary',
- }),
- operation: expect.objectContaining({
- domain: 'skill',
- input: expect.objectContaining({
- bodyMarkdown: 'Use the updated workflow summary wording.',
- }),
- operation: 'refine',
- }),
- }),
- ],
- }),
- }),
- }),
- }),
- summary: expect.stringContaining('有 1 条夜间回顾建议需要你确认。'),
- title: '有夜间回顾建议需要确认',
- trigger: 'agent-signal:nightly-review',
- type: 'decision',
- }),
- );
- expect(result.execution).toEqual(
- expect.objectContaining({
- briefId: 'brief-1',
- summaryReceiptId: 'nightly-review:user-1:agent-1:2026-05-04:review-summary',
- }),
- );
- });
-
- /**
- * @example
- * expect(deps.writeDailyBrief).toHaveBeenCalledWith(expect.objectContaining({ type: 'insight' }));
- */
- it('creates an insight brief for auto-applied nightly shared', async () => {
- const deps = createDependencies({
- runSelfReviewAgent: vi.fn(async () => ({
- execution: {
- actions: [
- {
- idempotencyKey:
- 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',
- resourceId: 'mem-1',
- status: ActionStatus.Applied,
- summary: 'Saved concise release summary preference.',
- },
- ],
- status: ReviewRunStatus.Completed,
- },
- projectionPlan: {
- ...reviewPlan,
- actions: [
- {
- ...reviewPlan.actions[0],
- actionType: 'write_memory',
- applyMode: ApplyMode.AutoApply,
- dedupeKey: 'memory:concise',
- idempotencyKey:
- 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',
- operation: {
- domain: 'memory',
- input: {
- content: 'User prefers concise release summaries.',
- userId: 'user-1',
- },
- operation: 'write',
- },
- rationale: 'The user stated a durable release summary preference.',
- risk: Risk.Low,
- target: { topicIds: ['topic-1'] },
- },
- ],
- } satisfies Plan,
- })),
- writeDailyBrief: vi.fn(async () => ({ id: 'brief-insight-1' })),
- writeReceipts: vi.fn(async () => {}),
- });
- const handler = createNightlyReviewSourceHandler(deps);
-
- const result = await handler.handle(createReviewSource());
-
- expect(deps.writeReceipts).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),
- expect.objectContaining({
- id: 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise:action',
- }),
- ]);
- expect(deps.writeDailyBrief).toHaveBeenCalledWith(
- expect.objectContaining({
- metadata: expect.objectContaining({
- agentSignal: expect.objectContaining({
- nightlySelfReview: expect.objectContaining({
- actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
- outcome: 'applied',
- }),
- }),
- }),
- title: 'Dream updated resources',
- trigger: 'agent-signal:nightly-review',
- type: 'insight',
- }),
- );
- expect(result.execution).toEqual(
- expect.objectContaining({
- briefId: 'brief-insight-1',
- }),
- );
- });
-
- /**
- * @example
- * expect(deps.writeDailyBrief).not.toHaveBeenCalled();
- */
- it('keeps skipped noop reviews silent after writing the summary receipt', async () => {
- const deps = createDependencies({
- writeDailyBrief: vi.fn(async () => ({ id: 'brief-1' })),
- writeReceipts: vi.fn(async () => {}),
- });
- const handler = createNightlyReviewSourceHandler(deps);
-
- const result = await handler.handle(createReviewSource());
-
- expect(deps.writeReceipts).toHaveBeenCalledWith([
- expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),
- ]);
- expect(deps.writeDailyBrief).not.toHaveBeenCalled();
- expect(result.execution).toEqual(
- expect.not.objectContaining({
- briefId: expect.any(String),
- }),
- );
- });
-
- /**
- * @example
- * expect(brief.metadata.agentSignal.nightlySelfReview.selfReviewProposal.actions[0].operation).toBeDefined();
- */
- it('projects frozen proposal action operations from the runner projection plan', async () => {
- const proposedSkillPlan = {
- ...reviewPlan,
- actions: [
- {
- ...reviewPlan.actions[0],
- actionType: 'refine_skill',
- applyMode: ApplyMode.ProposalOnly,
- baseSnapshot: {
- agentDocumentId: 'skill-doc-1',
- contentHash: 'sha256:workflow-summary',
- documentId: 'doc-skill-doc-1',
- managed: true,
- targetType: 'skill',
- writable: true,
- },
- dedupeKey: 'refine_skill:skill-doc-1',
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: 'Use the newer workflow summary wording.',
- skillDocumentId: 'skill-doc-1',
- userId: 'user-1',
- },
- operation: 'refine',
- },
- rationale: 'Review the workflow summary skill refinement.',
- risk: Risk.Medium,
- target: { skillDocumentId: 'skill-doc-1' },
- },
- ],
- } satisfies SelfReviewProposalPlan;
- const deps = createDependencies({
- runSelfReviewAgent: vi.fn(async () => ({
- execution: {
- actions: [
- {
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
- status: ActionStatus.Proposed,
- summary: 'Refine the workflow summary skill.',
- },
- ],
- status: ReviewRunStatus.Completed,
- },
- projectionPlan: proposedSkillPlan,
- })),
- writeDailyBrief: vi.fn(async () => ({ id: 'brief-1' })),
- writeReceipts: vi.fn(async () => {}),
- });
- const handler = createNightlyReviewSourceHandler(deps);
-
- await handler.handle(createReviewSource());
-
- expect(deps.writeDailyBrief).toHaveBeenCalledWith(
- expect.objectContaining({
- metadata: expect.objectContaining({
- agentSignal: expect.objectContaining({
- nightlySelfReview: expect.objectContaining({
- selfReviewProposal: expect.objectContaining({
- actions: [
- expect.objectContaining({
- actionType: 'refine_skill',
- operation: expect.objectContaining({
- domain: 'skill',
- operation: 'refine',
- }),
- }),
- ],
- }),
- }),
- }),
- }),
+ localDate: '2026-05-04',
+ operationId: 'op-nightly-1',
+ sourceId: reviewSourceId,
+ status: ReviewRunStatus.Dispatched,
+ userId: 'user-1',
}),
);
});
- /**
- * @example
- * expect(result.briefWriteFailed).toBe(true);
- */
- it('keeps nightly runs completed when brief creation fails after receipts', async () => {
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
- const briefError = new Error('brief store unavailable');
+ it('returns skipped without acquiring the guard when gates reject the review', async () => {
const deps = createDependencies({
- runSelfReviewAgent: vi.fn(async () => ({
- execution: {
- actions: [
- {
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
- status: ActionStatus.Proposed,
- summary: 'Review the skill refinement proposal.',
- },
- ],
- status: ReviewRunStatus.Completed,
- },
- projectionPlan: {
- ...reviewPlan,
- actions: [
- {
- ...reviewPlan.actions[0],
- actionType: 'refine_skill',
- applyMode: ApplyMode.ProposalOnly,
- baseSnapshot: {
- agentDocumentId: 'skill-doc-1',
- contentHash: 'sha256:workflow-summary',
- documentId: 'doc-skill-doc-1',
- managed: true,
- targetType: 'skill',
- writable: true,
- },
- dedupeKey: 'refine_skill:skill-doc-1',
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: 'Use the updated workflow summary wording.',
- skillDocumentId: 'skill-doc-1',
- userId: 'user-1',
- },
- operation: 'refine',
- },
- rationale: 'Review the skill refinement proposal.',
- risk: Risk.Medium,
- target: { skillDocumentId: 'skill-doc-1' },
- },
- ],
- } satisfies SelfReviewProposalPlan,
- })),
- writeDailyBrief: vi.fn(async () => {
- throw briefError;
- }),
- writeReceipts: vi.fn(async () => {}),
+ canRunReview: vi.fn(async () => false),
});
const handler = createNightlyReviewSourceHandler(deps);
@@ -549,22 +159,16 @@ describe('nightly review source handler', () => {
expect(result).toEqual(
expect.objectContaining({
- briefWriteFailed: true,
- status: ReviewRunStatus.Completed,
+ reason: 'gate_disabled',
+ status: ReviewRunStatus.Skipped,
}),
);
- expect(consoleError).toHaveBeenCalledWith(
- '[AgentSignal] Failed to write nightly review brief:',
- briefError,
- );
- consoleError.mockRestore();
+ expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
+ expect(deps.collectContext).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.status).toBe('deduped');
- */
- it('returns deduped without collecting when the review guard is already held', async () => {
+ it('returns deduped without collecting or dispatching when the review guard is held', async () => {
const deps = createDependencies({
acquireReviewGuard: vi.fn(async () => false),
});
@@ -574,47 +178,19 @@ describe('nightly review source handler', () => {
expect(result).toEqual(
expect.objectContaining({
- guardKey: 'nightly-review:user-1:agent-1:2026-05-04',
+ guardKey: reviewSourceId,
status: ReviewRunStatus.Deduped,
}),
);
expect(deps.collectContext).not.toHaveBeenCalled();
- expect(deps.runSelfReviewAgent).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('gate_disabled');
- */
- it('returns skipped without acquiring the guard when gates reject the review', async () => {
- const deps = createDependencies({
- canRunReview: vi.fn(async () => false),
- });
- const handler = createNightlyReviewSourceHandler(deps);
-
- const result = await handler.handle(createReviewSource());
-
- expect(result).toEqual(
- expect.objectContaining({
- reason: 'gate_disabled',
- status: ReviewRunStatus.Skipped,
- }),
- );
- expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
- expect(deps.collectContext).not.toHaveBeenCalled();
- });
-
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
it('returns skipped invalid without throwing for invalid payloads', async () => {
const deps = createDependencies();
const handler = createNightlyReviewSourceHandler(deps);
- const result = await handler.handle(
- createReviewSource({ agentId: 'agent-1', userId: 'user-1' }),
- );
+ const result = await handler.handle(createReviewSource({ agentId: 'agent-1', userId: 'user-1' }));
expect(result).toEqual(
expect.objectContaining({
@@ -623,15 +199,10 @@ describe('nightly review source handler', () => {
}),
);
expect(deps.canRunReview).not.toHaveBeenCalled();
- expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
- expect(deps.collectContext).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(result.reason).toBe('invalid_payload');
- */
- it('returns skipped invalid when source id does not match the nightly guard key', async () => {
+ it('returns skipped invalid when source id does not match the expected nightly key', async () => {
const deps = createDependencies();
const handler = createNightlyReviewSourceHandler(deps);
@@ -639,9 +210,9 @@ describe('nightly review source handler', () => {
...createReviewSource(),
sourceId: 'nightly-review:user-1:agent-1:wrong-date',
} satisfies SourceAgentNightlyReviewRequested;
- const mismatchedResult = await handler.handle(mismatchedSource);
+ const result = await handler.handle(mismatchedSource);
- expect(mismatchedResult).toEqual(
+ expect(result).toEqual(
expect.objectContaining({
reason: 'invalid_payload',
sourceId: 'nightly-review:user-1:agent-1:wrong-date',
@@ -649,15 +220,10 @@ describe('nightly review source handler', () => {
}),
);
expect(deps.canRunReview).not.toHaveBeenCalled();
- expect(deps.acquireReviewGuard).not.toHaveBeenCalled();
- expect(deps.collectContext).not.toHaveBeenCalled();
+ expect(deps.dispatch).not.toHaveBeenCalled();
});
- /**
- * @example
- * expect(sourceHandlers[0].listen).toBe('agent.nightly_review.requested');
- */
- it('installs an optional nightly source policy through default policy composition', async () => {
+ it('installs an optional nightly review source policy through default policy composition', async () => {
const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];
const deps = createDependencies();
const policies = createDefaultAgentSignalPolicies({
@@ -666,7 +232,7 @@ describe('nightly review source handler', () => {
judgeSatisfaction: async () => ({
confidence: 1,
evidence: [],
- reason: 'No feedback in nightly registration test.',
+ reason: 'No feedback in nightly review registration test.',
result: 'neutral',
}),
},
@@ -688,76 +254,36 @@ describe('nightly review source handler', () => {
});
}
- const nightlyHandler = sourceHandlers.find(
+ const nightlyReviewHandler = sourceHandlers.find(
(handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,
);
- expect(nightlyHandler).toEqual(
+ expect(nightlyReviewHandler).toEqual(
expect.objectContaining({
id: `${AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested}:shared-review`,
type: 'source',
}),
);
- const runtimeResult = await nightlyHandler?.handle(createReviewSource(), {
+ const runtimeResult = await nightlyReviewHandler?.handle(createReviewSource(), {
now: () => 100,
+ runtimeState: {
+ getGuardState: async () => ({}),
+ touchGuardState: async () => ({}),
+ },
scopeKey: 'agent:agent-1',
- } as never);
+ });
expect(runtimeResult).toEqual(
expect.objectContaining({
- concluded: expect.objectContaining({ status: ReviewRunStatus.Completed }),
+ concluded: expect.objectContaining({ status: ReviewRunStatus.Dispatched }),
status: 'conclude',
}),
);
});
-
- /**
- * @example
- * expect(nightlyHandler).toBeUndefined();
- */
- it('does not install nightly source handlers without nightly review dependencies', async () => {
- const sourceHandlers: AgentSignalSourceHandlerDefinition[] = [];
- const policies = createDefaultAgentSignalPolicies({
- feedbackSatisfactionJudge: {
- judge: {
- judgeSatisfaction: async () => ({
- confidence: 1,
- evidence: [],
- reason: 'No feedback in nightly registration test.',
- result: 'neutral',
- }),
- },
- },
- });
-
- for (const policy of policies) {
- await policy.install({
- handleAction(handler: AgentSignalActionHandlerDefinition) {
- expect(handler.type).toBe('action');
- },
- handleSignal(handler: AgentSignalSignalHandlerDefinition) {
- expect(handler.type).toBe('signal');
- },
- handleSource(handler) {
- sourceHandlers.push(handler);
- },
- });
- }
-
- const nightlyHandler = sourceHandlers.find(
- (handler) => handler.listen === AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,
- );
-
- expect(nightlyHandler).toBeUndefined();
- });
});
describe('nightly review source policy handler', () => {
- /**
- * @example
- * expect(handler.listen).toBe('agent.nightly_review.requested');
- */
it('listens to the nightly review requested source type', () => {
const handler = createNightlyReviewSourcePolicyHandler(createDependencies());
diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
index a083ea91aaf..76609ea119b 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
@@ -1,730 +1,55 @@
// @vitest-environment node
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
-import type { BriefItem } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
-import type * as SkillManagementModule from '@/server/services/skillManagement';
-import type * as ToolFirstRuntimeModule from '../../execute';
-import { listServerSelfReviewProposalActivity } from '../../server';
-import { ActionStatus, ReviewRunStatus } from '../../types';
-import type { NightlyReviewContext } from '../collect';
-import { createServerSelfReviewPolicyOptions } from '../server';
+import { createReviewRuntimePrimitives, createServerSelfReviewPolicyOptions } from '../server';
-const mocks = vi.hoisted(() => ({
- briefCreate: vi.fn(),
- briefListUnresolvedByAgentAndTrigger: vi.fn(async () => []),
- briefUpdateMetadata: vi.fn(),
- initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),
- executeSelfIteration: vi.fn(),
- skillReadTargetSnapshot: vi.fn(),
- skillReplaceSkillIndex: vi.fn(),
- translation: vi.fn(async () => ({
- locale: 'zh-CN',
- t: (key: string, options: Record<string, string> = {}) => {
- const resources: Record<string, string> = {
- 'brief.agentSignal.selfReview.proposal.heading': '建议',
- 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条助理建议需要你确认。',
- 'brief.agentSignal.selfReview.proposal.summary_plural':
- '有 {{count}} 条助理建议需要你确认。',
- 'brief.agentSignal.selfReview.proposal.title': '有助理建议需要确认',
- };
-
- return Object.entries(options).reduce(
- (content, [name, value]) => content.replace(`{{${name}}}`, value),
- resources[key] ?? key,
- );
- },
- })),
- userGetInfoForAIGeneration: vi.fn(async () => ({
- responseLanguage: 'zh-CN',
- userName: 'User',
- })),
-}));
-
-vi.mock('@/server/modules/ModelRuntime', () => ({
- initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
-}));
-
-vi.mock('../../execute', async (importOriginal) => ({
- ...(await importOriginal<typeof ToolFirstRuntimeModule>()),
- executeSelfIteration: mocks.executeSelfIteration,
-}));
-
-vi.mock('@/database/models/agentSignal/nightlyReview', () => ({
- AgentSignalNightlyReviewModel: class {
- listActiveAgentTargets = vi.fn(async () => []);
- },
-}));
-
-vi.mock('@/database/models/agentSignal/reviewContext', () => ({
- AgentSignalReviewContextModel: class {
- canAgentRunSelfIteration = vi.fn(async () => true);
- listDocumentActivity = vi.fn(async () => []);
- listRelevantMemories = vi.fn(async () => []);
- listToolActivity = vi.fn(async () => []);
- listTopicActivity = vi.fn(async () => []);
- },
-}));
-
-vi.mock('@/database/models/brief', () => ({
- BriefModel: class {
- create = mocks.briefCreate;
- listUnresolvedByAgentAndTrigger = mocks.briefListUnresolvedByAgentAndTrigger;
- updateMetadata = mocks.briefUpdateMetadata;
- },
-}));
-
-vi.mock('@/database/models/user', () => ({
- UserModel: {
- getInfoForAIGeneration: mocks.userGetInfoForAIGeneration,
- },
-}));
-
-vi.mock('@/server/translation', () => ({
- translation: mocks.translation,
-}));
-
-vi.mock('@/server/services/skillManagement', async (importOriginal) => ({
- ...(await importOriginal<typeof SkillManagementModule>()),
- SkillManagementDocumentService: class {
- createSkill = vi.fn();
- getSkill = vi.fn();
- listSkills = vi.fn(async () => []);
- readSkillTargetSnapshot = mocks.skillReadTargetSnapshot;
- replaceSkillIndex = mocks.skillReplaceSkillIndex;
- },
-}));
-
-vi.mock('@/server/services/agentSignal/featureGate', () => ({
- isAgentSignalEnabledForUser: vi.fn(async () => true),
-}));
-
-const baseBrief = (overrides: Partial<BriefItem>): BriefItem => ({
- actions: null,
- agentId: 'agent-1',
- artifacts: null,
- createdAt: new Date('2026-05-09T00:00:00.000Z'),
- cronJobId: null,
- id: 'brief-1',
- metadata: null,
- priority: 'normal',
- readAt: null,
- resolvedAction: null,
- resolvedAt: null,
- resolvedComment: null,
- summary: 'Proposal summary',
- taskId: null,
- title: 'Proposal',
- topicId: null,
- trigger: 'agent-signal:nightly-review',
- type: 'decision',
- userId: 'user-1',
- ...overrides,
-});
-
-const proposalMetadata = (
- overrides: Record<string, unknown> = {},
-): NonNullable<BriefItem['metadata']> => ({
- agentSignal: {
- nightlySelfReview: {
- selfReviewProposal: {
- actionType: 'refine_skill',
- actions: [
- {
- actionType: 'refine_skill',
- baseSnapshot: { targetTitle: 'Skill Index' },
- evidenceRefs: [
- { id: 'topic-1', type: 'topic' },
- { id: 'message-1', type: 'message' },
- ],
- idempotencyKey: 'source:refine_skill:skill:adoc-1',
- rationale: 'Refine the skill.',
- risk: 'medium',
- target: { skillDocumentId: 'adoc-1' },
- },
- ],
- createdAt: '2026-05-09T00:00:00.000Z',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- evidenceWindowEnd: '2026-05-09T02:00:00.000Z',
- evidenceWindowStart: '2026-05-09T00:00:00.000Z',
- expiresAt: '2026-05-12T00:00:00.000Z',
- proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',
- status: 'pending',
- updatedAt: '2026-05-09T01:00:00.000Z',
- version: 1,
- ...overrides,
- },
- },
- },
-});
-
-const createNightlyContext = (): NightlyReviewContext => ({
+const baseGuardInput = {
agentId: 'agent-1',
- documentActivity: {
- ambiguousBucket: [],
- excludedSummary: { count: 0, reasons: [] },
- generalDocumentBucket: [],
- skillBucket: [],
- },
- feedbackActivity: {
- neutralCount: 0,
- notSatisfied: [],
- satisfied: [],
- },
- selfReviewSignals: [],
- managedSkills: [],
- proposalActivity: {
- active: [],
- dismissedCount: 0,
- expiredCount: 0,
- staleCount: 0,
- supersededCount: 0,
- },
- receiptActivity: {
- appliedCount: 0,
- duplicateGroups: [],
- failedCount: 0,
- pendingProposalCount: 0,
- recentReceipts: [],
- reviewCount: 0,
- },
- relevantMemories: [],
- reviewWindowEnd: '2026-05-09T02:00:00.000Z',
- reviewWindowStart: '2026-05-09T00:00:00.000Z',
- selfFeedbackCandidates: [],
- toolActivity: [],
- topics: [],
+ guardKey: 'nightly-review:user-1:agent-1:2026-05-04',
+ localDate: '2026-05-04',
+ requestedAt: '2026-05-04T14:00:00.000Z',
+ reviewWindowEnd: '2026-05-04T14:00:00.000Z',
+ reviewWindowStart: '2026-05-03T14:00:00.000Z',
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
+ timezone: 'Asia/Shanghai',
userId: 'user-1',
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
- mocks.briefCreate.mockResolvedValue(baseBrief({ id: 'brief-created' }));
- mocks.briefListUnresolvedByAgentAndTrigger.mockResolvedValue([]);
- mocks.briefUpdateMetadata.mockResolvedValue(undefined);
- mocks.initModelRuntimeFromDB.mockResolvedValue({ chat: vi.fn() });
- mocks.skillReadTargetSnapshot.mockResolvedValue(undefined);
- mocks.skillReplaceSkillIndex.mockResolvedValue(undefined);
- mocks.executeSelfIteration.mockResolvedValue({
- content: 'Created a skill.',
- stepCount: 3,
- toolCalls: [
- {
- apiName: 'createSkillIfAbsent',
- arguments: JSON.stringify({
- bodyMarkdown: 'Use concise answers.',
- idempotencyKey: 'op-create-skill',
- name: 'concise-answers',
- title: 'Concise answers',
- }),
- id: 'tool-call-1',
- identifier: 'agent-signal-self-iteration',
- type: 'builtin',
- },
- ],
- usage: [],
- writeOutcomes: [
- {
- result: {
- receiptId: 'op-create-skill',
- resourceId: 'skill-1',
- status: 'applied',
- summary: 'Created managed skill concise-answers.',
- },
- toolName: 'createSkillIfAbsent',
- },
- ],
- });
-});
-
-afterEach(() => {
- delete (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient;
-});
-
-const createSkillProposalToolArguments = () => ({
- actions: [
- {
- actionType: 'create_skill',
- applyMode: 'proposal_only',
- baseSnapshot: {
- absent: true,
- skillName: 'concise-answers',
- targetType: 'skill',
- },
- confidence: 0.9,
- dedupeKey: 'skill:concise-answers',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source-1:create_skill:concise-answers',
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: 'Prefer concise answers.',
- name: 'concise-answers',
- title: 'Concise answers',
- userId: 'user-1',
- },
- operation: 'create',
- },
- rationale: 'User repeatedly asks for concise answers.',
- risk: 'low',
- target: { skillName: 'concise-answers' },
- },
- ],
- idempotencyKey: 'proposal-op-1',
- proposalKey: 'agent-1:create_skill:skill:concise-answers',
- summary: 'Review concise answers skill.',
-});
-
-describe('listServerSelfReviewProposalActivity', () => {
- /**
- * @example
- * listServerSelfReviewProposalActivity skips malformed metadata and maps active proposal targets.
- */
- it('filters invalid metadata and maps active proposal target digests', async () => {
- const digest = await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async () => [
- baseBrief({ id: 'invalid', metadata: { proposal: { status: 'pending' } } }),
- baseBrief({
- agentId: 'other-agent',
- id: 'other-agent',
- metadata: proposalMetadata(),
- }),
- baseBrief({
- id: 'other-trigger',
- metadata: proposalMetadata(),
- trigger: 'other-trigger',
- }),
- baseBrief({ id: 'active', metadata: proposalMetadata() }),
- ],
- },
- now: '2026-05-09T01:00:00.000Z',
- userId: 'user-1',
- });
-
- expect(digest).toMatchObject({
- dismissedCount: 0,
- expiredCount: 0,
- staleCount: 0,
- supersededCount: 0,
- });
- expect(digest.active).toEqual([
- {
- actionType: 'refine_skill',
- createdAt: '2026-05-09T00:00:00.000Z',
- evidenceCount: 2,
- expiresAt: '2026-05-12T00:00:00.000Z',
- proposalId: 'active',
- proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',
- status: 'pending',
- summary: 'Proposal summary',
- targetId: 'adoc-1',
- targetTitle: 'Skill Index',
- updatedAt: '2026-05-09T01:00:00.000Z',
- },
- ]);
- });
-
- /**
- * @example
- * listServerSelfReviewProposalActivity passes trigger and agent filters to the brief reader.
- */
- it('queries unresolved proposal briefs by trigger and agent before the read cap', async () => {
- const calls: Array<{ agentId: string; limit?: number; trigger: string }> = [];
-
- await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async (options) => {
- calls.push(options);
-
- return [];
- },
- },
- userId: 'user-1',
- });
-
- expect(calls).toEqual([
- {
- agentId: 'agent-1',
- limit: 20,
- trigger: 'agent-signal:nightly-review',
- },
- ]);
- });
-
- /**
- * @example
- * listServerSelfReviewProposalActivity excludes expired pending proposals from active activity.
- */
- it('counts expired pending proposals as expired instead of active', async () => {
- const digest = await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async () => [
- baseBrief({
- id: 'expired-pending',
- metadata: proposalMetadata({ expiresAt: '2026-05-10T00:00:00.000Z' }),
- }),
- ],
- },
- now: '2026-05-10T00:00:00.000Z',
- userId: 'user-1',
- });
-
- expect(digest.active).toEqual([]);
- expect(digest.expiredCount).toBe(1);
- });
-
- /**
- * @example
- * listServerSelfReviewProposalActivity ignores legacy noop proposal metadata.
- */
- it('skips noop proposal metadata from active activity', async () => {
- const digest = await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async () => [
- baseBrief({
- id: 'noop',
- metadata: proposalMetadata({
- actionType: 'noop',
- actions: [
- {
- actionType: 'noop',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source:noop:quiet',
- rationale: 'No self-iteration needed.',
- risk: 'low',
- },
- ],
- proposalKey: 'agent-1:noop:unknown:noop',
- }),
- }),
- ],
- },
- userId: 'user-1',
- });
-
- expect(digest.active).toEqual([]);
- });
-
- /**
- * @example
- * listServerSelfReviewProposalActivity keeps unexpired pending proposals in active activity.
- */
- it('keeps future pending proposals active', async () => {
- const digest = await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async () => [
- baseBrief({
- id: 'future-pending',
- metadata: proposalMetadata({ expiresAt: '2026-05-10T00:00:01.000Z' }),
- }),
- ],
- },
- now: '2026-05-10T00:00:00.000Z',
- userId: 'user-1',
- });
-
- expect(digest.active.map((proposal) => proposal.proposalId)).toEqual(['future-pending']);
- expect(digest.expiredCount).toBe(0);
- });
-
- /**
- * @example
- * listServerSelfReviewProposalActivity prefers skillDocumentId when a proposal target has multiple ids.
- */
- it('uses proposal key target priority when mapping active proposal target ids', async () => {
- const digest = await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async () => [
- baseBrief({
- id: 'multi-target',
- metadata: proposalMetadata({
- actions: [
- {
- actionType: 'refine_skill',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source:refine_skill:skill:adoc-1',
- rationale: 'Refine the skill.',
- risk: 'medium',
- target: {
- memoryId: 'mem-1',
- skillDocumentId: 'adoc-1',
- skillName: 'skill-name',
- },
- },
- ],
- }),
- }),
- ],
- },
- now: '2026-05-09T01:00:00.000Z',
- userId: 'user-1',
- });
-
- expect(digest.active[0]?.targetId).toBe('adoc-1');
- });
-
- /**
- * @example
- * listServerSelfReviewProposalActivity counts inactive unresolved proposal statuses without listing them as active.
- */
- it('separates active proposals from inactive unresolved proposal status counts', async () => {
- const digest = await listServerSelfReviewProposalActivity({
- agentId: 'agent-1',
- briefModel: {
- listUnresolvedByAgentAndTrigger: async () => [
- baseBrief({ id: 'accepted', metadata: proposalMetadata({ status: 'accepted' }) }),
- baseBrief({ id: 'dismissed', metadata: proposalMetadata({ status: 'dismissed' }) }),
- baseBrief({ id: 'expired', metadata: proposalMetadata({ status: 'expired' }) }),
- baseBrief({ id: 'stale', metadata: proposalMetadata({ status: 'stale' }) }),
- baseBrief({ id: 'superseded', metadata: proposalMetadata({ status: 'superseded' }) }),
- ],
- },
- userId: 'user-1',
- });
-
- expect(digest.active.map((proposal) => proposal.proposalId)).toEqual(['accepted']);
- expect(digest.dismissedCount).toBe(1);
- expect(digest.expiredCount).toBe(1);
- expect(digest.staleCount).toBe(1);
- expect(digest.supersededCount).toBe(1);
- });
-});
+} as const;
describe('createServerSelfReviewPolicyOptions', () => {
- /**
- * @example
- * createServerSelfReviewPolicyOptions delegates nightly mutation authority to the
- * tool-first runtime instead of the legacy reviewer -> planner -> executor chain.
- */
- it('runs nightly shared through the tool-first runtime with DB model runtime and real tools', async () => {
- const modelRuntime = { chat: vi.fn() };
- mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
-
+ it('exposes dispatch-shaped handler deps (gate, guard, collector, db) without legacy runner/brief/receipt wiring', () => {
const options = createServerSelfReviewPolicyOptions({
agentId: 'agent-1',
db: {} as unknown as LobeChatDatabase,
selfIterationEnabled: true,
userId: 'user-1',
});
- const result = await options.runSelfReviewAgent({
- context: createNightlyContext(),
- localDate: '2026-05-09',
- sourceId: 'nightly-review:user-1:agent-1:2026-05-09',
- userId: 'user-1',
- });
- expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledTimes(1);
- expect(mocks.executeSelfIteration).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'agent-1',
- maxSteps: 10,
- modelRuntime,
- sourceId: 'nightly-review:user-1:agent-1:2026-05-09',
- userId: 'user-1',
- }),
- );
- expect(result.stepCount).toBe(3);
- expect(result.execution).toMatchObject({
- actions: [
- {
- idempotencyKey: 'op-create-skill',
- resourceId: 'skill-1',
- status: ActionStatus.Applied,
- },
- ],
- sourceId: 'nightly-review:user-1:agent-1:2026-05-09',
- status: ReviewRunStatus.Completed,
- });
- expect(result.projectionPlan.actions).toHaveLength(1);
- expect(result.projectionPlan.actions[0]).toMatchObject({
- actionType: 'create_skill',
- idempotencyKey: 'op-create-skill',
- });
+ expect(options.acquireReviewGuard).toEqual(expect.any(Function));
+ expect(options.canRunReview).toEqual(expect.any(Function));
+ expect(options.collectContext).toEqual(expect.any(Function));
+ expect(options.db).toBeDefined();
+ // The nightly run + brief + receipts now happen via execAgent / the builtin
+ // review serverRuntime / the completion path — not inline here.
+ expect('runSelfReviewAgent' in options).toBe(false);
+ expect('writeDailyBrief' in options).toBe(false);
+ expect('writeReceipts' in options).toBe(false);
+ expect('resolveBriefTextTranslator' in options).toBe(false);
});
- /**
- * @example
- * createServerSelfReviewPolicyOptions exposes createSelfReviewProposal with real brief
- * persistence instead of returning an unsupported tool result.
- */
- it('persists proposal lifecycle tool writes through Daily Brief proposal metadata', async () => {
- const modelRuntime = { chat: vi.fn() };
- const toolArguments = createSkillProposalToolArguments();
- (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient = {
- expire: vi.fn(async () => 1),
- hgetall: vi.fn(async () => ({})),
- hset: vi.fn(async () => 1),
- set: vi.fn(async () => 'OK'),
- zadd: vi.fn(async () => 1),
- };
- mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
- mocks.executeSelfIteration.mockImplementation(async (input) => {
- const result = await input.tools.createSelfReviewProposal({
- actions: toolArguments.actions,
- idempotencyKey: toolArguments.idempotencyKey,
- metadata: {},
- proposalKey: toolArguments.proposalKey,
- summary: toolArguments.summary,
- userId: 'user-1',
- });
-
- return {
- content: 'Created a proposal.',
- stepCount: 2,
- toolCalls: [
- {
- apiName: 'createSelfReviewProposal',
- arguments: JSON.stringify(toolArguments),
- id: 'call-proposal-1',
- identifier: 'agent-signal-self-iteration',
- type: 'builtin',
- },
- ],
- usage: [],
- writeOutcomes: [{ result, toolName: 'createSelfReviewProposal' }],
- };
- });
-
+ it('rejects the review when self-iteration is disabled (before any DB access)', async () => {
const options = createServerSelfReviewPolicyOptions({
agentId: 'agent-1',
db: {} as unknown as LobeChatDatabase,
- selfIterationEnabled: true,
- userId: 'user-1',
- });
- const result = await options.runSelfReviewAgent({
- context: createNightlyContext(),
- localDate: '2026-05-09',
- sourceId: 'source-1',
+ selfIterationEnabled: false,
userId: 'user-1',
});
- expect(mocks.briefCreate).toHaveBeenCalledTimes(1);
- expect(mocks.briefCreate.mock.calls[0]?.[0]).toMatchObject({
- metadata: {
- agentSignal: {
- nightlySelfReview: {
- selfReviewProposal: {
- actions: [
- {
- actionType: 'create_skill',
- operation: {
- domain: 'skill',
- operation: 'create',
- },
- },
- ],
- proposalKey: 'agent-1:create_skill:skill:concise-answers',
- status: 'pending',
- },
- },
- },
- },
- summary: expect.stringContaining('有 1 条助理建议需要你确认。'),
- title: '有助理建议需要确认',
- type: 'decision',
- });
- expect(result.execution.actions).toEqual([]);
- expect(result.projectionPlan.actions).toEqual([]);
+ await expect(options.canRunReview(baseGuardInput)).resolves.toBe(false);
});
- /**
- * @example
- * const digest = await tools.getEvidenceDigest({ evidenceIds: ['message-1', 'agent-doc-1'] });
- * expect(digest.topics[0].topicId).toBe('topic-1');
- */
- it('keeps topic and signal context when evidence digest is requested with message or agent document ids', async () => {
- const modelRuntime = { chat: vi.fn() };
- const context: NightlyReviewContext = {
- ...createNightlyContext(),
- documentActivity: {
- ...createNightlyContext().documentActivity,
- skillBucket: [
- {
- agentDocumentId: 'agent-doc-1',
- documentId: 'doc-1',
- hintIsSkill: false,
- reason: 'templateId=agent-skill',
- updatedAt: '2026-05-09T01:00:00.000Z',
- },
- ],
- },
- selfReviewSignals: [
- {
- evidenceRefs: [
- { id: 'message-1', type: 'message' },
- { id: 'agent-doc-1', type: 'agent_document' },
- ],
- features: [],
- kind: 'skill_document_with_tool_failure',
- strength: 'medium',
- },
- ],
- managedSkills: [{ documentId: 'agent-doc-1', name: 'release-note-checklist' }],
- topics: [
- {
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- failedToolCalls: [
- {
- apiName: 'replaceSkillContentCAS',
- messageId: 'message-1',
- toolCallId: 'tool-call-1',
- },
- ],
- failedToolCount: 1,
- highSignalReasons: ['failed_tool'],
- messageCount: 1,
- reviewScore: 4001,
- summary: 'The skill refinement failed.',
- topicId: 'topic-1',
- },
- ],
- };
- mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
- mocks.executeSelfIteration.mockImplementation(async (input) => {
- const digest = await input.tools.getEvidenceDigest({
- agentId: 'agent-1',
- evidenceIds: ['message-1', 'agent-doc-1'],
- reviewWindowEnd: context.reviewWindowEnd,
- reviewWindowStart: context.reviewWindowStart,
- userId: 'user-1',
- });
-
- expect(digest).toMatchObject({
- selfReviewSignals: [
- {
- kind: 'skill_document_with_tool_failure',
- },
- ],
- managedSkills: [
- {
- documentId: 'agent-doc-1',
- name: 'release-note-checklist',
- },
- ],
- topics: [
- {
- topicId: 'topic-1',
- },
- ],
- });
-
- return {
- content: 'Inspected evidence.',
- stepCount: 1,
- toolCalls: [],
- usage: [],
- writeOutcomes: [],
- };
- });
-
+ it('rejects reviews whose payload user id does not match the policy owner', async () => {
const options = createServerSelfReviewPolicyOptions({
agentId: 'agent-1',
db: {} as unknown as LobeChatDatabase,
@@ -732,219 +57,32 @@ describe('createServerSelfReviewPolicyOptions', () => {
userId: 'user-1',
});
- await options.runSelfReviewAgent({
- context,
- localDate: '2026-05-09',
- sourceId: 'source-1',
- userId: 'user-1',
- });
+ await expect(options.canRunReview({ ...baseGuardInput, userId: 'user-2' })).resolves.toBe(false);
});
+});
- /**
- * @example
- * createSelfReviewProposal({ actions: [{ actionType: 'refine_skill' }] })
- * snapshots the target skill on the server before creating the approval brief.
- */
- it('enriches refine skill proposals with server-side base snapshots', async () => {
- const modelRuntime = { chat: vi.fn() };
- const toolArguments = {
- actions: [
- {
- actionType: 'refine_skill',
- applyMode: 'proposal_only',
- confidence: 0.9,
- dedupeKey: 'skill:skill-doc-1',
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
- idempotencyKey: 'source-1:refine_skill:skill-doc-1',
- operation: {
- domain: 'skill',
- input: {
- bodyMarkdown: 'Updated skill body.',
- skillDocumentId: 'skill-doc-1',
- userId: 'user-1',
- },
- operation: 'refine',
- },
- rationale: 'Repeated tool failures show this skill needs a safer workflow.',
- risk: 'low',
- target: { skillDocumentId: 'skill-doc-1' },
- },
- ],
- idempotencyKey: 'proposal-op-refine-1',
- proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',
- summary: 'Review skill refinement.',
- };
- (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient = {
- expire: vi.fn(async () => 1),
- hgetall: vi.fn(async () => ({})),
- hset: vi.fn(async () => 1),
- set: vi.fn(async () => 'OK'),
- zadd: vi.fn(async () => 1),
- };
- mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
- mocks.skillReadTargetSnapshot.mockResolvedValue({
- agentDocumentId: 'skill-doc-1',
- contentHash: 'hash-before',
- documentId: 'document-1',
- managed: true,
- targetTitle: 'Existing skill',
- writable: true,
- });
- mocks.executeSelfIteration.mockImplementation(async (input) => {
- const result = await input.tools.createSelfReviewProposal({
- actions: toolArguments.actions,
- idempotencyKey: toolArguments.idempotencyKey,
- metadata: {},
- proposalKey: toolArguments.proposalKey,
- summary: toolArguments.summary,
- userId: 'user-1',
- });
-
- return {
- content: 'Created a refine proposal.',
- stepCount: 2,
- toolCalls: [
- {
- apiName: 'createSelfReviewProposal',
- arguments: JSON.stringify(toolArguments),
- id: 'call-proposal-refine-1',
- identifier: 'agent-signal-self-iteration',
- type: 'builtin',
- },
- ],
- usage: [],
- writeOutcomes: [{ result, toolName: 'createSelfReviewProposal' }],
- };
- });
-
- const options = createServerSelfReviewPolicyOptions({
- agentId: 'agent-1',
- db: {} as unknown as LobeChatDatabase,
- selfIterationEnabled: true,
- userId: 'user-1',
- });
- const result = await options.runSelfReviewAgent({
- context: createNightlyContext(),
- localDate: '2026-05-09',
- sourceId: 'source-1',
- userId: 'user-1',
- });
-
- expect(mocks.briefCreate).toHaveBeenCalledTimes(1);
- expect(mocks.briefCreate.mock.calls[0]?.[0]).toMatchObject({
- metadata: {
- agentSignal: {
- nightlySelfReview: {
- selfReviewProposal: {
- actions: [
- {
- actionType: 'refine_skill',
- baseSnapshot: {
- agentDocumentId: 'skill-doc-1',
- contentHash: 'hash-before',
- documentId: 'document-1',
- managed: true,
- targetType: 'skill',
- writable: true,
- },
- operation: {
- domain: 'skill',
- operation: 'refine',
- },
- },
- ],
- proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',
- status: 'pending',
- },
- },
- },
- },
- type: 'decision',
- });
- expect(result.execution.actions).toEqual([]);
- expect(result.projectionPlan.actions).toEqual([]);
- });
-
- /**
- * @example
- * replaceSkillContentCAS({ skillDocumentId: 'skill-index-1', bodyMarkdown: '...' })
- * captures the CAS snapshot and normalizes index ids to bundle ids before preflight.
- */
- it('enriches direct refine skill writes with server-side CAS snapshots', async () => {
- const modelRuntime = { chat: vi.fn() };
- (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient = {
- expire: vi.fn(async () => 1),
- hgetall: vi.fn(async () => ({})),
- hset: vi.fn(async () => 1),
- set: vi.fn(async () => 'OK'),
- zadd: vi.fn(async () => 1),
- };
- mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
- mocks.skillReadTargetSnapshot.mockResolvedValue({
- agentDocumentId: 'skill-bundle-1',
- contentHash: 'hash-before',
- documentId: 'document-1',
- managed: true,
- targetTitle: 'Existing skill',
- writable: true,
- });
- mocks.skillReplaceSkillIndex.mockResolvedValue({
- bundle: { agentDocumentId: 'skill-bundle-1' },
- name: 'existing-skill',
- });
- mocks.executeSelfIteration.mockImplementation(async (input) => {
- const result = await input.tools.replaceSkillContentCAS({
- bodyMarkdown: 'Updated skill body.',
- idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',
- skillDocumentId: 'skill-index-1',
- userId: 'user-1',
- } as Parameters<typeof input.tools.replaceSkillContentCAS>[0]);
-
- return {
- content: 'Updated a skill.',
- stepCount: 2,
- toolCalls: [
- {
- apiName: 'replaceSkillContentCAS',
- arguments: JSON.stringify({
- bodyMarkdown: 'Updated skill body.',
- idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',
- skillDocumentId: 'skill-index-1',
- }),
- id: 'call-refine-1',
- identifier: 'agent-signal-self-iteration',
- type: 'builtin',
- },
- ],
- usage: [],
- writeOutcomes: [{ result, toolName: 'replaceSkillContentCAS' }],
- };
- });
-
- const options = createServerSelfReviewPolicyOptions({
+describe('createReviewRuntimePrimitives', () => {
+ it('builds the live review tool surface (skill/memory writes + proposal lifecycle) for the serverRuntime', () => {
+ const service = createReviewRuntimePrimitives({
agentId: 'agent-1',
+ briefModel: {} as never,
db: {} as unknown as LobeChatDatabase,
- selfIterationEnabled: true,
- userId: 'user-1',
- });
- const result = await options.runSelfReviewAgent({
- context: createNightlyContext(),
- localDate: '2026-05-09',
- sourceId: 'source-1',
- userId: 'user-1',
- });
-
- expect(mocks.skillReplaceSkillIndex).toHaveBeenCalledWith(
- expect.objectContaining({
- agentDocumentId: 'skill-bundle-1',
- agentId: 'agent-1',
- bodyMarkdown: 'Updated skill body.',
- }),
- );
- expect(result.execution.actions[0]).toMatchObject({
- idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',
- resourceId: 'skill-bundle-1',
- status: ActionStatus.Applied,
- });
+ localDate: '2026-05-04',
+ proposalBriefWriter: {} as never,
+ reviewWindowEnd: '2026-05-04T14:00:00.000Z',
+ reviewWindowStart: '2026-05-03T14:00:00.000Z',
+ skillDocumentService: {} as never,
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
+ userId: 'user-1',
+ });
+
+ // Pure construction (no DB / receipt / operation side channel) — just the
+ // advertised api surface the package runtime echoes.
+ expect(service.createSelfReviewProposal).toEqual(expect.any(Function));
+ expect(service.createSkillIfAbsent).toEqual(expect.any(Function));
+ expect(service.replaceSkillContentCAS).toEqual(expect.any(Function));
+ expect(service.writeMemory).toEqual(expect.any(Function));
+ expect(service.listManagedSkills).toEqual(expect.any(Function));
+ expect(service.listSelfReviewProposals).toEqual(expect.any(Function));
});
});
diff --git a/src/server/services/agentSignal/services/selfIteration/review/handler.ts b/src/server/services/agentSignal/services/selfIteration/review/handler.ts
index 28a8a57d499..92f1b1f3b3b 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/handler.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/handler.ts
@@ -1,20 +1,17 @@
import type { SourceAgentNightlyReviewRequested } from '@lobechat/agent-signal/source';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
+import { createAgentSignalSelfIterationPrompt } from '@lobechat/prompts';
import { isNonEmptyString } from '@lobechat/utils';
+import type { LobeChatDatabase } from '@/database/type';
+
import { defineSourceHandler } from '../../../runtime/middleware';
-import type { AgentSignalReceipt } from '../../receiptService';
-import { createSelfReviewReceipts } from '../../receiptService';
-import type { AgentRunResult } from '../execute';
-import type { EvidenceRef, Plan, RunResult } from '../types';
+import { enqueueSelfIterationRun } from '../dispatch/enqueueSelfIterationRun';
import { buildNightlyReviewSourceId, ReviewRunStatus } from '../types';
-import type { SelfReviewBriefProjection } from './brief';
-import { createBriefSelfReviewService, getNightlySelfReviewBriefMetadata } from './brief';
-import type { SelfReviewBriefTextTranslator } from './briefText';
import type { CollectNightlyReviewContextInput, NightlyReviewContext } from './collect';
-import type { SelfReviewProposalPlan } from './proposal';
/**
* Validated nightly review request payload consumed by the handler.
@@ -52,19 +49,13 @@ export interface NightlyReviewSourceGuardInput extends NightlyReviewSourcePayloa
export interface NightlyReviewSourceHandlerResult extends Record<string, unknown> {
/** Stable agent id being reviewed when payload validation succeeds. */
agentId?: string;
- /** Whether Daily Brief creation failed after shared execution. */
- briefWriteFailed?: boolean;
- /** Executor result for completed runs. */
- execution?: RunResult;
/** Stable guard key used for idempotency when payload validation succeeds. */
guardKey?: string;
/** User-local date in YYYY-MM-DD form when payload validation succeeds. */
localDate?: string;
- /** Number of planned self-review actions before execution. */
- plannedActionCount?: number;
- /** Planner summary for future brief construction. */
- planSummary?: string;
- /** Machine-readable skip reason for non-completed runs. */
+ /** Operation id of the enqueued background self-iteration run, when dispatched. */
+ operationId?: string;
+ /** Machine-readable skip reason for non-dispatched runs. */
reason?: 'gate_disabled' | 'invalid_payload';
/** Review window end as an ISO string when payload validation succeeds. */
reviewWindowEnd?: string;
@@ -88,21 +79,16 @@ export interface CreateNightlyReviewSourceHandlerDependencies {
canRunReview: (input: NightlyReviewSourceGuardInput) => Promise<boolean>;
/** Collects bounded digest context without mutating shared resources. */
collectContext: (input: CollectNightlyReviewContextInput) => Promise<NightlyReviewContext>;
- /** Resolves a home-namespace translator for persisted nightly Brief text. */
- resolveBriefTextTranslator?: (input: {
- userId: string;
- }) => Promise<SelfReviewBriefTextTranslator | undefined>;
- /** Runs the bounded self-iteration agent and returns execution plus the frozen projection plan. */
- runSelfReviewAgent: (input: {
- context: NightlyReviewContext;
- localDate: string;
- sourceId: string;
- userId: string;
- }) => Promise<AgentRunResult>;
- /** Writes a Daily Brief payload for user-visible nightly outcomes. */
- writeDailyBrief?: (brief: SelfReviewBriefProjection) => Promise<{ id?: string } | void>;
- /** Writes durable receipts for the review summary and action outcomes. */
- writeReceipts?: (receipts: AgentSignalReceipt[]) => Promise<void>;
+ /** Postgres handle used by the dispatch helper to enqueue the execAgent run. */
+ db: LobeChatDatabase;
+ /** Enqueues the async self-iteration run. Overridable for tests. */
+ dispatch?: typeof enqueueSelfIterationRun;
+ /**
+ * Maximum self-iteration runtime steps.
+ *
+ * @default builtin agent default
+ */
+ maxSteps?: number;
}
interface NightlyReviewSpanLike {
@@ -193,133 +179,6 @@ const toBaseResult = (
userId: guardInput.userId,
});
-const applyReceiptIdsToExecution = (
- execution: RunResult,
- receipts: AgentSignalReceipt[],
-): RunResult => {
- const receiptByActionKey = new Map(
- receipts
- .filter((receipt) => receipt.id.endsWith(':action'))
- .map((receipt) => [receipt.id.slice(0, -':action'.length), receipt.id]),
- );
-
- return {
- ...execution,
- actions: execution.actions.map((action) => ({
- ...action,
- ...(receiptByActionKey.get(action.idempotencyKey)
- ? { receiptId: receiptByActionKey.get(action.idempotencyKey) }
- : {}),
- })),
- summaryReceiptId: `${execution.sourceId ?? receipts[0]?.sourceId}:review-summary`,
- };
-};
-
-const collectPlanEvidenceRefs = (plan: Plan): EvidenceRef[] => {
- const evidenceRefs = new Map<string, EvidenceRef>();
-
- for (const action of plan.actions) {
- for (const evidenceRef of action.evidenceRefs) {
- evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);
- }
- }
-
- return [...evidenceRefs.values()];
-};
-
-const isMergeableProposalAction = (actionType: string) =>
- actionType === 'create_skill' || actionType === 'refine_skill';
-
-const hasProjectionBaseSnapshot = (action: Plan['actions'][number]) => {
- if (!isMergeableProposalAction(action.actionType)) return true;
-
- const actionWithSnapshot = action as Plan['actions'][number] & {
- baseSnapshot?: unknown;
- };
-
- return actionWithSnapshot.baseSnapshot !== undefined;
-};
-
-const isSnapshotAwareProposalPlan = (plan: Plan): plan is SelfReviewProposalPlan =>
- plan.actions.every(hasProjectionBaseSnapshot);
-
-const writeNightlyReceipts = async (
- deps: CreateNightlyReviewSourceHandlerDependencies,
- receipts: AgentSignalReceipt[],
-) => {
- if (!deps.writeReceipts || receipts.length === 0) return;
-
- return tracer.startActiveSpan(
- 'agent_signal.nightly_review.write_receipts',
- {
- attributes: {
- 'agent.signal.nightly.receipt_count': receipts.length,
- 'agent.signal.source_id': receipts[0]?.sourceId ?? '',
- },
- },
- async (span) => {
- try {
- await deps.writeReceipts?.(receipts);
- span.setStatus({ code: SpanStatusCode.OK });
- } catch (error) {
- span.setStatus({
- code: SpanStatusCode.ERROR,
- message:
- error instanceof Error ? error.message : 'AgentSignal nightly receipts write failed',
- });
- span.recordException(error as Error);
- console.error('[AgentSignal] Failed to write nightly review receipts:', error);
- } finally {
- span.end();
- }
- },
- );
-};
-
-const writeNightlyBrief = async (
- deps: CreateNightlyReviewSourceHandlerDependencies,
- brief: SelfReviewBriefProjection | undefined,
-) => {
- if (!deps.writeDailyBrief || !brief) return {};
-
- const metadata = getNightlySelfReviewBriefMetadata(brief.metadata);
-
- return tracer.startActiveSpan(
- 'agent_signal.nightly_review.write_brief',
- {
- attributes: {
- 'agent.signal.agent_id': brief.agentId ?? '',
- 'agent.signal.nightly.applied_count': metadata?.actionCounts.applied ?? 0,
- 'agent.signal.nightly.failed_count': metadata?.actionCounts.failed ?? 0,
- 'agent.signal.nightly.outcome': metadata?.outcome ?? 'unknown',
- 'agent.signal.nightly.proposed_count': metadata?.actionCounts.proposed ?? 0,
- 'agent.signal.nightly.skipped_count': metadata?.actionCounts.skipped ?? 0,
- },
- },
- async (span) => {
- try {
- const result = await deps.writeDailyBrief?.(brief);
- span.setAttribute('agent.signal.nightly.brief_id', result?.id ?? '');
- span.setStatus({ code: SpanStatusCode.OK });
-
- return result && result.id ? { briefId: result.id } : {};
- } catch (error) {
- span.setStatus({
- code: SpanStatusCode.ERROR,
- message:
- error instanceof Error ? error.message : 'AgentSignal nightly brief write failed',
- });
- span.recordException(error as Error);
- console.error('[AgentSignal] Failed to write nightly review brief:', error);
-
- return { briefWriteFailed: true };
- } finally {
- span.end();
- }
- },
- );
-};
-
/**
* Creates the DI-friendly handler for nightly review request sources.
*
@@ -329,22 +188,21 @@ const writeNightlyBrief = async (
* -> `agent.nightly_review.requested`
* -> {@link createNightlyReviewSourceHandler}
*
- * Upstream:
- * - `agent.nightly_review.requested`
- *
- * Downstream:
- * - injected bounded self-iteration agent runner
- *
- * Use when:
- * - Tests need to run the nightly review orchestration without DB or LLM dependencies
- * - Runtime policy composition needs a side-effect boundary before executing self-iteration plans
+ * The handler validates the request, re-checks gates + idempotency, collects the
+ * bounded review digest, then enqueues an async `execAgent` run under the builtin
+ * `nightly-review` agent. The review window + local date ride on the marker so the
+ * builtin `agent-signal-review` serverRuntime can re-derive them; the Daily Brief
+ * is written in-run by the review tool primitive, and receipts are projected by
+ * the completion path — this handler runs no model and writes no brief/receipts
+ * inline.
*
* Expects:
* - `source` is an `agent.nightly_review.requested` source with scheduler-produced payload
- * - Dependencies enforce gates, idempotency, runner limits, and persistence
+ * - Dependencies enforce gates, idempotency, and provide a db handle for dispatch
*
* Returns:
- * - A run result with status and enough plan metadata for future brief builders
+ * - A run result with `Dispatched` status + the enqueued operation id, or a
+ * `Skipped` / `Deduped` status when gates / idempotency reject the run
*/
export const createNightlyReviewSourceHandler = (
deps: CreateNightlyReviewSourceHandlerDependencies,
@@ -444,94 +302,57 @@ export const createNightlyReviewSourceHandler = (
);
},
);
- const agentResult = await runNightlyReviewSpan(
- 'agent_signal.nightly_review.run_agent',
+
+ const prompt = createAgentSignalSelfIterationPrompt({
+ agentId: payload.agentId,
+ context,
+ mode: 'review',
+ sourceId: source.sourceId,
+ userId: payload.userId,
+ window: {
+ end: payload.reviewWindowEnd,
+ localDate: payload.localDate,
+ start: payload.reviewWindowStart,
+ timezone: payload.timezone,
+ },
+ });
+
+ const { operationId } = await runNightlyReviewSpan(
+ 'agent_signal.nightly_review.dispatch',
{
'agent.signal.agent_id': payload.agentId,
- 'agent.signal.nightly.document_skill_event_count':
- context.documentActivity?.skillBucket?.length ?? 0,
- 'agent.signal.nightly.managed_skill_count': context.managedSkills.length,
- 'agent.signal.nightly.self_review_signal_count': context.selfReviewSignals?.length ?? 0,
- 'agent.signal.nightly.memory_count': context.relevantMemories.length,
- 'agent.signal.nightly.topic_count': context.topics.length,
- 'agent.signal.nightly.tool_activity_count': context.toolActivity?.length ?? 0,
'agent.signal.source_id': source.sourceId,
'agent.signal.user_id': payload.userId,
},
- () =>
- deps.runSelfReviewAgent({
- context,
- localDate: payload.localDate,
- sourceId: source.sourceId,
+ () => {
+ const dispatch = deps.dispatch ?? enqueueSelfIterationRun;
+
+ return dispatch({
+ agentId: payload.agentId,
+ db: deps.db,
+ marker: {
+ agentId: payload.agentId,
+ kind: 'nightly-review',
+ localDate: payload.localDate,
+ reviewWindowEnd: payload.reviewWindowEnd,
+ reviewWindowStart: payload.reviewWindowStart,
+ sourceId: source.sourceId,
+ },
+ ...(deps.maxSteps ? { maxSteps: deps.maxSteps } : {}),
+ prompt,
+ slug: BUILTIN_AGENT_SLUGS.nightlyReview,
userId: payload.userId,
- }),
- (span, result) => {
- span.setAttribute(
- 'agent.signal.nightly.plan_action_count',
- result.projectionPlan.actions.length,
- );
- span.setAttribute(
- 'agent.signal.nightly.execution_action_count',
- result.execution.actions.length,
- );
- if (typeof result.stepCount === 'number') {
- span.setAttribute('agent.signal.nightly.agent_step_count', result.stepCount);
- }
+ });
},
- );
- const plan = agentResult.projectionPlan;
- const proposalPlan = isSnapshotAwareProposalPlan(plan) ? plan : undefined;
- const execution = agentResult.execution;
- const receipts = createSelfReviewReceipts({
- agentId: payload.agentId,
- createdAt: source.timestamp,
- localDate: payload.localDate,
- plan,
- result: {
- ...execution,
- sourceId: source.sourceId,
- },
- sourceId: source.sourceId,
- sourceType: source.sourceType,
- timezone: payload.timezone,
- userId: payload.userId,
- });
- const executionWithReceipts = applyReceiptIdsToExecution(
- {
- ...execution,
- sourceId: source.sourceId,
+ (span, result) => {
+ span.setAttribute('agent.signal.nightly.operation_id', result.operationId);
},
- receipts,
);
- await writeNightlyReceipts(deps, receipts);
-
- const t = await deps.resolveBriefTextTranslator?.({ userId: payload.userId });
- const brief = createBriefSelfReviewService().projectNightlyReviewBrief({
- agentId: payload.agentId,
- evidenceRefs: collectPlanEvidenceRefs(plan),
- ideas: agentResult.ideas,
- localDate: payload.localDate,
- ...(proposalPlan ? { plan: proposalPlan } : {}),
- result: executionWithReceipts,
- reviewWindowEnd: payload.reviewWindowEnd,
- reviewWindowStart: payload.reviewWindowStart,
- t,
- timezone: payload.timezone,
- userId: payload.userId,
- });
- const briefResult = await writeNightlyBrief(deps, brief);
-
return {
...baseResult,
- ...briefResult,
- execution: {
- ...executionWithReceipts,
- ...('briefId' in briefResult ? { briefId: briefResult.briefId } : {}),
- },
- plannedActionCount: plan.actions.length,
- planSummary: plan.summary,
- status: execution.status,
+ operationId,
+ status: ReviewRunStatus.Dispatched,
};
},
);
@@ -547,21 +368,12 @@ export const createNightlyReviewSourceHandler = (
* -> `agent.nightly_review.requested`
* -> {@link createNightlyReviewSourcePolicyHandler}
*
- * Upstream:
- * - `agent.nightly_review.requested`
- *
- * Downstream:
- * - {@link createNightlyReviewSourceHandler}
- *
* Use when:
* - Default Agent Signal policies are composed with nightly review dependencies
* - The runtime source registry needs an installable source handler definition
*
- * Expects:
- * - All server-only dependencies are injected by the caller
- *
* Returns:
- * - A source handler that concludes the runtime chain with the review run metadata
+ * - A source handler that concludes the runtime chain with the dispatch metadata
*/
export const createNightlyReviewSourcePolicyHandler = (
deps: CreateNightlyReviewSourceHandlerDependencies,
diff --git a/src/server/services/agentSignal/services/selfIteration/review/server.ts b/src/server/services/agentSignal/services/selfIteration/review/server.ts
index 76ed8d0c0e1..1075ada1317 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/server.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/server.ts
@@ -1,4 +1,4 @@
-import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
+import type { AgentSignalRuntimeService } from '@lobechat/builtin-tool-agent-signal';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
import { pickTrimmedString, toRecord } from '@lobechat/utils';
@@ -6,19 +6,14 @@ import { pickTrimmedString, toRecord } from '@lobechat/utils';
import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';
import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
import { BriefModel } from '@/database/models/brief';
-import { UserModel } from '@/database/models/user';
import type { BriefItem } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';
import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';
import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
-import { translation } from '@/server/translation';
-import { persistAgentSignalReceipts } from '../../receiptService';
-import { createAgentRunner, executeSelfIteration } from '../execute';
import { projectRun } from '../projection';
import type { CreateServerSelfIterationPolicyOptions } from '../server';
import { listServerSelfReviewProposalActivity } from '../server';
@@ -26,18 +21,16 @@ import type {
CloseSelfReviewProposalInput,
CreateSelfReviewProposalInput,
CreateSkillIfAbsentInput,
- OperationReservation,
RefreshSelfReviewProposalInput,
ReplaceSkillContentCASInput,
SupersedeSelfReviewProposalInput,
- ToolReceiptInput,
- ToolWriteResult,
WriteMemoryInput,
} from '../tools/shared';
-import { createMemoryService, createToolSet } from '../tools/shared';
+import { createMemoryService } from '../tools/shared';
import type { EvidenceRef } from '../types';
import { Risk, Scope } from '../types';
-import { createBriefSelfReviewService, createServerSelfReviewBriefWriter } from './brief';
+import type { createServerSelfReviewBriefWriter } from './brief';
+import { createBriefSelfReviewService } from './brief';
import type { SelfReviewBriefTextTranslator } from './briefText';
import type {
FeedbackActivityDigest,
@@ -58,9 +51,6 @@ import {
import { createSelfReviewProposalPreflightService } from './proposalPreflight';
import { createSelfReviewProposalSnapshotService } from './proposalSnapshot';
-const NIGHTLY_REVIEW_SOURCE_TYPE = 'agent.nightly_review.requested';
-const SELF_ITERATION_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;
-
interface ProposalBriefReader {
listUnresolvedByAgentAndTrigger: (options: {
agentId: string;
@@ -69,142 +59,6 @@ interface ProposalBriefReader {
}) => Promise<Awaited<ReturnType<BriefModel['listUnresolvedByAgentAndTrigger']>>>;
}
-const selfIterationOperationScopeKey = (idempotencyKey: string) =>
- `shared-operation:${idempotencyKey}`;
-
-const selfIterationOperationReserveKey = (idempotencyKey: string) =>
- `shared-operation-reserve:${idempotencyKey}`;
-
-const parseStoredOperationResult = (
- payload: Record<string, string> | undefined,
-): ToolWriteResult | undefined => {
- if (!payload?.result) return;
-
- try {
- const result = JSON.parse(payload.result) as ToolWriteResult;
-
- if (
- result.status === 'applied' ||
- result.status === 'deduped' ||
- result.status === 'failed' ||
- result.status === 'proposed' ||
- result.status === 'skipped_stale' ||
- result.status === 'skipped_unsupported'
- ) {
- return result;
- }
- } catch {
- return;
- }
-};
-
-const createSkippedOperationResult = (): ToolWriteResult => ({
- status: 'skipped_unsupported',
- summary:
- 'Self-iteration operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',
-});
-
-const reserveSelfIterationOperation = async (
- idempotencyKey: string,
-): Promise<OperationReservation> => {
- const scopeKey = selfIterationOperationScopeKey(idempotencyKey);
- const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));
-
- if (existing) return { existing, reserved: false };
-
- // NOTICE:
- // Redis is the only available cross-worker idempotency boundary for nightly tool writes.
- // `tryDedupe` also returns false when the Redis client is unavailable, so the safe fallback is
- // to skip mutation instead of writing without a durable reservation.
- // Source/context: `src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts`.
- // Removal condition: replace with a database-backed self-iteration operation ledger.
- const reserved = await redisSourceEventStore.tryDedupe(
- selfIterationOperationReserveKey(idempotencyKey),
- SELF_ITERATION_OPERATION_STATE_TTL_SECONDS,
- );
-
- if (reserved) return { reserved: true };
-
- return {
- existing:
- parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ??
- createSkippedOperationResult(),
- reserved: false,
- };
-};
-
-const completeSelfIterationOperation = async (input: ToolReceiptInput) => {
- await redisSourceEventStore.writeWindow(
- selfIterationOperationScopeKey(input.idempotencyKey),
- {
- result: JSON.stringify({
- ...(input.receiptId ? { receiptId: input.receiptId } : {}),
- ...(input.resourceId ? { resourceId: input.resourceId } : {}),
- status: input.status,
- ...(input.summary ? { summary: input.summary } : {}),
- } satisfies ToolWriteResult),
- },
- SELF_ITERATION_OPERATION_STATE_TTL_SECONDS,
- );
-};
-
-const getToolReceiptStatus = (
- status: ToolReceiptInput['status'],
-): 'applied' | 'failed' | 'proposed' | 'skipped' => {
- if (status === 'applied') return 'applied';
- if (status === 'failed') return 'failed';
- if (status === 'proposed') return 'proposed';
-
- return 'skipped';
-};
-
-const writeSelfReviewToolReceipt = async ({
- agentId,
- input,
- sourceId,
- userId,
-}: {
- agentId: string;
- input: ToolReceiptInput;
- sourceId: string;
- userId: string;
-}) => {
- await persistAgentSignalReceipts([
- {
- agentId,
- createdAt: Date.now(),
- detail: input.summary ?? `Self-review tool ${input.toolName} finished with ${input.status}.`,
- id: input.idempotencyKey,
- kind:
- input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'
- ? 'skill'
- : 'review',
- metadata: {
- sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,
- },
- sourceId,
- sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,
- status: getToolReceiptStatus(input.status),
- ...(input.resourceId &&
- (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')
- ? {
- target: {
- id: input.resourceId,
- ...(input.summary ? { summary: input.summary } : {}),
- title: input.summary ?? input.resourceId,
- type: 'skill',
- },
- }
- : {}),
- title: input.summary ?? 'Self-review tool outcome',
- topicId: sourceId,
- userId,
- },
- ]);
-
- return { receiptId: input.idempotencyKey };
-};
-
const createSkillProposalAction = (input: CreateSkillIfAbsentInput): SelfReviewProposalAction => ({
actionType: 'create_skill',
baseSnapshot: {
@@ -546,59 +400,76 @@ const updateSelfReviewProposalBrief = async ({
};
};
-export const createServerToolSet = ({
- agentId,
- briefModel,
- briefTextTranslator,
- context,
- db,
- localDate,
- proposalBriefWriter,
- skillDocumentService,
- sourceId,
- userId,
-}: {
+export interface ReviewRuntimePrimitiveDeps {
agentId: string;
briefModel: BriefModel;
briefTextTranslator?: SelfReviewBriefTextTranslator;
- context: Parameters<
- CreateNightlyReviewSourceHandlerDependencies['runSelfReviewAgent']
- >[0]['context'];
db: LobeChatDatabase;
localDate: string;
proposalBriefWriter: ReturnType<typeof createServerSelfReviewBriefWriter>;
+ reviewWindowEnd: string;
+ reviewWindowStart: string;
skillDocumentService: SkillManagementDocumentService;
sourceId: string;
userId: string;
-}) => {
- const proposalPreflight = createSelfReviewProposalPreflightService({
- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
+}
- return !skills.some((skill) => skill.name === name);
- },
- readSkillTargetSnapshot: (skillDocumentId) =>
- skillDocumentService.readSkillTargetSnapshot({
- agentDocumentId: skillDocumentId,
- agentId,
- }),
+/**
+ * Builds the nightly-review tool primitives for the execAgent path — pure live
+ * DB reads + durable writes, keyed to match the advertised api names.
+ *
+ * Unlike {@link createServerToolSet}, these carry no `reserveOperation` /
+ * receipt / `completeOperation` side channel: idempotency and receipt
+ * projection live on the execAgent completion path, so a tool call only reads
+ * or mutates. The evidence corpus is embedded in the agent's prompt, so there
+ * is deliberately no `getEvidenceDigest` primitive — the agent reads evidence
+ * from its own context, and these tools only touch live state.
+ */
+export const createReviewRuntimePrimitives = (
+ deps: ReviewRuntimePrimitiveDeps,
+): AgentSignalRuntimeService => {
+ const {
+ agentId,
+ briefModel,
+ briefTextTranslator,
+ db,
+ localDate,
+ proposalBriefWriter,
+ reviewWindowEnd,
+ reviewWindowStart,
+ skillDocumentService,
+ sourceId,
+ userId,
+ } = deps;
+
+ const isSkillNameAvailable = async ({
+ agentId: targetAgentId,
+ name,
+ }: {
+ agentId?: string;
+ name: string;
+ }) => {
+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
+
+ return !skills.some((skill) => skill.name === name);
+ };
+ const readSkillTargetSnapshot = (skillDocumentId: string) =>
+ skillDocumentService.readSkillTargetSnapshot({ agentDocumentId: skillDocumentId, agentId });
+
+ const proposalPreflight = createSelfReviewProposalPreflightService({
+ isSkillNameAvailable,
+ readSkillTargetSnapshot,
});
const proposalSnapshot = createSelfReviewProposalSnapshotService({
- isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
- const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
-
- return !skills.some((skill) => skill.name === name);
- },
- readSkillTargetSnapshot: (skillDocumentId) =>
- skillDocumentService.readSkillTargetSnapshot({
- agentDocumentId: skillDocumentId,
- agentId,
- }),
+ isSkillNameAvailable,
+ readSkillTargetSnapshot,
});
- return createToolSet({
- closeProposal: async (input: CloseSelfReviewProposalInput) =>
- updateSelfReviewProposalBrief({
+ return {
+ closeSelfReviewProposal: async (rawInput) => {
+ const input = rawInput as unknown as CloseSelfReviewProposalInput;
+
+ return updateSelfReviewProposalBrief({
agentId,
briefModel,
proposalId: input.proposalId,
@@ -608,16 +479,10 @@ export const createServerToolSet = ({
status: 'dismissed',
updatedAt: new Date().toISOString(),
}),
- }),
- completeOperation: completeSelfIterationOperation,
- completeReplaceSkillInput: (input) =>
- withCompleteReplaceSkillSnapshot({
- agentId,
- input,
- snapshotService: proposalSnapshot,
- userId,
- }),
- createProposal: async (input) => {
+ });
+ },
+ createSelfReviewProposal: async (rawInput) => {
+ const input = rawInput as unknown as CreateSelfReviewProposalInput;
const projectionInput = await withCompleteProposalSnapshots({
agentId,
input,
@@ -638,8 +503,8 @@ export const createServerToolSet = ({
localDate,
plan: projection.projectionPlan,
result: projection.execution,
- reviewWindowEnd: context.reviewWindowEnd,
- reviewWindowStart: context.reviewWindowStart,
+ reviewWindowEnd,
+ reviewWindowStart,
t: briefTextTranslator,
timezone: 'UTC',
userId,
@@ -655,10 +520,22 @@ export const createServerToolSet = ({
summary: input.summary ?? 'Created self-review proposal.',
};
},
- createSkill: async (input) => {
+ createSkillIfAbsent: async (rawInput) => {
+ const input = rawInput as unknown as CreateSkillIfAbsentInput;
+
+ if (!pickTrimmedString(input.name) || !pickTrimmedString(input.bodyMarkdown)) {
+ return {
+ status: 'skipped_unsupported',
+ summary: 'Skill creation requires a non-empty name and body.',
+ };
+ }
+
const preflight = await proposalPreflight.checkAction(createSkillProposalAction(input));
if (!preflight.allowed) {
- throw new Error(`Skill creation preflight failed: ${preflight.reason}`);
+ return {
+ status: 'skipped_stale',
+ summary: `Skill creation preflight failed: ${preflight.reason}`,
+ };
}
const result = await skillDocumentService.createSkill({
@@ -674,120 +551,50 @@ export const createServerToolSet = ({
summary: `Created managed skill ${result.name}.`,
};
},
- writeMemory: async (input: WriteMemoryInput) => {
- // TODO: Harden the real writeMemory E2E path. Local QStash verification showed this
- // tool reaches the memory action agent, but the agent does not always converge to an
- // applied receipt/brief. Keep this marker until the memory auto-apply case has a
- // deterministic eval plus a passing end-to-end run.
- const memoryService = createMemoryService({
- writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
- const result = await runMemoryActionAgent(
- {
- agentId,
- message: content,
- reason: `Agent Signal self-review memory candidate from ${evidenceRefs.length} evidence refs.`,
- },
- {
- db,
- userId,
- },
- );
-
- if (result.status !== 'applied') {
- throw new Error(
- result.detail ?? 'Memory action agent did not apply a durable memory write.',
- );
- }
-
- return {
- memoryId: idempotencyKey,
- summary: result.detail ?? content,
- };
- },
- });
- const result = await memoryService.writeMemory({
- evidenceRefs: input.evidenceRefs,
- idempotencyKey: input.idempotencyKey,
- input: {
- content: input.content,
- userId: input.userId,
- },
- });
-
- return {
- resourceId: result.memoryId,
- summary: result.summary,
+ getManagedSkill: async (rawInput) => {
+ const { agentId: targetAgentId, skillDocumentId } = rawInput as {
+ agentId?: string;
+ skillDocumentId: string;
};
- },
- getEvidenceDigest: async ({ evidenceIds }) => {
- const selectedEvidenceIds = new Set(evidenceIds ?? []);
- const includeAll = selectedEvidenceIds.size === 0;
- const hasSelectedEvidence = (refs: { id: string }[] | undefined) =>
- refs?.some((ref) => selectedEvidenceIds.has(ref.id)) ?? false;
- return {
- documentActivity: context.documentActivity,
- selfReviewSignals: includeAll
- ? context.selfReviewSignals
- : context.selfReviewSignals.filter((signal) => hasSelectedEvidence(signal.evidenceRefs)),
- managedSkills: context.managedSkills,
- proposalActivity: context.proposalActivity,
- receiptActivity: context.receiptActivity,
- toolActivity: context.toolActivity,
- topics: includeAll
- ? context.topics
- : context.topics.filter(
- (topic) =>
- hasSelectedEvidence(topic.evidenceRefs) ||
- topic.failedMessages?.some((message) =>
- selectedEvidenceIds.has(message.messageId),
- ) ||
- topic.failedToolCalls?.some(
- (toolCall) =>
- selectedEvidenceIds.has(toolCall.messageId) ||
- (toolCall.toolCallId && selectedEvidenceIds.has(toolCall.toolCallId)),
- ),
- ),
- };
- },
- getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>
- skillDocumentService.getSkill({
+ return skillDocumentService.getSkill({
agentDocumentId: skillDocumentId,
- agentId: targetAgentId,
+ agentId: targetAgentId ?? agentId,
includeContent: true,
- }),
- listSelfReviewProposals: ({ agentId: targetAgentId }) =>
- listServerSelfReviewProposalActivity({
- agentId: targetAgentId,
- briefModel,
- userId,
- }).then((digest) => [digest]),
- listManagedSkills: ({ agentId: targetAgentId }) =>
- skillDocumentService.listSkills({ agentId: targetAgentId }),
- preflight: async (input) => {
- if ('skillDocumentId' in input) {
- const result = await proposalPreflight.checkAction(createRefineProposalAction(input));
-
- return result.allowed ? { allowed: true } : { allowed: false, reason: result.reason };
- }
+ });
+ },
+ listManagedSkills: async (rawInput) => {
+ const { agentId: targetAgentId } = rawInput as { agentId?: string };
- return { allowed: true };
+ return skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
},
- readProposal: async ({ proposalId, proposalKey }) => {
+ listSelfReviewProposals: async (rawInput) => {
+ const { agentId: targetAgentId } = rawInput as { agentId?: string };
const digest = await listServerSelfReviewProposalActivity({
- agentId,
+ agentId: targetAgentId ?? agentId,
briefModel,
userId,
});
+ return [digest];
+ },
+ readSelfReviewProposal: async (rawInput) => {
+ const { proposalId, proposalKey } = rawInput as {
+ proposalId?: string;
+ proposalKey?: string;
+ };
+ const digest = await listServerSelfReviewProposalActivity({ agentId, briefModel, userId });
+
return digest.active.find(
(proposal) =>
(proposalId && proposal.proposalId === proposalId) ||
(proposalKey && proposal.proposalKey === proposalKey),
);
},
- refreshProposal: async (input: RefreshSelfReviewProposalInput) =>
- updateSelfReviewProposalBrief({
+ refreshSelfReviewProposal: async (rawInput) => {
+ const input = rawInput as unknown as RefreshSelfReviewProposalInput;
+
+ return updateSelfReviewProposalBrief({
agentId,
briefModel,
proposalId: input.proposalId,
@@ -798,13 +605,47 @@ export const createServerToolSet = ({
incoming: proposal,
now: new Date().toISOString(),
}),
- }),
- replaceSkill: async (input) => {
+ });
+ },
+ replaceSkillContentCAS: async (rawInput) => {
+ const input = rawInput as unknown as ReplaceSkillContentCASInput;
+ const enriched = await withCompleteReplaceSkillSnapshot({
+ agentId,
+ input,
+ snapshotService: proposalSnapshot,
+ userId,
+ });
+
+ if (!pickTrimmedString(enriched.bodyMarkdown)) {
+ return {
+ resourceId: enriched.skillDocumentId,
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a non-empty body.',
+ };
+ }
+
+ if (!isCompleteRefineToolSnapshot(enriched.baseSnapshot)) {
+ return {
+ resourceId: enriched.skillDocumentId,
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a complete base snapshot.',
+ };
+ }
+
+ const preflight = await proposalPreflight.checkAction(createRefineProposalAction(enriched));
+ if (!preflight.allowed) {
+ return {
+ resourceId: enriched.skillDocumentId,
+ status: 'skipped_stale',
+ summary: preflight.reason || input.summary,
+ };
+ }
+
const result = await skillDocumentService.replaceSkillIndex({
- agentDocumentId: input.skillDocumentId,
+ agentDocumentId: enriched.skillDocumentId,
agentId,
- bodyMarkdown: input.bodyMarkdown,
- description: input.description,
+ bodyMarkdown: enriched.bodyMarkdown,
+ description: enriched.description,
});
if (!result) throw new Error('Skill target not found');
@@ -814,9 +655,10 @@ export const createServerToolSet = ({
summary: `Refined managed skill ${result.name}.`,
};
},
- reserveOperation: reserveSelfIterationOperation,
- supersedeProposal: async (input: SupersedeSelfReviewProposalInput) =>
- updateSelfReviewProposalBrief({
+ supersedeSelfReviewProposal: async (rawInput) => {
+ const input = rawInput as unknown as SupersedeSelfReviewProposalInput;
+
+ return updateSelfReviewProposalBrief({
agentId,
briefModel,
proposalId: input.proposalId,
@@ -827,9 +669,48 @@ export const createServerToolSet = ({
now: new Date().toISOString(),
supersededBy: input.supersededBy,
}),
- }),
- writeReceipt: (input) => writeSelfReviewToolReceipt({ agentId, input, sourceId, userId }),
- });
+ });
+ },
+ writeMemory: async (rawInput) => {
+ const input = rawInput as unknown as WriteMemoryInput;
+ const memoryService = createMemoryService({
+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
+ const result = await runMemoryActionAgent(
+ {
+ agentId,
+ message: content,
+ reason: `Agent Signal self-review memory candidate from ${evidenceRefs.length} evidence refs.`,
+ },
+ { db, userId },
+ );
+
+ if (result.status !== 'applied') {
+ throw new Error(
+ result.detail ?? 'Memory action agent did not apply a durable memory write.',
+ );
+ }
+
+ return {
+ memoryId: idempotencyKey,
+ summary: result.detail ?? content,
+ };
+ },
+ });
+ const result = await memoryService.writeMemory({
+ evidenceRefs: input.evidenceRefs,
+ idempotencyKey: input.idempotencyKey,
+ input: {
+ content: input.content,
+ userId: input.userId,
+ },
+ });
+
+ return {
+ resourceId: result.memoryId,
+ summary: result.summary,
+ };
+ },
+ };
};
/**
@@ -1066,13 +947,6 @@ export const createServerSelfReviewPolicyOptions = ({
}));
},
});
- const briefWriter = createServerSelfReviewBriefWriter(db, userId);
- const resolveBriefTextTranslator = async ({ userId }: { userId: string }) => {
- const userInfo = await UserModel.getInfoForAIGeneration(db, userId);
- const { t } = await translation('home', userInfo.responseLanguage ?? 'en-US');
-
- return t;
- };
return {
acquireReviewGuard: (input) =>
@@ -1097,68 +971,6 @@ export const createServerSelfReviewPolicyOptions = ({
return targets.length > 0;
},
collectContext: (input) => collector.collect(input),
- runSelfReviewAgent: async ({ context, localDate, sourceId, userId: runnerUserId }) => {
- const briefTextTranslator = await resolveBriefTextTranslator({ userId: runnerUserId });
- const modelRuntime = await initModelRuntimeFromDB(
- db,
- runnerUserId,
- DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
- );
- const toolSet = createServerToolSet({
- agentId: context.agentId,
- briefModel,
- briefTextTranslator,
- context,
- db,
- localDate: localDate ?? context.reviewWindowEnd.slice(0, 10),
- proposalBriefWriter: briefWriter,
- skillDocumentService,
- sourceId,
- userId: runnerUserId,
- });
- const selfReviewAgentRunner = createAgentRunner({
- maxSteps: 10,
- run: async ({ context, localDate, maxSteps, reviewScope, sourceId, tools, userId }) => {
- const runtimeResult = await executeSelfIteration({
- agentId: context.agentId,
- context,
- maxSteps,
- model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,
- modelRuntime,
- sourceId,
- tools,
- userId,
- });
- const projected = projectRun({
- content: runtimeResult.content,
- localDate,
- outcomes: runtimeResult.writeOutcomes.map((outcome) => ({
- ...outcome.result,
- toolName: outcome.toolName,
- })),
- reviewScope,
- sourceId,
- toolCalls: runtimeResult.toolCalls,
- userId,
- });
-
- return {
- ...projected,
- stepCount: runtimeResult.stepCount,
- };
- },
- tools: toolSet,
- });
-
- return selfReviewAgentRunner.run({
- context,
- localDate,
- sourceId,
- userId: runnerUserId,
- });
- },
- resolveBriefTextTranslator,
- writeDailyBrief: (brief) => briefWriter.writeDailyBrief(brief),
- writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),
+ db,
};
};
diff --git a/src/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts b/src/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts
new file mode 100644
index 00000000000..e9769af3f5b
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives.ts
@@ -0,0 +1,202 @@
+import type { AgentSignalRuntimeService } from '@lobechat/builtin-tool-agent-signal';
+
+import type { LobeChatDatabase } from '@/database/type';
+import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';
+import type { SkillManagementDocumentService } from '@/server/services/skillManagement';
+
+import { createSelfReviewProposalPreflightService } from '../review/proposalPreflight';
+import { createSelfReviewProposalSnapshotService } from '../review/proposalSnapshot';
+import { Risk } from '../types';
+import type {
+ CreateSkillIfAbsentInput,
+ ReplaceSkillContentCASInput,
+ WriteMemoryInput,
+} from './shared';
+import { createMemoryService, createSkillManagementService } from './shared';
+
+export interface ResourceRuntimePrimitiveDeps {
+ agentId: string;
+ db: LobeChatDatabase;
+ /** Builds the memory-candidate reason; lets each mode tag its origin. */
+ memoryReason: (evidenceCount: number) => string;
+ skillDocumentService: SkillManagementDocumentService;
+ userId: string;
+}
+
+/**
+ * Builds the resource tool primitives shared by the reflection and
+ * self-feedback-intent execAgent runtimes — safe live-DB skill reads / writes
+ * plus user-memory writes, keyed to match the advertised resource api names.
+ *
+ * Pure like the review primitives: no `reserveOperation` / receipt /
+ * `completeOperation` side channel (idempotency + receipt projection live on
+ * the completion path), and no `getEvidenceDigest` — evidence is embedded in
+ * the agent's prompt, so these tools only touch live state.
+ */
+export const createResourceRuntimePrimitives = ({
+ agentId,
+ db,
+ memoryReason,
+ skillDocumentService,
+ userId,
+}: ResourceRuntimePrimitiveDeps): AgentSignalRuntimeService => {
+ const isSkillNameAvailable = async ({
+ agentId: targetAgentId,
+ name,
+ }: {
+ agentId?: string;
+ name: string;
+ }) => {
+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
+
+ return !skills.some((skill) => skill.name === name);
+ };
+ const readSkillTargetSnapshot = (skillDocumentId: string) =>
+ skillDocumentService.readSkillTargetSnapshot({ agentDocumentId: skillDocumentId, agentId });
+
+ const proposalPreflight = createSelfReviewProposalPreflightService({
+ isSkillNameAvailable,
+ readSkillTargetSnapshot,
+ });
+ const proposalSnapshot = createSelfReviewProposalSnapshotService({
+ isSkillNameAvailable,
+ readSkillTargetSnapshot,
+ });
+
+ const skillService = createSkillManagementService({
+ createSkill: async ({ input }) => {
+ const result = await skillDocumentService.createSkill({
+ agentId,
+ bodyMarkdown: input.bodyMarkdown ?? '',
+ description: input.description ?? 'Agent Signal managed skill.',
+ name: input.name ?? input.title ?? 'agent-signal-skill',
+ title: input.title ?? input.name ?? 'Agent Signal skill',
+ });
+
+ return {
+ skillDocumentId: result.bundle.agentDocumentId,
+ summary: `Created managed skill ${result.name}.`,
+ };
+ },
+ refineSkill: async ({ input }) => {
+ const result = await skillDocumentService.replaceSkillIndex({
+ agentDocumentId: input.skillDocumentId,
+ agentId,
+ bodyMarkdown: input.bodyMarkdown ?? '',
+ });
+
+ if (!result) throw new Error('Skill target not found');
+
+ return {
+ skillDocumentId: result.bundle.agentDocumentId,
+ summary: `Refined managed skill ${result.name}.`,
+ };
+ },
+ });
+
+ return {
+ createSkillIfAbsent: async (rawInput) => {
+ const input = rawInput as unknown as CreateSkillIfAbsentInput;
+ const result = await skillService.createSkill({
+ evidenceRefs: [],
+ idempotencyKey: input.idempotencyKey,
+ input,
+ });
+
+ return { resourceId: result.skillDocumentId, summary: result.summary };
+ },
+ getManagedSkill: async (rawInput) => {
+ const { agentId: targetAgentId, skillDocumentId } = rawInput as {
+ agentId?: string;
+ skillDocumentId: string;
+ };
+
+ return skillDocumentService.getSkill({
+ agentDocumentId: skillDocumentId,
+ agentId: targetAgentId ?? agentId,
+ includeContent: true,
+ });
+ },
+ listManagedSkills: async (rawInput) => {
+ const { agentId: targetAgentId } = rawInput as { agentId?: string };
+
+ return skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
+ },
+ replaceSkillContentCAS: async (rawInput) => {
+ const input = rawInput as unknown as ReplaceSkillContentCASInput;
+ const baseSnapshot = await proposalSnapshot.captureActionSnapshot({
+ actionType: 'refine_skill',
+ agentId,
+ input: { skillDocumentId: input.skillDocumentId },
+ userId,
+ });
+ const enriched = {
+ ...input,
+ baseSnapshot,
+ skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,
+ };
+
+ const preflight = await proposalPreflight.checkAction({
+ actionType: 'refine_skill',
+ baseSnapshot: enriched.baseSnapshot,
+ evidenceRefs: [],
+ idempotencyKey: enriched.idempotencyKey,
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: enriched.bodyMarkdown,
+ patch: enriched.summary,
+ skillDocumentId: enriched.skillDocumentId,
+ userId: enriched.userId,
+ },
+ operation: 'refine',
+ },
+ rationale: enriched.summary ?? `Refine managed skill ${enriched.skillDocumentId}.`,
+ risk: Risk.Low,
+ target: { skillDocumentId: enriched.skillDocumentId },
+ });
+
+ if (!preflight.allowed) {
+ return {
+ resourceId: enriched.skillDocumentId,
+ status: 'skipped_stale',
+ summary: preflight.reason || enriched.summary,
+ };
+ }
+
+ const result = await skillService.refineSkill({
+ evidenceRefs: [],
+ idempotencyKey: enriched.idempotencyKey,
+ input: enriched,
+ });
+
+ return { resourceId: result.skillDocumentId, summary: result.summary };
+ },
+ writeMemory: async (rawInput) => {
+ const input = rawInput as unknown as WriteMemoryInput;
+ const memoryService = createMemoryService({
+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
+ const result = await runMemoryActionAgent(
+ { agentId, message: content, reason: memoryReason(evidenceRefs.length) },
+ { db, userId },
+ );
+
+ if (result.status !== 'applied') {
+ throw new Error(
+ result.detail ?? 'Memory action agent did not apply a durable memory write.',
+ );
+ }
+
+ return { memoryId: idempotencyKey, summary: result.detail ?? content };
+ },
+ });
+ const result = await memoryService.writeMemory({
+ evidenceRefs: input.evidenceRefs,
+ idempotencyKey: input.idempotencyKey,
+ input: { content: input.content, userId: input.userId },
+ });
+
+ return { resourceId: result.memoryId, summary: result.summary };
+ },
+ };
+};
diff --git a/src/server/services/agentSignal/services/selfIteration/types.ts b/src/server/services/agentSignal/services/selfIteration/types.ts
index 27ad646ea7d..0ecb073944f 100644
--- a/src/server/services/agentSignal/services/selfIteration/types.ts
+++ b/src/server/services/agentSignal/services/selfIteration/types.ts
@@ -129,6 +129,8 @@ export enum ReviewRunStatus {
Collected = 'collected',
Completed = 'completed',
Deduped = 'deduped',
+ /** Background self-iteration run was enqueued via execAgent; outcome lands on completion. */
+ Dispatched = 'dispatched',
Failed = 'failed',
PartiallyApplied = 'partially_applied',
Planned = 'planned',
diff --git a/src/server/services/agentSignal/sources/__tests__/index.test.ts b/src/server/services/agentSignal/sources/__tests__/index.test.ts
index 518cc28f3fc..c5d4bd762ce 100644
--- a/src/server/services/agentSignal/sources/__tests__/index.test.ts
+++ b/src/server/services/agentSignal/sources/__tests__/index.test.ts
@@ -59,4 +59,31 @@ describe('agent signal sources', () => {
});
expect(result.trigger.windowEventCount).toBe(2);
});
+
+ it('carries the selfIteration payload through the agent.execution.completed renderer', async () => {
+ const { buildSource } = await import('..');
+
+ // Compact completion payload the CompletionLifecycle attaches; the renderer
+ // rebuilds the payload from an allow-list, so this field is the one that
+ // regressed — it MUST survive for the completion policy to project receipts.
+ const selfIteration = {
+ artifacts: [],
+ marker: { kind: 'memory', sourceId: 'src_1', topicId: 'topic_1' },
+ mutations: [
+ { apiName: 'writeMemory', data: { kind: 'mutation', status: 'applied' }, kind: 'mutation' },
+ ],
+ userId: 'user_1',
+ };
+
+ const built = buildSource({
+ payload: { agentId: 'agent_1', operationId: 'op_1', selfIteration, topicId: 'topic_1' },
+ scopeKey: 'topic:topic_1',
+ sourceId: 'op_1:complete:done',
+ sourceType: 'agent.execution.completed',
+ timestamp: 1_710_000_000_000,
+ });
+
+ expect(built.sourceType).toBe('agent.execution.completed');
+ expect(built.payload.selfIteration).toEqual(selfIteration);
+ });
});
diff --git a/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts b/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts
index ffc96e322e5..80e9f4c9ec8 100644
--- a/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts
+++ b/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts
@@ -10,6 +10,10 @@ export const agentExecutionCompletedRenderer = {
payload: {
agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
operationId: String(input.payload.operationId ?? input.sourceId),
+ // Compact self-iteration tool outcomes extracted from finalState by the
+ // completion lifecycle. Opaque here (validated downstream); MUST be
+ // carried through so the completion policy can project receipts/briefs.
+ selfIteration: input.payload.selfIteration,
serializedContext:
typeof input.payload.serializedContext === 'string'
? input.payload.serializedContext
diff --git a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index b06402b0091..fcce0a80bc4 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -11,6 +11,7 @@ import { AiAgentService } from '../index';
const {
mockCreateOperation,
mockGetAgentConfig,
+ mockGetBuiltinAgent,
mockGetInfoForAIGeneration,
mockIsAgentSignalEnabledForUser,
mockMessageCreate,
@@ -20,6 +21,7 @@ const {
} = vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
mockGetAgentConfig: vi.fn(),
+ mockGetBuiltinAgent: vi.fn(),
mockGetInfoForAIGeneration: vi.fn(),
mockIsAgentSignalEnabledForUser: vi.fn(),
mockMessageCreate: vi.fn(),
@@ -52,6 +54,7 @@ vi.mock('@/database/models/message', () => ({
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn().mockImplementation(() => ({
getAgentConfig: vi.fn(),
+ getBuiltinAgent: mockGetBuiltinAgent,
queryAgents: vi.fn().mockResolvedValue([]),
})),
}));
@@ -199,9 +202,42 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
operationId: 'op-123',
success: true,
});
+ mockGetBuiltinAgent.mockResolvedValue(null);
service = new AiAgentService(mockDb, userId);
});
+ it('materializes a builtin agent addressed by slug when no row exists yet', async () => {
+ // Background self-iteration runs dispatch via execAgent({ slug }) before any
+ // persisted row exists. The first resolve (by slug) misses; execAgent must
+ // lazily materialize the virtual builtin row (getBuiltinAgent) and re-resolve
+ // — without it the run throws `Agent not found: self-reflection`.
+ mockGetAgentConfig.mockResolvedValueOnce(null).mockResolvedValueOnce({
+ chatConfig: {},
+ id: 'agent-self-reflection',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug: 'self-reflection',
+ systemRole: '',
+ });
+ mockGetBuiltinAgent.mockResolvedValueOnce({ id: 'agent-self-reflection', slug: 'self-reflection' });
+
+ await service.execAgent({ prompt: 'reflect', slug: 'self-reflection' });
+
+ expect(mockGetBuiltinAgent).toHaveBeenCalledWith('self-reflection');
+ expect(mockCreateOperation).toHaveBeenCalledTimes(1);
+ expect(mockCreateOperation.mock.calls[0][0].agentConfig.slug).toBe('self-reflection');
+ });
+
+ it('throws for an unknown non-builtin identifier without materializing a row', async () => {
+ mockGetAgentConfig.mockResolvedValue(null);
+
+ await expect(service.execAgent({ agentId: 'does-not-exist', prompt: 'hi' })).rejects.toThrow(
+ 'Agent not found: does-not-exist',
+ );
+ expect(mockGetBuiltinAgent).not.toHaveBeenCalled();
+ });
+
it('should merge runtime systemRole for inbox agent when DB systemRole is empty', async () => {
// Inbox agent with no user-customized systemRole in DB
mockGetAgentConfig.mockResolvedValue({
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index e7111afe11f..41b8cd3d6d5 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -386,7 +386,16 @@ export class AiAgentService {
throwIfAborted(signal, 'Agent execution aborted before startup');
// 1. Get agent configuration with default config merged (supports both id and slug)
- const agentConfig = await this.agentService.getAgentConfig(identifier);
+ let agentConfig = await this.agentService.getAgentConfig(identifier);
+ // Builtin agents (inbox / page / task / self-iteration slugs) may be addressed
+ // purely by slug before a row exists — e.g. background self-iteration runs
+ // dispatched via execAgent({ slug }). Lazily materialize the virtual row from
+ // the builtin registry (mirrors the inbox/task `getBuiltinAgent` path) and
+ // re-resolve. No-op for ordinary agent ids (getBuiltinAgent returns null).
+ if (!agentConfig && (Object.values(BUILTIN_AGENT_SLUGS) as string[]).includes(identifier)) {
+ await this.agentModel.getBuiltinAgent(identifier);
+ agentConfig = await this.agentService.getAgentConfig(identifier);
+ }
if (!agentConfig) {
throw new Error(`Agent not found: ${identifier}`);
}
@@ -2175,7 +2184,17 @@ export class AiAgentService {
deviceSystemInfo: Object.keys(deviceSystemInfo).length > 0 ? deviceSystemInfo : undefined,
userTimezone,
appContext: {
- agentId: resolvedAgentId,
+ // Background self-iteration runs execute under a builtin slug (so they
+ // inherit the builtin agent's tools / systemRole / model), but their
+ // resource tools and receipts must attribute to the *reviewed* user
+ // agent, which rides on the marker. Prefer it so the tool-execution
+ // context (state.metadata.agentId) targets the reviewed agent; ordinary
+ // runs (no marker) fall back to the resolved executing agent.
+ agentId: appContext?.agentSignal?.agentId ?? resolvedAgentId,
+ // Run-scoped Agent Signal marker for background self-iteration / memory
+ // runs — lands in state.metadata.agentSignal so the completion path can
+ // project receipts/briefs. Undefined for ordinary chat runs.
+ ...(appContext?.agentSignal ? { agentSignal: appContext.agentSignal } : {}),
defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
documentId: appContext?.documentId,
groupId: appContext?.groupId,
diff --git a/src/server/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts b/src/server/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts
new file mode 100644
index 00000000000..96e1916e83a
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/agentSignalFeedbackIntent.ts
@@ -0,0 +1,45 @@
+import {
+ AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,
+ AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,
+ AgentSignalToolExecutionRuntime,
+} from '@lobechat/builtin-tool-agent-signal';
+
+import { createResourceRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives';
+import { SkillManagementDocumentService } from '@/server/services/skillManagement';
+
+import type { ServerRuntimeRegistration } from './types';
+
+/**
+ * Registers the self-feedback-intent builtin server runtime, so an `execAgent`
+ * run with `plugins: ['agent-signal-feedback-intent']` can execute its tools.
+ * It shares the reflection resource surface (safe skill reads / writes +
+ * user-memory writes) plus the artifact recorders the package runtime echoes;
+ * the distinct identifier keeps plugin routing and bookkeeping mode-specific.
+ *
+ * Not to be confused with the `declareSelfFeedbackIntent` fast-loop tool
+ * ({@link ./selfFeedbackIntent}) a live agent calls to enqueue a source event —
+ * this runtime backs the background agent that actions a declared intent.
+ */
+export const agentSignalFeedbackIntentRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ const { agentId, serverDB, userId } = context;
+ if (!agentId || !userId || !serverDB) {
+ throw new Error('agent-signal-feedback-intent requires agentId, userId and serverDB');
+ }
+
+ const service = createResourceRuntimePrimitives({
+ agentId,
+ db: serverDB,
+ memoryReason: (count) =>
+ `Agent Signal self-feedback intent memory candidate from ${count} evidence refs.`,
+ skillDocumentService: new SkillManagementDocumentService(serverDB, userId),
+ userId,
+ });
+
+ return new AgentSignalToolExecutionRuntime({
+ apiNames: AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,
+ service,
+ });
+ },
+ identifier: AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/agentSignalReflection.ts b/src/server/services/toolExecution/serverRuntimes/agentSignalReflection.ts
new file mode 100644
index 00000000000..562018e87e5
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/agentSignalReflection.ts
@@ -0,0 +1,41 @@
+import {
+ AGENT_SIGNAL_REFLECTION_IDENTIFIER,
+ AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,
+ AgentSignalToolExecutionRuntime,
+} from '@lobechat/builtin-tool-agent-signal';
+
+import { createResourceRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/tools/runtimePrimitives';
+import { SkillManagementDocumentService } from '@/server/services/skillManagement';
+
+import type { ServerRuntimeRegistration } from './types';
+
+/**
+ * Registers the post-turn self-reflection builtin server runtime, so an
+ * `execAgent` run with `plugins: ['agent-signal-reflection']` can execute its
+ * tools. The reflection surface is resource-only (safe skill reads / writes +
+ * user-memory writes) plus the artifact recorders, which the package runtime
+ * echoes. Evidence is embedded in the agent's prompt, so there is no collector.
+ */
+export const agentSignalReflectionRuntime: ServerRuntimeRegistration = {
+ factory: (context) => {
+ const { agentId, serverDB, userId } = context;
+ if (!agentId || !userId || !serverDB) {
+ throw new Error('agent-signal-reflection requires agentId, userId and serverDB');
+ }
+
+ const service = createResourceRuntimePrimitives({
+ agentId,
+ db: serverDB,
+ memoryReason: (count) =>
+ `Agent Signal self-reflection memory candidate from ${count} evidence refs.`,
+ skillDocumentService: new SkillManagementDocumentService(serverDB, userId),
+ userId,
+ });
+
+ return new AgentSignalToolExecutionRuntime({
+ apiNames: AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,
+ service,
+ });
+ },
+ identifier: AGENT_SIGNAL_REFLECTION_IDENTIFIER,
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/agentSignalReview.ts b/src/server/services/toolExecution/serverRuntimes/agentSignalReview.ts
new file mode 100644
index 00000000000..2860a91f2ec
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/agentSignalReview.ts
@@ -0,0 +1,71 @@
+import {
+ AGENT_SIGNAL_REVIEW_IDENTIFIER,
+ AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
+ AgentSignalToolExecutionRuntime,
+} from '@lobechat/builtin-tool-agent-signal';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { BriefModel } from '@/database/models/brief';
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
+import { readAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';
+import { createServerSelfReviewBriefWriter } from '@/server/services/agentSignal/services/selfIteration/review/brief';
+import { createReviewRuntimePrimitives } from '@/server/services/agentSignal/services/selfIteration/review/server';
+import { SkillManagementDocumentService } from '@/server/services/skillManagement';
+import { translation } from '@/server/translation';
+
+import type { ServerRuntimeRegistration } from './types';
+
+const resolveBriefTextTranslator = async (db: LobeChatDatabase, userId: string) => {
+ const userInfo = await UserModel.getInfoForAIGeneration(db, userId);
+ const { t } = await translation('home', userInfo.responseLanguage ?? 'en-US');
+
+ return t;
+};
+
+/**
+ * Registers the nightly-review self-iteration builtin server runtime, so an
+ * `execAgent` run with `plugins: ['agent-signal-review']` can execute its tools.
+ *
+ * The factory resolves the review window from the operation's `agentSignal`
+ * marker (the only per-run state a tool still needs — the evidence corpus is in
+ * the agent's prompt), builds the pure live-DB primitives from the execution
+ * context, and hands them to the package runtime. No evidence collector, no
+ * `createServerToolSet` side channel (dedupe / receipt / operation state).
+ */
+export const agentSignalReviewRuntime: ServerRuntimeRegistration = {
+ factory: async (context) => {
+ const { agentId, operationId, serverDB, userId } = context;
+ if (!agentId || !userId || !operationId || !serverDB) {
+ throw new Error('agent-signal-review requires agentId, userId, operationId and serverDB');
+ }
+
+ const operation = await new AgentOperationModel(serverDB, userId).findById(operationId);
+ const marker = readAgentSignalMarker(operation?.metadata);
+
+ const reviewWindowEnd = marker?.reviewWindowEnd ?? new Date(0).toISOString();
+ const reviewWindowStart = marker?.reviewWindowStart ?? new Date(0).toISOString();
+ const localDate = marker?.localDate ?? reviewWindowEnd.slice(0, 10);
+ const sourceId = marker?.sourceId ?? operationId;
+
+ const service = createReviewRuntimePrimitives({
+ agentId,
+ briefModel: new BriefModel(serverDB, userId),
+ briefTextTranslator: await resolveBriefTextTranslator(serverDB, userId),
+ db: serverDB,
+ localDate,
+ proposalBriefWriter: createServerSelfReviewBriefWriter(serverDB, userId),
+ reviewWindowEnd,
+ reviewWindowStart,
+ skillDocumentService: new SkillManagementDocumentService(serverDB, userId),
+ sourceId,
+ userId,
+ });
+
+ return new AgentSignalToolExecutionRuntime({
+ apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,
+ service,
+ });
+ },
+ identifier: AGENT_SIGNAL_REVIEW_IDENTIFIER,
+};
diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.ts
index e66b95e1205..bdf9a29287a 100644
--- a/src/server/services/toolExecution/serverRuntimes/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/index.ts
@@ -11,6 +11,9 @@ import { activatorRuntime } from './activator';
import { agentBuilderRuntime } from './agentBuilder';
import { agentDocumentsRuntime } from './agentDocuments';
import { agentManagementRuntime } from './agentManagement';
+import { agentSignalFeedbackIntentRuntime } from './agentSignalFeedbackIntent';
+import { agentSignalReflectionRuntime } from './agentSignalReflection';
+import { agentSignalReviewRuntime } from './agentSignalReview';
import { briefRuntime } from './brief';
import { calculatorRuntime } from './calculator';
import { cloudSandboxRuntime } from './cloudSandbox';
@@ -73,6 +76,9 @@ registerRuntimes([
webOnboardingRuntime,
lobeAgentRuntime,
selfFeedbackIntentRuntime,
+ agentSignalReviewRuntime,
+ agentSignalReflectionRuntime,
+ agentSignalFeedbackIntentRuntime,
]);
// ==================== Registry API ====================
diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.ts
index 3fbed3ad50d..e4087ef36ba 100644
--- a/src/server/workflows/agentSignal/__tests__/run.test.ts
+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts
@@ -9,7 +9,6 @@ import { describe, expect, it, vi } from 'vitest';
import { createProcedurePolicyOptions as createProcedurePolicyOptionsFixture } from '@/server/services/agentSignal/procedure';
import type { SelfReflectionReviewContext } from '@/server/services/agentSignal/services/selfIteration/reflection/handler';
import type { NightlyReviewContext } from '@/server/services/agentSignal/services/selfIteration/review/collect';
-import { ReviewRunStatus, Scope } from '@/server/services/agentSignal/services/selfIteration/types';
import type { AgentSignalPolicyStateStore } from '@/server/services/agentSignal/store/types';
import type { RunAgentSignalWorkflowDeps } from '@/server/workflows/agentSignal/run';
import { runAgentSignalWorkflow } from '@/server/workflows/agentSignal/run';
@@ -820,15 +819,8 @@ describe('runAgentSignalWorkflow', () => {
userId,
}),
),
- runSelfReviewAgent: vi.fn(async () => ({
- execution: { actions: [], status: ReviewRunStatus.Completed },
- projectionPlan: {
- actions: [],
- plannerVersion: 'test',
- reviewScope: Scope.Nightly,
- summary: 'Noop',
- },
- })),
+ db,
+ dispatch: vi.fn(async () => ({ operationId: 'op-self-iter-1', topicId: 'topic-1' })),
};
const createSelfReviewPolicyOptions: NonNullable<
RunAgentSignalWorkflowDeps['createSelfReviewPolicyOptions']
@@ -895,21 +887,8 @@ describe('runAgentSignalWorkflow', () => {
acquireReviewGuard: vi.fn(async () => true),
canRunReview: vi.fn(async () => true),
collectContext: vi.fn(async () => selfReflectionContext),
- executeSelfIteration: vi.fn(async () => ({
- actions: [],
- content: 'Noop',
- ideas: [],
- intents: [],
- status: ReviewRunStatus.Completed,
- stepCount: 0,
- toolCalls: [],
- usage: [],
- writeOutcomes: [],
- })),
- model: 'gpt-test',
- modelRuntime: { chat: vi.fn() },
- tools: {} as never,
- writeReceipt: vi.fn(async () => {}),
+ db,
+ dispatch: vi.fn(async () => ({ operationId: 'op-self-iter-1', topicId: 'topic-1' })),
};
const createSelfReflectionPolicyOptions: NonNullable<
RunAgentSignalWorkflowDeps['createSelfReflectionPolicyOptions']
@@ -968,21 +947,9 @@ describe('runAgentSignalWorkflow', () => {
const selfFeedbackIntentPolicyOptions = {
acquireReviewGuard: vi.fn(async () => true),
canRunReview: vi.fn(async () => true),
- executeSelfIteration: vi.fn(async () => ({
- actions: [],
- content: 'Noop',
- ideas: [],
- intents: [],
- status: ReviewRunStatus.Completed,
- stepCount: 0,
- toolCalls: [],
- usage: [],
- writeOutcomes: [],
- })),
- model: 'gpt-test',
- modelRuntime: { chat: vi.fn() },
- tools: {} as never,
- writeReceipt: vi.fn(async () => {}),
+ db,
+ dispatch: vi.fn(async () => ({ operationId: 'op-self-iter-1', topicId: 'topic-1' })),
+ enrichEvidence: vi.fn(async () => ({ evidenceRefs: [] })),
};
const createSelfFeedbackIntentPolicyOptions: NonNullable<
RunAgentSignalWorkflowDeps['createSelfFeedbackIntentPolicyOptions']