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.

✨ feat(agent-signal): defer skill synthesis to turn completion with trajectory evidence (#16342)

Arvin Xu83b99fc3f50c
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 7b278524060..adc179728dd 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -216,14 +216,16 @@ export class CompletionLifecycle {
*/
async emitSignalEvents(operationId: string, state: any, reason: string): Promise<SignalEvent[]> {
try {
- const { metadata } = this.buildLifecycleEvent(operationId, state, reason);
+ const { assistantMessageId, 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',
+ '[completion-lifecycle] emit agent.execution.completed op=%s userId=%s assistant=%s metaAssistant=%s selfIteration=%s',
operationId,
metadata?.userId || this.userId,
+ assistantMessageId ?? 'undefined',
+ metadata?.assistantMessageId ?? 'undefined',
selfIteration
? `kind=${selfIteration.marker?.kind} mutations=${selfIteration.mutations?.length}`
: 'ABSENT',
@@ -257,7 +259,20 @@ export class CompletionLifecycle {
{
payload: {
agentId: metadata?.agentId,
+ // Anchor the deferred skill synthesis to the completed assistant
+ // turn (LOBE-10802): the completion-stage skill handler walks
+ // this id back to the user message to read the parked candidate
+ // and seeds the skill under the assistant group. Resolved from
+ // the final assistant message row when operation metadata omits
+ // it (the server execAgent path).
+ anchorMessageId: assistantMessageId,
+ assistantMessageId,
operationId,
+ // Carry the completion reason so completion-stage consumers can
+ // tell a finished turn from a non-terminal pause
+ // (waiting_for_async_tool / waiting_for_human), which reuse this
+ // same source.
+ reason,
// 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.
@@ -450,11 +465,19 @@ export class CompletionLifecycle {
const lastAssistantMessage = messages
.slice()
.reverse()
- .find((m: { content?: unknown; role: string }) => m.role === 'assistant');
+ .find((m: { content?: unknown; id?: string; role: string }) => m.role === 'assistant');
const lastAssistantContent = lastAssistantMessage
? extractTextFromMessageContent(lastAssistantMessage.content)
: undefined;
+ // Operation-level metadata only carries `assistantMessageId` on the client
+ // runtime path; a server `execAgent` turn leaves it unset (`{}` in DB). Fall
+ // back to the persisted id on the final assistant message row in state so the
+ // completion event can anchor deferred skill synthesis to this turn
+ // (LOBE-10802). A metadata value, when present, still wins.
+ const assistantMessageId =
+ metadata?.assistantMessageId ?? (lastAssistantMessage as { id?: string } | undefined)?.id;
+
const attachments = extractOutboundAttachments(messages);
const duration = state?.createdAt
@@ -470,6 +493,7 @@ export class CompletionLifecycle {
const formattedError = state?.error ? formatErrorForState(state.error) : undefined;
return {
+ assistantMessageId,
event: {
agentId: metadata?.agentId || '',
attachments: attachments.length > 0 ? attachments : undefined,
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 0deeea2f431..3388884f12b 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -2,6 +2,7 @@
import { ChatErrorType } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import * as agentSignalService from '@/server/services/agentSignal';
import * as verifyServices from '@/server/services/verify';
import { CompletionLifecycle } from '../CompletionLifecycle';
@@ -224,6 +225,50 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {
expect(event.errorType).toBeUndefined();
expect(event.errorAttribution).toBeUndefined();
});
+
+ it('resolves assistantMessageId from the final assistant message row when metadata omits it', () => {
+ // Regression (LOBE-10802): a server execAgent turn carries operation-level
+ // metadata ({} in DB) with no assistantMessageId, so the completion event
+ // previously shipped assistantMessageId=undefined and the deferred
+ // skill-synthesis handler no-oped. The id must fall back to the persisted
+ // id on the final assistant message row in state.
+ const state = {
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ { content: 'tool result', id: 'msg-tool', role: 'tool' },
+ { content: 'final answer', id: 'msg-assistant', role: 'assistant' },
+ { content: 'trailing tool result', id: 'msg-tool-2', role: 'tool' },
+ ],
+ metadata: { agentId: 'agent-1', userId: 'user-1' },
+ };
+
+ const { assistantMessageId } = callBuild(state, 'done');
+
+ expect(assistantMessageId).toBe('msg-assistant');
+ });
+
+ it('prefers metadata.assistantMessageId over the state row (client runtime path)', () => {
+ // The client runtime path supplies assistantMessageId on operation metadata;
+ // it must win over the state-row fallback so the anchor stays the id the
+ // client already persisted the parked candidate against.
+ const state = {
+ messages: [{ content: 'final answer', id: 'msg-from-state', role: 'assistant' }],
+ metadata: { agentId: 'agent-1', assistantMessageId: 'msg-from-metadata' },
+ };
+
+ const { assistantMessageId } = callBuild(state, 'done');
+
+ expect(assistantMessageId).toBe('msg-from-metadata');
+ });
+
+ it('leaves assistantMessageId undefined when neither metadata nor a state row carries it', () => {
+ const { assistantMessageId } = callBuild(
+ { messages: [{ content: 'just a user prompt', role: 'user' }], metadata: {} },
+ 'done',
+ );
+
+ expect(assistantMessageId).toBeUndefined();
+ });
});
describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
@@ -364,3 +409,39 @@ describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
expect(unregisterSpy).toHaveBeenCalledWith('op-1');
});
});
+
+describe('CompletionLifecycle.emitSignalEvents β€” assistant anchor', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('ships the resolved assistantMessageId on the completed payload for a server turn', async () => {
+ // Regression (LOBE-10802): on a server execAgent turn the operation metadata
+ // has no assistantMessageId, so the agent.execution.completed event used to
+ // carry assistantMessageId=undefined and the deferred skill-synthesis handler
+ // no-oped. The payload must now anchor to the final assistant message row.
+ const emitSpy = vi
+ .spyOn(agentSignalService, 'emitAgentSignalSourceEvent')
+ .mockResolvedValue(undefined as any);
+
+ const lifecycle = buildLifecycle();
+ const state = {
+ messages: [
+ { content: 'user prompt', id: 'msg-user', role: 'user' },
+ { content: 'final answer', id: 'msg-assistant', role: 'assistant' },
+ ],
+ metadata: { agentId: 'agent-1', topicId: 'tpc-1', userId: 'user-1' },
+ stepCount: 2,
+ };
+
+ await lifecycle.emitSignalEvents('op-1', state, 'done');
+
+ expect(emitSpy).toHaveBeenCalledTimes(1);
+ const [emission] = emitSpy.mock.calls[0];
+ expect(emission.sourceType).toBe('agent.execution.completed');
+ expect(emission.payload).toMatchObject({
+ anchorMessageId: 'msg-assistant',
+ assistantMessageId: 'msg-assistant',
+ });
+ });
+});
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts
new file mode 100644
index 00000000000..0b3e8940a04
--- /dev/null
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts
@@ -0,0 +1,357 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
+import * as agentSignalService from '@/server/services/agentSignal';
+
+import type { RuntimeProcessorContext } from '../../../runtime/context';
+import { createCompletionSkillSynthesisSourceHandler } from '../completionSkillSynthesis';
+import type { PendingSkillSynthesis, RecordedSkillIntent } from '../skillIntentRecord';
+
+/**
+ * LOBE-10802 β€” deferred skill synthesis on `agent.execution.completed`.
+ *
+ * These tests pin the completion-stage handler in isolation: the parked
+ * candidate is read, the turn trajectory (tool sequence + final product) is
+ * assembled into the synthesis prompt, the skill seed anchors to the completed
+ * assistant message (not a floating mainline root), and the candidate is
+ * consumed exactly once so a duplicate completion cannot re-synthesize.
+ */
+
+const TOPIC_ID = 'tpc_1';
+const USER_MESSAGE_ID = 'msg_user';
+const ASSISTANT_MESSAGE_ID = 'msg_assistant';
+const USER_REQUEST =
+ 'Assign T199 to device 2, research and build an MVP, then write a complete report.';
+
+// The assistant turn's tool sequence β€” the reusable "how" that the inbound
+// prompt alone could not capture (it did not exist yet at user-message time).
+const ASSISTANT_TOOLS = [
+ { apiName: 'searchAgent', arguments: '{"query":"device 2"}', identifier: 'lobehub-agent' },
+ {
+ apiName: 'assignTask',
+ arguments: '{"taskId":"T199","deviceId":"cc-2"}',
+ identifier: 'lobehub-task',
+ },
+];
+
+const buildPendingSynthesis = (
+ overrides: Partial<PendingSkillSynthesis> = {},
+): PendingSkillSynthesis => ({
+ agentId: 'agent_1',
+ evidence: [
+ { cue: 'requested correction / new action', excerpt: 'reusable task execution pattern' },
+ ],
+ message: USER_REQUEST,
+ topicId: TOPIC_ID,
+ ...overrides,
+});
+
+const buildParkedRecord = (
+ pendingSynthesis: PendingSkillSynthesis | undefined,
+): RecordedSkillIntent => ({
+ createdAt: 1,
+ explicitness: 'implicit_strong_learning',
+ feedbackMessageId: USER_MESSAGE_ID,
+ reason: 'a reusable task execution pattern',
+ route: 'direct_decision',
+ scopeKey: `topic:${TOPIC_ID}`,
+ sourceId: USER_MESSAGE_ID,
+ ...(pendingSynthesis ? { pendingSynthesis } : {}),
+});
+
+// db.query.messages.findMany feeds assembleTrajectoryContext; ordering mirrors
+// the turn window (user request first, assistant product + tool calls last).
+const trajectoryRows = [
+ { content: USER_REQUEST, id: USER_MESSAGE_ID, role: 'user', tools: null },
+ {
+ content: 'T-199 已启动,初ζ­₯ MVP 与ζŠ₯ε‘Šε·²δΊ§ε‡Ίγ€‚',
+ id: ASSISTANT_MESSAGE_ID,
+ role: 'assistant',
+ tools: ASSISTANT_TOOLS,
+ },
+];
+
+// MessageModel.findById resolves through db.query.messages.findFirst; the handler
+// walks assistant -> user parent, so the two calls return in that order.
+const ASSISTANT_ROW = {
+ content: 'T-199 已启动',
+ createdAt: new Date(1000),
+ id: ASSISTANT_MESSAGE_ID,
+ parentId: USER_MESSAGE_ID,
+ role: 'assistant',
+ threadId: null,
+};
+const USER_ROW = {
+ content: USER_REQUEST,
+ createdAt: new Date(500),
+ id: USER_MESSAGE_ID,
+ parentId: null,
+ role: 'user',
+ threadId: null,
+};
+
+const createDb = () => {
+ const findFirst = vi.fn().mockResolvedValueOnce(ASSISTANT_ROW).mockResolvedValueOnce(USER_ROW);
+ const findMany = vi.fn().mockResolvedValue(trajectoryRows);
+ return { db: { query: { messages: { findFirst, findMany } } } as never, findFirst, findMany };
+};
+
+const createContext = (applied = false): RuntimeProcessorContext =>
+ ({
+ now: () => 1,
+ runtimeState: {
+ getGuardState: vi.fn().mockResolvedValue(applied ? { lastEventAt: 1 } : {}),
+ touchGuardState: vi.fn().mockResolvedValue({}),
+ },
+ scopeKey: `topic:${TOPIC_ID}`,
+ }) as unknown as RuntimeProcessorContext;
+
+// A normal, non-error, non-self-iteration completion for the user turn.
+const createSource = (payloadOverrides: Record<string, unknown> = {}) =>
+ ({
+ payload: {
+ agentId: 'agent_1',
+ anchorMessageId: ASSISTANT_MESSAGE_ID,
+ assistantMessageId: ASSISTANT_MESSAGE_ID,
+ operationId: 'op_run',
+ steps: 3,
+ topicId: TOPIC_ID,
+ ...payloadOverrides,
+ },
+ sourceId: 'src_completed',
+ sourceType: 'agent.execution.completed',
+ timestamp: 1,
+ }) as never;
+
+interface HarnessOptions {
+ pendingSynthesis?: PendingSkillSynthesis | undefined;
+ recordOverride?: RecordedSkillIntent | undefined | null;
+ selfIterationEnabled?: boolean;
+}
+
+const createHarness = (opts: HarnessOptions = {}) => {
+ const { selfIterationEnabled = true } = opts;
+ const record =
+ opts.recordOverride === undefined
+ ? buildParkedRecord(opts.pendingSynthesis ?? buildPendingSynthesis())
+ : (opts.recordOverride ?? undefined);
+
+ const read = vi.fn().mockResolvedValue(record);
+ const write = vi.fn().mockResolvedValue(undefined);
+ const dispatch = vi.fn().mockResolvedValue({ operationId: 'op_skill', topicId: TOPIC_ID });
+ const { db, findFirst, findMany } = createDb();
+
+ const handler = createCompletionSkillSynthesisSourceHandler({
+ db,
+ dispatch,
+ procedureState: { skillIntentRecords: { read, write } as never },
+ selfIterationEnabled,
+ userId: 'user_1',
+ });
+
+ return { dispatch, findFirst, findMany, handler, read, write };
+};
+
+describe('createCompletionSkillSynthesisSourceHandler', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('listens on agent.execution.completed', () => {
+ const { handler } = createHarness();
+ expect(handler.listen).toBe('agent.execution.completed');
+ expect(handler.type).toBe('source');
+ });
+
+ it('synthesizes the parked candidate off the completed-turn trajectory and anchors to the assistant turn', async () => {
+ const { dispatch, handler, write } = createHarness();
+
+ await handler.handle(createSource(), createContext());
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ const dispatched = dispatch.mock.calls[0][0];
+
+ // Acceptance: the seed anchors to the completed assistant turn, not the user
+ // message β€” so it is not a floating `parent_id=null` mainline root.
+ expect(dispatched.marker.anchorMessageId).toBe(ASSISTANT_MESSAGE_ID);
+ expect(dispatched.sourceMessageId).toBe(ASSISTANT_MESSAGE_ID);
+ expect(dispatched.marker.triggerMessageId).toBe(USER_MESSAGE_ID);
+
+ // Acceptance: the synthesis prompt carries the tool sequence + final product
+ // (trajectory), not just the user prompt.
+ expect(dispatched.prompt).toContain(USER_REQUEST);
+ expect(dispatched.prompt).toContain('lobehub-task.assignTask');
+ expect(dispatched.prompt).toContain('lobehub-agent.searchAgent');
+ expect(dispatched.prompt).toContain('completion_trajectory');
+ expect(dispatched.prompt).toContain('<turn_trajectory>');
+
+ // Acceptance: the parked candidate is consumed exactly once on a genuine
+ // dispatch so a duplicate completion cannot re-synthesize.
+ expect(write).toHaveBeenCalledWith(
+ expect.objectContaining({ feedbackMessageId: USER_MESSAGE_ID, pendingSynthesis: undefined }),
+ );
+ });
+
+ it('does not re-synthesize when the action already applied (idempotency)', async () => {
+ const { dispatch, handler, write } = createHarness();
+
+ // Guard reports the action already applied β€” a duplicate completion (retry).
+ await handler.handle(createSource(), createContext(true));
+
+ expect(dispatch).not.toHaveBeenCalled();
+ // A skipped (already-applied) attempt must not consume the candidate again.
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when no candidate was parked', async () => {
+ const { dispatch, handler, write } = createHarness({ recordOverride: null });
+
+ await handler.handle(createSource(), createContext());
+
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(write).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when the parked record carries no synthesis payload', async () => {
+ const { dispatch, handler } = createHarness({
+ recordOverride: buildParkedRecord(undefined),
+ });
+
+ await handler.handle(createSource(), createContext());
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('skips self-iteration completions without reading the candidate', async () => {
+ const { dispatch, findFirst, handler, read } = createHarness();
+
+ await handler.handle(createSource({ selfIteration: { kind: 'skill' } }), createContext());
+
+ expect(read).not.toHaveBeenCalled();
+ // Returns before hydrating the turn β€” no message reads, no dispatch.
+ expect(findFirst).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when self-iteration is disabled', async () => {
+ const { dispatch, handler, read } = createHarness({ selfIterationEnabled: false });
+
+ await handler.handle(createSource(), createContext());
+
+ expect(read).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ // `agent.execution.completed` is reused for non-terminal pauses β€” the turn's
+ // final assistant product doesn't exist yet, so the handler must not read or
+ // consume the parked candidate (the later real completion does the synthesis).
+ it.each(['waiting_for_async_tool', 'waiting_for_human'])(
+ 'skips the non-terminal park completion %s without consuming the candidate',
+ async (reason) => {
+ const { dispatch, findFirst, handler, read } = createHarness();
+
+ await handler.handle(createSource({ reason }), createContext());
+
+ expect(read).not.toHaveBeenCalled();
+ expect(findFirst).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ },
+ );
+});
+
+/**
+ * End-to-end across the seam the LOBE-10802 bug lived in: emit the completion
+ * event from a *server execAgent* state whose operation metadata carries NO
+ * per-turn `assistantMessageId` (DB shape: `{}` + agentId/topicId/userId), then
+ * feed the emitted payload straight into the completion-skill-synthesis handler.
+ *
+ * The whole logic chain runs in-process β€” no QStash, no HTTP. The earlier
+ * handler tests hardcoded `assistantMessageId` in `createSource()`, which masked
+ * this gap; here the anchor is whatever `CompletionLifecycle.emitSignalEvents`
+ * actually produces, so a regression in the resolution breaks the dispatch.
+ */
+describe('completion skill synthesis end-to-end (emit -> handler, no operation-metadata anchor)', () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // Run the real emit path over a server-turn state and return the emitted
+ // `agent.execution.completed` payload (the contract the handler consumes).
+ const emitCompletedPayload = async (messages: unknown[]) => {
+ const captured: Array<{ payload?: any; sourceType?: string }> = [];
+ vi.spyOn(agentSignalService, 'emitAgentSignalSourceEvent').mockImplementation((async (
+ emission: any,
+ ) => {
+ captured.push(emission);
+ return undefined;
+ }) as never);
+
+ const lifecycle = new CompletionLifecycle({} as never, 'user_1');
+ await lifecycle.emitSignalEvents(
+ 'op_run',
+ {
+ messages,
+ // Operation-level metadata only β€” no per-turn assistantMessageId, exactly
+ // as a server execAgent turn persists it.
+ metadata: { agentId: 'agent_1', topicId: TOPIC_ID, userId: 'user_1' },
+ stepCount: 3,
+ status: 'done',
+ },
+ 'done',
+ );
+
+ return captured.find((e) => e.sourceType === 'agent.execution.completed')?.payload;
+ };
+
+ const sourceFromPayload = (payload: unknown) =>
+ ({
+ payload,
+ sourceId: 'op_run:complete:done',
+ sourceType: 'agent.execution.completed',
+ timestamp: 1,
+ }) as never;
+
+ it('resolves the anchor from the assistant row and drives the handler to dispatch + consume', async () => {
+ const payload = await emitCompletedPayload([
+ { content: USER_REQUEST, id: USER_MESSAGE_ID, role: 'user' },
+ { content: 'T-199 已启动', id: ASSISTANT_MESSAGE_ID, role: 'assistant' },
+ ]);
+
+ // The fix: the completion event carries the resolved assistant anchor even
+ // though operation metadata never held it.
+ expect(payload.assistantMessageId).toBe(ASSISTANT_MESSAGE_ID);
+ expect(payload.anchorMessageId).toBe(ASSISTANT_MESSAGE_ID);
+
+ // Feed the emitted payload through the real handler β€” the orchestration seam.
+ const { dispatch, handler, write } = createHarness();
+ await handler.handle(sourceFromPayload(payload), createContext());
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ const dispatched = dispatch.mock.calls[0][0];
+ expect(dispatched.marker.anchorMessageId).toBe(ASSISTANT_MESSAGE_ID);
+ expect(dispatched.sourceMessageId).toBe(ASSISTANT_MESSAGE_ID);
+ expect(dispatched.prompt).toContain('<turn_trajectory>');
+ expect(dispatched.prompt).toContain('lobehub-task.assignTask');
+ // The parked candidate is consumed so a duplicate completion cannot re-run.
+ expect(write).toHaveBeenCalledWith(
+ expect.objectContaining({ feedbackMessageId: USER_MESSAGE_ID, pendingSynthesis: undefined }),
+ );
+ });
+
+ it('pre-fix shape (no assistant turn, no metadata anchor) emits an undefined anchor and the handler no-ops', async () => {
+ // Reproduces the blocking defect's signal: with no assistant turn in state
+ // and none on metadata, the completion event ships no anchor at all.
+ const payload = await emitCompletedPayload([
+ { content: USER_REQUEST, id: USER_MESSAGE_ID, role: 'user' },
+ ]);
+
+ expect(payload.assistantMessageId).toBeUndefined();
+
+ const { dispatch, handler } = createHarness();
+ await handler.handle(sourceFromPayload(payload), createContext());
+
+ // The handler gates on the missing anchor β€” exactly the live Layer-4 no-op.
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
index f5eff3f04e1..bbc9bb89993 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
@@ -430,6 +430,70 @@ describe('feedbackActionPlanner', () => {
);
});
+ /**
+ * @example
+ * LOBE-10802: a server execAgent inbound skill candidate (trigger is neither
+ * `client.runtime.*` nor an agent-signal self-iteration run) is parked WITH a
+ * synthesis payload and NOT dispatched on the user prompt alone β€” the deferred
+ * completion-stage handler synthesizes it off the full trajectory instead.
+ */
+ it('parks a server-inbound skill candidate until agent.execution.completed', async () => {
+ const store = createStore();
+ const procedure = createProcedurePolicyOptions({
+ now: () => 123,
+ policyStateStore: store,
+ ttlSeconds: 3600,
+ });
+ const writeIntentRecord = vi.spyOn(procedure.procedureState.skillIntentRecords!, 'write');
+ const skillActions = { prepare: vi.fn() };
+ const handler = createFeedbackActionPlannerSignalHandler({
+ actionServices: {
+ memoryActions: { prepare: vi.fn() },
+ skillActions: skillActions as never,
+ },
+ procedure: {
+ now: () => 123,
+ procedureState: procedure.procedureState,
+ },
+ });
+ const signal = createDomainSignal({
+ message: 'Assign T199 to device 2, research and build an MVP, then write a report.',
+ messageId: 'msg_skill_server',
+ satisfactionResult: 'not_satisfied',
+ signalId: 'sig_skill_server',
+ skillActionIntent: 'create',
+ skillIntentConfidence: 0.9,
+ skillIntentExplicitness: 'implicit_strong_learning',
+ skillIntentReason: 'a reusable task execution pattern',
+ skillRoute: 'direct_decision',
+ sourceId: 'source_skill_server',
+ target: 'skill',
+ // A server execAgent inbound trigger β€” not client.runtime.* and not the
+ // agent-signal self-iteration trigger β€” so it reaches the deferred lane.
+ trigger: 'bot',
+ });
+
+ const result = await handler.handle(signal, context);
+
+ expect(result).toEqual({
+ concluded: { reason: 'skill candidate parked until agent.execution.completed' },
+ status: 'conclude',
+ });
+ // Crucially: no inbound dispatch β€” synthesis is deferred, not run on the prompt.
+ expect(skillActions.prepare).not.toHaveBeenCalled();
+ // The parked record carries the synthesis payload (message) for the
+ // completion-stage handler to act on once the trajectory exists.
+ expect(writeIntentRecord).toHaveBeenCalledWith(
+ expect.objectContaining({
+ feedbackMessageId: 'msg_skill_server',
+ route: 'direct_decision',
+ pendingSynthesis: expect.objectContaining({
+ message: 'Assign T199 to device 2, research and build an MVP, then write a report.',
+ }),
+ }),
+ );
+ });
+
/**
* @example
* Completion-triggered direct skill intent is allowed to mutate skills.
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
index 8f11818b92b..e651fb6bfb7 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
@@ -153,7 +153,14 @@ export const executeSkillManagementAction = async (
}
const sourceId = idempotencyKey ?? action.actionId;
- const { messageId, topicId } = action.payload;
+ const { assistantMessageId, messageId, topicId } = action.payload;
+
+ // Anchor the skill seed under the completed assistant turn when the synthesis
+ // ran deferred at `agent.execution.completed` (LOBE-10802); fall back to the
+ // user message for the legacy inbound dispatch. Anchoring to the assistant
+ // message keeps the seed inside the assistant group instead of surfacing as a
+ // floating `parent_id=null` mainline root.
+ const anchorMessageId = assistantMessageId ?? messageId;
const prompt = buildSkillFeedbackPrompt({
agentId,
@@ -172,7 +179,8 @@ export const executeSkillManagementAction = async (
agentId,
kind: 'skill',
sourceId,
- ...(messageId ? { anchorMessageId: messageId, triggerMessageId: messageId } : {}),
+ ...(anchorMessageId ? { anchorMessageId } : {}),
+ ...(messageId ? { triggerMessageId: messageId } : {}),
...(topicId ? { topicId } : {}),
};
@@ -183,7 +191,7 @@ export const executeSkillManagementAction = async (
marker,
prompt,
slug: BUILTIN_AGENT_SLUGS.skillManagement,
- ...(messageId ? { sourceMessageId: messageId } : {}),
+ ...(anchorMessageId ? { sourceMessageId: anchorMessageId } : {}),
threadTitle: 'Agent Signal Skill',
...(topicId ? { topicId } : {}),
userId: options.userId,
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts
new file mode 100644
index 00000000000..f4b464cde5e
--- /dev/null
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts
@@ -0,0 +1,308 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { messages } from '@lobechat/database/schemas';
+import debug from 'debug';
+import { and, asc, eq, gte, isNull } from 'drizzle-orm';
+
+import { MessageModel } from '@/database/models/message';
+import type { LobeChatDatabase } from '@/database/type';
+import { buildWorkspaceWhere } from '@/database/utils/workspace';
+
+import type { RuntimeProcessorContext } from '../../runtime/context';
+import { defineSourceHandler } from '../../runtime/middleware';
+import {
+ type ActionSkillManagementHandle,
+ AGENT_SIGNAL_POLICY_ACTION_TYPES,
+ type AgentSignalFeedbackEvidence,
+} from '../types';
+import type { SkillManagementActionHandlerOptions } from './actions';
+import { executeSkillManagementAction } from './actions';
+
+const log = debug('lobe-server:agent-signal:completion-skill-synthesis');
+
+/** Cap on the number of turn messages serialized into the trajectory context. */
+const MAX_TRAJECTORY_MESSAGES = 40;
+
+const escapeXml = (value: string) =>
+ value
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&apos;');
+
+type CompletedTurnMessage = {
+ content: string | null;
+ id: string;
+ role: string;
+ tools: unknown;
+};
+
+interface CompletedTurnAnchors {
+ /** Thread the completed turn ran under (assistant row), null on the main line. */
+ threadId?: string;
+ /** Start of the turn window β€” the initiating user message timestamp. */
+ turnStartAt: Date;
+ /** Id of the user message that initiated the completed turn. */
+ userMessageId: string;
+}
+
+/**
+ * Resolves the user message that initiated the completed turn by walking the
+ * assistant message's parent chain (mirrors the `client.runtime.complete`
+ * hydration). Returns undefined when the assistant message is missing, is not an
+ * assistant turn, or has no user ancestor with content.
+ */
+const resolveCompletedTurnAnchors = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+ assistantMessageId: string,
+): Promise<CompletedTurnAnchors | undefined> => {
+ const messageModel = new MessageModel(db, userId, workspaceId);
+ const assistant = await messageModel.findById(assistantMessageId);
+ if (!assistant || assistant.role !== 'assistant') return undefined;
+
+ const threadId = assistant.threadId ?? undefined;
+ let parentId = assistant.parentId;
+ const visited = new Set<string>([assistant.id]);
+
+ while (typeof parentId === 'string') {
+ if (visited.has(parentId)) return undefined;
+ visited.add(parentId);
+
+ const parent = await messageModel.findById(parentId);
+ if (!parent) return undefined;
+ if (parent.role === 'user') {
+ if (!parent.content) return undefined;
+ return {
+ ...(threadId ? { threadId } : {}),
+ turnStartAt: parent.createdAt,
+ userMessageId: parent.id,
+ };
+ }
+
+ parentId = parent.parentId;
+ }
+
+ return undefined;
+};
+
+const renderToolCalls = (tools: unknown): string => {
+ if (!Array.isArray(tools)) return '';
+
+ return tools
+ .map((tool) => {
+ if (!tool || typeof tool !== 'object') return '';
+ const {
+ apiName,
+ arguments: args,
+ identifier,
+ } = tool as {
+ apiName?: string;
+ arguments?: string;
+ identifier?: string;
+ };
+ const name = [identifier, apiName].filter(Boolean).join('.') || 'tool';
+ const argText = typeof args === 'string' ? args : '';
+
+ return `<tool_call name="${escapeXml(name)}">${escapeXml(argText)}</tool_call>`;
+ })
+ .filter(Boolean)
+ .join('');
+};
+
+const renderTrajectoryMessage = (message: CompletedTurnMessage): string => {
+ const content = escapeXml((message.content ?? '').trim());
+ const toolCalls = message.role === 'assistant' ? renderToolCalls(message.tools) : '';
+
+ return [
+ `<message id="${escapeXml(message.id)}" role="${escapeXml(message.role)}">`,
+ `<content>${content}</content>`,
+ toolCalls,
+ `</message>`,
+ ].join('');
+};
+
+/**
+ * Assembles the completed-turn trajectory (user request, the tool-call sequence,
+ * tool results, and the final assistant product) into one XML envelope used as
+ * the deferred skill synthesis context. This is the evidence the inbound prompt
+ * alone could not provide (LOBE-10802 acceptance: evidence carries the tool
+ * sequence + final product, not just the user prompt).
+ */
+const assembleTrajectoryContext = async (input: {
+ db: LobeChatDatabase;
+ threadId?: string;
+ topicId: string;
+ turnStartAt: Date;
+ userId: string;
+ workspaceId?: string;
+}): Promise<{ serializedContext: string; toolNames: string[] }> => {
+ const threadScopeFilter =
+ typeof input.threadId === 'string'
+ ? eq(messages.threadId, input.threadId)
+ : isNull(messages.threadId);
+
+ const rows = (await input.db.query.messages.findMany({
+ columns: { content: true, id: true, role: true, tools: true },
+ limit: MAX_TRAJECTORY_MESSAGES,
+ orderBy: [asc(messages.createdAt)],
+ where: and(
+ buildWorkspaceWhere({ userId: input.userId, workspaceId: input.workspaceId }, messages),
+ eq(messages.topicId, input.topicId),
+ gte(messages.createdAt, input.turnStartAt),
+ threadScopeFilter,
+ ),
+ })) as CompletedTurnMessage[];
+
+ const toolNames = rows
+ .filter((row) => row.role === 'assistant' && Array.isArray(row.tools))
+ .flatMap((row) =>
+ (row.tools as Array<{ apiName?: string; identifier?: string }>).map((tool) =>
+ [tool?.identifier, tool?.apiName].filter(Boolean).join('.'),
+ ),
+ )
+ .filter(Boolean);
+
+ const serializedContext = [
+ '<turn_trajectory>',
+ rows.map(renderTrajectoryMessage).join(''),
+ '</turn_trajectory>',
+ ].join('');
+
+ return { serializedContext, toolNames };
+};
+
+/**
+ * Options for the deferred completion-stage skill synthesis source handler.
+ * Reuses the skill-management action handler dependencies; `procedureState`
+ * provides the parked-candidate store.
+ */
+export type CompletionSkillSynthesisOptions = SkillManagementActionHandlerOptions;
+
+/**
+ * Builds the `agent.execution.completed` source handler that performs deferred
+ * skill synthesis (LOBE-10802).
+ *
+ * For a normal, non-error, non-self-iteration server execAgent turn it:
+ * 1. Hydrates the completed turn (assistant -> user parent).
+ * 2. Reads the candidate the inbound `agent.user.message` detect stage parked.
+ * 3. Assembles the turn trajectory (tool sequence + final product) as context.
+ * 4. Dispatches the skill-management run anchored to the assistant message,
+ * consuming the parked candidate so it synthesizes exactly once.
+ *
+ * Self-iteration completions (the skill run's own completion) carry a
+ * `selfIteration` payload and are skipped, preventing recursion.
+ */
+export const createCompletionSkillSynthesisSourceHandler = (
+ options: CompletionSkillSynthesisOptions,
+) =>
+ defineSourceHandler(
+ AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted,
+ 'agent.execution.completed:skill-synthesis',
+ async (source, ctx: RuntimeProcessorContext): Promise<void> => {
+ const payload = source.payload;
+ // Self-iteration runs (including the skill-management run itself) carry a
+ // marker-derived selfIteration payload β€” never re-synthesize from them.
+ if (payload.selfIteration) return;
+ // `agent.execution.completed` is reused for non-terminal pauses
+ // (waiting_for_async_tool / waiting_for_human): the turn's final assistant
+ // product doesn't exist yet, so synthesizing now would read a partial
+ // trajectory and consume the parked candidate before the real completion.
+ if (payload.reason === 'waiting_for_async_tool' || payload.reason === 'waiting_for_human') {
+ return;
+ }
+ if (!options.selfIterationEnabled) return;
+
+ const skillIntentRecords = options.procedureState?.skillIntentRecords;
+ if (!skillIntentRecords?.read) return;
+
+ const assistantMessageId = payload.assistantMessageId ?? payload.anchorMessageId;
+ const { topicId } = payload;
+ if (!assistantMessageId || !topicId) return;
+
+ const anchors = await resolveCompletedTurnAnchors(
+ options.db,
+ options.userId,
+ options.workspaceId,
+ assistantMessageId,
+ );
+ if (!anchors) return;
+ const { threadId, turnStartAt, userMessageId } = anchors;
+
+ const record = await skillIntentRecords.read({
+ scopeKey: ctx.scopeKey,
+ sourceId: userMessageId,
+ });
+ // No parked candidate (or a client-runtime record without a synthesis
+ // payload) β€” this turn is not a deferred skill candidate; no-op.
+ if (!record?.pendingSynthesis) return;
+
+ const { pendingSynthesis } = record;
+
+ const { serializedContext, toolNames } = await assembleTrajectoryContext({
+ db: options.db,
+ ...(threadId ? { threadId } : {}),
+ topicId,
+ turnStartAt,
+ userId: options.userId,
+ ...(options.workspaceId ? { workspaceId: options.workspaceId } : {}),
+ });
+
+ const trajectoryEvidence: AgentSignalFeedbackEvidence[] = toolNames.length
+ ? [
+ {
+ cue: 'completion_trajectory',
+ excerpt: `Executed tools: ${[...new Set(toolNames)].join(', ')}`,
+ },
+ ]
+ : [];
+
+ const idempotencyKey = `${userMessageId}:skill:${userMessageId}`;
+ const action: ActionSkillManagementHandle = {
+ actionId: `${assistantMessageId}:completion:${userMessageId}:skill-management`,
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
+ chain: { rootSourceId: userMessageId },
+ payload: {
+ ...((pendingSynthesis.agentId ?? payload.agentId)
+ ? { agentId: pendingSynthesis.agentId ?? payload.agentId }
+ : {}),
+ assistantMessageId,
+ ...(pendingSynthesis.conflictPolicy
+ ? { conflictPolicy: pendingSynthesis.conflictPolicy }
+ : {}),
+ evidence: [...trajectoryEvidence, ...(pendingSynthesis.evidence ?? [])],
+ idempotencyKey,
+ message: pendingSynthesis.message,
+ messageId: userMessageId,
+ ...(record.reason ? { reason: record.reason } : {}),
+ serializedContext,
+ ...(pendingSynthesis.sourceHints ? { sourceHints: pendingSynthesis.sourceHints } : {}),
+ topicId,
+ },
+ signal: {
+ signalId: `${userMessageId}:skill-synthesis`,
+ signalType: 'signal.feedback.domain.skill',
+ },
+ source: { sourceId: source.sourceId, sourceType: source.sourceType },
+ timestamp: source.timestamp,
+ };
+
+ log(
+ '[completion-skill-synthesis] dispatching deferred skill synthesis user=%s assistant=%s op=%s tools=%d',
+ userMessageId,
+ assistantMessageId,
+ payload.operationId,
+ toolNames.length,
+ );
+
+ const result = await executeSkillManagementAction(action, options, ctx);
+
+ // Consume the parked candidate so a duplicate completion (retry / repair)
+ // cannot re-synthesize. Only on a genuine dispatch β€” a skipped idempotent
+ // attempt already synthesized, and a failure should stay retryable.
+ if (result.status === 'applied' && skillIntentRecords.write) {
+ await skillIntentRecords.write({ ...record, pendingSynthesis: undefined });
+ }
+ },
+ );
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
index 32b2659a9de..4da31212440 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
@@ -3,6 +3,7 @@ import type {
RuntimeProcessorResult,
} from '@lobechat/agent-signal';
import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { RequestTrigger } from '@lobechat/types';
import type {
AgentSignalProcedureMarker,
@@ -32,7 +33,7 @@ import { createDefaultActionServices } from '../../services/actionServices';
import type { ProcedureMarkerSuppressInput, ProcedureStateService } from '../../services/types';
import type { SignalFeedbackDomainMemory } from '../types';
import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../types';
-import type { RecordedSkillIntent } from './skillIntentRecord';
+import type { PendingSkillSynthesis, RecordedSkillIntent } from './skillIntentRecord';
/**
* Weak positive skill feedback needs repeated observations before the accumulator emits.
@@ -123,6 +124,39 @@ const detectClientComplete = (signal: FeedbackDomainSignal) => {
return signal.payload.trigger === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete;
};
+/**
+ * Detects a server execAgent inbound skill candidate that should be parked and
+ * synthesized after the run finishes (LOBE-10802), rather than dispatched on the
+ * user message alone. The client-runtime lane parks/synthesizes through its own
+ * `client.runtime.start` / `client.runtime.complete` pair and is never re-routed
+ * here; agent-signal self-iteration runs are suppressed upstream but guarded too.
+ */
+const detectServerInboundDeferredSkill = (signal: FeedbackDomainSignal): boolean => {
+ const { trigger } = signal.payload;
+ if (!trigger) return false;
+ if (trigger === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart) return false;
+ if (trigger === AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete) return false;
+ if (trigger === RequestTrigger.AgentSignal) return false;
+
+ return true;
+};
+
+/**
+ * Builds the synthesis payload parked with a deferred server-inbound skill
+ * candidate. Carries only the inbound-stage facts the completion handler cannot
+ * recover on its own; the trajectory evidence is assembled fresh at completion.
+ */
+const buildPendingSkillSynthesis = (
+ signal: NonSatisfiedSkillActionServiceSignal,
+): PendingSkillSynthesis => ({
+ ...(signal.payload.agentId ? { agentId: signal.payload.agentId } : {}),
+ ...(signal.payload.conflictPolicy ? { conflictPolicy: signal.payload.conflictPolicy } : {}),
+ ...(signal.payload.evidence?.length ? { evidence: signal.payload.evidence } : {}),
+ message: signal.payload.message,
+ ...(signal.payload.sourceHints ? { sourceHints: signal.payload.sourceHints } : {}),
+ ...(signal.payload.topicId ? { topicId: signal.payload.topicId } : {}),
+});
+
const findCompletionHintedDocumentReceipts = async (
signal: FeedbackDomainSignal,
context: RuntimeProcessorContext,
@@ -185,6 +219,7 @@ const createHintedDocumentSkillSignal = (
const createRecordedSkillIntent = (
signal: NonSatisfiedSkillActionServiceSignal,
context: RuntimeProcessorContext,
+ options?: { withSynthesis?: boolean },
): RecordedSkillIntent => ({
...(signal.payload.skillActionIntent ? { actionIntent: signal.payload.skillActionIntent } : {}),
...(typeof signal.payload.skillIntentConfidence === 'number'
@@ -193,6 +228,7 @@ const createRecordedSkillIntent = (
createdAt: context.now(),
explicitness: signal.payload.skillIntentExplicitness ?? 'weak_positive',
feedbackMessageId: signal.payload.messageId,
+ ...(options?.withSynthesis ? { pendingSynthesis: buildPendingSkillSynthesis(signal) } : {}),
...(signal.payload.skillIntentReason || signal.payload.reason
? { reason: signal.payload.skillIntentReason ?? signal.payload.reason }
: {}),
@@ -450,6 +486,24 @@ export const createFeedbackActionPlannerSignalHandler = (
};
}
+ // Defer server execAgent inbound synthesis to agent.execution.completed
+ // (LOBE-10802): park the candidate with its synthesis payload so the
+ // completion-stage handler synthesizes from the full trajectory (tool
+ // sequence + final product) instead of the user prompt alone. Only when
+ // the intent-record store is wired β€” otherwise fall through to the legacy
+ // inbound dispatch so synthesis is never silently dropped.
+ const skillIntentWriter = options.procedure?.procedureState?.skillIntentRecords?.write;
+ if (skillIntentWriter && detectServerInboundDeferredSkill(signal)) {
+ await skillIntentWriter(
+ createRecordedSkillIntent(signal, procedureContext, { withSynthesis: true }),
+ );
+
+ return {
+ concluded: { reason: 'skill candidate parked until agent.execution.completed' },
+ status: 'conclude',
+ };
+ }
+
const plan = actionServices.skillActions.prepare(signal);
return {
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/index.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/index.ts
index 100845d5061..aa9ff1d258d 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/index.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/index.ts
@@ -8,6 +8,7 @@ import type {
UserMemoryActionHandlerOptions,
} from './actions';
import { defineSkillManagementActionHandler, defineUserMemoryActionHandler } from './actions';
+import { createCompletionSkillSynthesisSourceHandler } from './completionSkillSynthesis';
import { createFeedbackActionPlannerSignalHandler } from './feedbackAction';
import type { CreateFeedbackDomainJudgePolicyOptions } from './feedbackDomain';
import {
@@ -85,6 +86,13 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOpti
procedureState:
options.skillManagement.procedureState ?? options.procedure?.procedureState,
}),
+ // Deferred skill synthesis (LOBE-10802): synthesize the parked skill
+ // candidate after `agent.execution.completed`, off the full trajectory.
+ createCompletionSkillSynthesisSourceHandler({
+ ...options.skillManagement,
+ procedureState:
+ options.skillManagement.procedureState ?? options.procedure?.procedureState,
+ }),
]
: []),
...(options.userMemory ? [defineUserMemoryActionHandler(options.userMemory)] : []),
diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/skillIntentRecord.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/skillIntentRecord.ts
index 1d73aed88d0..c801f131364 100644
--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/skillIntentRecord.ts
+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/skillIntentRecord.ts
@@ -2,6 +2,9 @@ import { z } from 'zod';
import type { AgentSignalPolicyStateStore } from '../../store/types';
import type {
+ AgentSignalFeedbackDomainConflictPolicy,
+ AgentSignalFeedbackEvidence,
+ AgentSignalFeedbackSourceHints,
AgentSignalSkillActionIntent,
AgentSignalSkillIntentExplicitness,
AgentSignalSkillIntentRoute,
@@ -9,6 +12,34 @@ import type {
const POLICY_ID = 'analyze-intent:skill-intent-records';
+/**
+ * Synthesis payload parked alongside a detect-stage skill candidate so the
+ * deferred completion-stage handler can dispatch the skill-management run from
+ * the original user request without re-running domain classification.
+ *
+ * Trajectory evidence (tool sequence + final product) is assembled fresh at
+ * completion; this carries only the inbound-stage facts the completion handler
+ * cannot otherwise recover.
+ */
+const PendingSkillSynthesisSchema = z.object({
+ agentId: z.string().optional(),
+ conflictPolicy: z
+ .object({
+ // Mirror AgentSignalFeedbackDomainTarget so the parsed record stays
+ // assignable to RecordedSkillIntent.pendingSynthesis (a bare z.string()
+ // widens to string[] and breaks the conflictPolicy type).
+ forbiddenWith: z.array(z.enum(['memory', 'none', 'prompt', 'skill'])).optional(),
+ mode: z.enum(['exclusive', 'fanout']),
+ priority: z.number(),
+ })
+ .optional(),
+ evidence: z.array(z.object({ cue: z.string(), excerpt: z.string() })).optional(),
+ message: z.string(),
+ sourceHints: z.record(z.unknown()).optional(),
+ threadId: z.string().optional(),
+ topicId: z.string().optional(),
+});
+
const RecordedSkillIntentSchema = z.object({
actionIntent: z.enum(['create', 'refine', 'consolidate', 'maintain', 'noop']).optional(),
confidence: z.number().min(0).max(1).optional(),
@@ -20,12 +51,33 @@ const RecordedSkillIntentSchema = z.object({
'non_skill_preference',
]),
feedbackMessageId: z.string(),
+ pendingSynthesis: PendingSkillSynthesisSchema.optional(),
reason: z.string().optional(),
route: z.enum(['direct_decision', 'accumulate', 'non_skill']),
scopeKey: z.string(),
sourceId: z.string(),
});
+/**
+ * Synthesis payload parked alongside a detect-stage skill candidate.
+ */
+export interface PendingSkillSynthesis {
+ /** Reviewed user agent the skill receipt should attribute to. */
+ agentId?: string;
+ /** Inbound-stage conflict policy carried through to the deferred action. */
+ conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
+ /** Inbound-stage evidence, supplemented by trajectory evidence at completion. */
+ evidence?: AgentSignalFeedbackEvidence[];
+ /** Original user request text that the deferred skill synthesis acts on. */
+ message: string;
+ /** Structured source hints attached to the inbound feedback source. */
+ sourceHints?: AgentSignalFeedbackSourceHints;
+ /** Thread the turn ran under, when scoped to a thread. */
+ threadId?: string;
+ /** Topic the turn ran under. */
+ topicId?: string;
+}
+
/**
* Recorded skill intent stored between user-message and completion analysis stages.
*/
@@ -40,6 +92,13 @@ export interface RecordedSkillIntent {
explicitness: AgentSignalSkillIntentExplicitness;
/** User feedback message id that produced this record. */
feedbackMessageId: string;
+ /**
+ * Synthesis payload for the deferred completion-stage skill run. Present when
+ * a server execAgent inbound turn parked a candidate to synthesize after
+ * `agent.execution.completed` (LOBE-10802); absent for the client-runtime
+ * lane, which re-derives the source at `client.runtime.complete`.
+ */
+ pendingSynthesis?: PendingSkillSynthesis;
/** Optional private-safe reason suitable for traces and eval assertions. */
reason?: string;
/** Runtime route selected before completion-stage evidence is available. */
diff --git a/apps/server/src/services/agentSignal/policies/types.ts b/apps/server/src/services/agentSignal/policies/types.ts
index 71a6fef0b7d..0059a60171f 100644
--- a/apps/server/src/services/agentSignal/policies/types.ts
+++ b/apps/server/src/services/agentSignal/policies/types.ts
@@ -317,6 +317,12 @@ export interface AgentSignalPolicyActionPayloadMap {
};
[AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle]: {
agentId?: string;
+ /**
+ * Assistant message that completed the turn. When present (deferred
+ * completion-stage synthesis, LOBE-10802) the skill seed anchors here
+ * instead of under the user message, so it is not a floating mainline root.
+ */
+ assistantMessageId?: string;
conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
evidence?: AgentSignalFeedbackEvidence[];
feedbackHint?: Exclude<AgentSignalFeedbackSatisfactionResult, 'neutral'>;
diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.ts
index 42848475e12..3f9d397f2e2 100644
--- a/packages/agent-signal/src/source/sourceTypes.ts
+++ b/packages/agent-signal/src/source/sourceTypes.ts
@@ -31,7 +31,21 @@ export type AgentSignalSourceType = ValueOf<typeof AGENT_SIGNAL_SOURCE_TYPES>;
export interface AgentSignalSourcePayloadMap {
[AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted]: {
agentId?: string;
+ /**
+ * Message the deferred skill synthesis should anchor to β€” the assistant turn
+ * that completed this run. Lets completion-stage skill synthesis seed under
+ * the assistant group instead of as a floating `parent_id=null` mainline root.
+ */
+ anchorMessageId?: string;
+ /** Assistant message id for the completed turn; used to hydrate the trajectory. */
+ assistantMessageId?: string;
operationId: string;
+ /**
+ * Completion reason as classified by the producer. Non-terminal pauses
+ * (`waiting_for_async_tool` / `waiting_for_human`) reuse this same source, so
+ * completion-stage consumers that need a finished turn must filter on it.
+ */
+ reason?: string;
/**
* Opaque completion side-effect payload attached by the executor for
* builtin background agents (e.g. self-iteration tool outcomes used for
@@ -41,6 +55,8 @@ export interface AgentSignalSourcePayloadMap {
serializedContext?: string;
steps: number;
topicId?: string;
+ /** User message that initiated this turn, when known by the producer. */
+ triggerMessageId?: string;
turnCount?: number;
};
[AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed]: {