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(server): agent signal now is easier to use (#14326)

Neko1324b67590f7
diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.ts
index 8cae2077226..56b88fcc0a6 100644
--- a/src/server/services/agentSignal/orchestrator.ts
+++ b/src/server/services/agentSignal/orchestrator.ts
@@ -120,6 +120,7 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignal
...options.policyOptions?.feedbackSatisfactionJudge,
userId: context.userId,
},
+ classifierDiagnostics: options.policyOptions?.classifierDiagnostics,
procedure: procedurePolicyOptions,
userMemory: {
db: context.db,
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
index 8f144c9d542..f5b5a80e149 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackAction.test.ts
@@ -5,11 +5,13 @@ import { AgentSignalProcedureInspector, createProcedurePolicyOptions } from '../
import { createRuntimeProcessorContext } from '../../../runtime/context';
import type { AgentSignalPolicyStateStore } from '../../../store/types';
import type {
+ ActionUserMemoryHandle,
SignalFeedbackDomainMemory,
SignalFeedbackDomainNone,
SignalFeedbackDomainPrompt,
SignalFeedbackDomainSkill,
} from '../../types';
+import { createAnalyzeIntentPolicy } from '..';
import { createFeedbackActionPlannerSignalHandler } from '../feedbackAction';
const context = createRuntimeProcessorContext({
@@ -163,6 +165,57 @@ function createDomainSignal(
}
describe('feedbackActionPlanner', () => {
+ /**
+ * @example
+ * composed procedure dependencies expose the procedure state service and install in policy order.
+ */
+ it('passes composed procedure state through analyze-intent policy options', async () => {
+ const procedure = createProcedurePolicyOptions({
+ policyStateStore: createStore(),
+ ttlSeconds: 3600,
+ });
+ const installed: string[] = [];
+
+ await createAnalyzeIntentPolicy({
+ feedbackSatisfactionJudge: {
+ judge: {
+ judgeSatisfaction: async () => ({
+ confidence: 0.9,
+ evidence: [{ cue: 'test', excerpt: 'test' }],
+ reason: 'test-satisfaction-judge',
+ result: 'not_satisfied',
+ }),
+ },
+ },
+ procedure,
+ }).install({
+ handleAction: (handler) => {
+ installed.push(`${handler.type}:${handler.id}`);
+ },
+ handleSignal: (handler) => {
+ installed.push(`${handler.type}:${handler.id}`);
+ },
+ handleSource: (handler) => {
+ installed.push(`${handler.type}:${handler.id}`);
+ },
+ });
+
+ expect(procedure.procedureState).toEqual(
+ expect.objectContaining({
+ accumulators: expect.any(Object),
+ markers: expect.any(Object),
+ receipts: expect.any(Object),
+ records: expect.any(Object),
+ }),
+ );
+ expect(installed).toEqual([
+ 'source:source.tool-outcome.procedure',
+ 'source:agent.user.message:feedback-satisfaction-judge',
+ 'signal:signal.feedback-domain-judge',
+ 'signal:signal.feedback-action-planner',
+ ]);
+ });
+
it('creates stable idempotency keys for memory actions', async () => {
const handler = createFeedbackActionPlannerSignalHandler();
const signal = createDomainSignal({
@@ -194,6 +247,69 @@ describe('feedbackActionPlanner', () => {
expect(second).toEqual(first);
});
+ /**
+ * @example
+ * action services own memory action preparation while the handler only dispatches the plan.
+ */
+ it('dispatches memory action plans prepared by injected action services', async () => {
+ const action = {
+ actionId: 'action:custom-memory',
+ actionType: 'action.user-memory.handle' as const,
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'sig_action_service',
+ parentSignalId: 'sig_action_service',
+ rootSourceId: 'source_action_service',
+ },
+ payload: {
+ agentId: undefined,
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout' as const, priority: 100 },
+ evidence: [],
+ feedbackHint: 'not_satisfied' as const,
+ idempotencyKey: 'custom-memory-key',
+ message: 'Remember this preference.',
+ messageId: 'msg_action_service',
+ reason: 'custom action service',
+ sourceHints: {},
+ topicId: undefined,
+ },
+ signal: {
+ signalId: 'sig_action_service',
+ signalType: 'signal.feedback.domain.memory',
+ },
+ source: {
+ sourceId: 'source_action_service',
+ sourceType: 'agent.user.message' as const,
+ },
+ timestamp: 1,
+ } satisfies ActionUserMemoryHandle;
+ const prepare = vi.fn(() => ({
+ action,
+ reason: 'custom memory action plan',
+ risk: 'low' as const,
+ }));
+ const handler = createFeedbackActionPlannerSignalHandler({
+ actionServices: {
+ memoryActions: { prepare },
+ },
+ });
+ const signal = createDomainSignal({
+ message: 'Remember this preference.',
+ messageId: 'msg_action_service',
+ signalId: 'sig_action_service',
+ sourceId: 'source_action_service',
+ target: 'memory',
+ });
+
+ const result = await handler.handle(signal, context);
+
+ expect(prepare).toHaveBeenCalledWith(signal);
+ expect(result).toEqual({
+ actions: [action],
+ status: 'dispatch',
+ });
+ });
+
it('plans skill-management actions for skill domain signals', async () => {
const handler = createFeedbackActionPlannerSignalHandler();
const skillResult = await handler.handle(
@@ -335,6 +451,80 @@ describe('feedbackActionPlanner', () => {
);
});
+ /**
+ * @example
+ * procedureState-only dependencies support weak satisfied skill accumulation.
+ */
+ it('accumulates satisfied skill feedback through procedure state service', async () => {
+ let now = 100;
+ const store = createStore();
+ const procedure = createProcedurePolicyOptions({
+ now: () => now,
+ policyStateStore: store,
+ ttlSeconds: 3600,
+ });
+ const handler = createFeedbackActionPlannerSignalHandler({
+ procedure: {
+ procedureState: procedure.procedureState,
+ },
+ });
+
+ const first = await handler.handle(
+ createDomainSignal({
+ message: 'This successful workflow can be kept as a reference.',
+ messageId: 'msg_skill_state_positive_1',
+ satisfactionResult: 'satisfied',
+ signalId: 'sig_skill_state_positive_1',
+ sourceId: 'source_skill_state_positive_1',
+ target: 'skill',
+ }),
+ context,
+ );
+ now = 130;
+ const second = await handler.handle(
+ createDomainSignal({
+ message: 'The review flow from earlier is worth reusing next time.',
+ messageId: 'msg_skill_state_positive_2',
+ satisfactionResult: 'satisfied',
+ signalId: 'sig_skill_state_positive_2',
+ sourceId: 'source_skill_state_positive_2',
+ target: 'skill',
+ }),
+ context,
+ );
+ const snapshot = await new AgentSignalProcedureInspector(store).inspectScope('topic:thread_1');
+
+ expect(first).toBeUndefined();
+ expect(second).toEqual(
+ expect.objectContaining({
+ signals: [
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ bucketKey: 'topic:thread_1:skill',
+ domain: 'skill',
+ recordIds: [
+ 'procedure-record:sig_skill_state_positive_1:skill-candidate',
+ 'procedure-record:sig_skill_state_positive_2:skill-candidate',
+ ],
+ suggestedActions: ['maintain'],
+ }),
+ signalType: 'signal.procedure.bucket.scored',
+ }),
+ ],
+ status: 'dispatch',
+ }),
+ );
+ expect(snapshot.markers).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ domainKey: 'skill',
+ markerType: 'accumulated',
+ signalId: 'sig_skill_state_positive_2:signal:procedure-accumulated',
+ }),
+ ]),
+ );
+ });
+
/**
* @example
* one context skill record plus one weak candidate stays below accumulated marker threshold.
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts
index 187ccbd5dca..056ced45fc6 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackDomain.test.ts
@@ -175,6 +175,62 @@ describe('feedbackDomainJudge', () => {
expect(result).toBeUndefined();
});
+ it('dispatches a none domain signal when a non-neutral resolver returns none', async () => {
+ const handler = createFeedbackDomainJudgeSignalHandler({
+ resolveDomains: async () => [
+ {
+ confidence: 0.81,
+ evidence: [],
+ reason: 'non-actionable feedback',
+ target: 'none',
+ },
+ ],
+ });
+
+ const result = await handler.handle(
+ {
+ chain: {
+ chainId: 'chain_none',
+ parentNodeId: 'source_none',
+ rootSourceId: 'source_none',
+ },
+ payload: {
+ confidence: 0.89,
+ evidence: [{ cue: 'commentary', excerpt: 'That was interesting.' }],
+ message: 'That was interesting.',
+ messageId: 'msg_none',
+ reason: 'commentary-only',
+ result: 'satisfied',
+ sourceHints: { intents: ['prompt'] },
+ },
+ signalId: 'sig_none',
+ signalType: 'signal.feedback.satisfaction',
+ source: { sourceId: 'source_none', sourceType: 'agent.user.message' },
+ timestamp: 1,
+ },
+ context,
+ );
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ signals: [
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ conflictPolicy: {
+ forbiddenWith: ['memory', 'prompt', 'skill'],
+ mode: 'exclusive',
+ priority: 0,
+ },
+ evidence: [{ cue: 'commentary', excerpt: 'That was interesting.' }],
+ target: 'none',
+ }),
+ signalType: 'signal.feedback.domain.none',
+ }),
+ ],
+ }),
+ );
+ });
+
it('passes structured satisfaction output to the resolver without serialized context', async () => {
let resolverInput:
| Parameters<
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
index 88120b62b96..3421960abb3 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackAction.ts
@@ -1,45 +1,50 @@
-import type { BaseAction, BaseSignal, RuntimeProcessorResult } from '@lobechat/agent-signal';
+import type {
+ RuntimeDispatchProcessorResult,
+ RuntimeProcessorResult,
+} from '@lobechat/agent-signal';
import type {
AgentSignalProcedureMarker,
AgentSignalProcedureRecord,
ProcedureAccumulatorScoreResult,
} from '../../procedure';
-import { createProcedureKey, createProcedureMarker, createProcedureRecord } from '../../procedure';
+import { createProcedureKey, createProcedureMarker } from '../../procedure';
+import type {
+ FeedbackDomainSignal,
+ ProcedureProcessorStateService,
+ SatisfiedSkillFeedbackDomainSignal,
+} from '../../processors/procedure';
+import {
+ accumulateSignal,
+ scoreIncrease,
+ suppressHandled,
+ transitionScoredProcedure,
+ transitionSuppressedProcedure,
+} from '../../processors/procedure';
import type { RuntimeProcessorContext } from '../../runtime/context';
import { defineSignalHandler } from '../../runtime/middleware';
-import {
- AGENT_SIGNAL_POLICY_ACTION_TYPES,
- AGENT_SIGNAL_POLICY_SIGNAL_TYPES,
- type AgentSignalFeedbackDomainTarget,
- type AgentSignalFeedbackSourceHints,
+import type { AgentSignalActionServices } from '../../services/actionServices';
+import { createDefaultActionServices } from '../../services/actionServices';
+import type { ProcedureMarkerSuppressInput, ProcedureStateService } from '../../services/types';
+import type {
+ AgentSignalFeedbackSatisfactionResult,
+ SignalFeedbackDomainMemory,
+ SignalFeedbackDomainSkill,
} from '../types';
+import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES } from '../types';
/**
- * Builds the durable action idempotency key for one planned feedback action.
- *
- * The key intentionally uses the root source id, target domain, and message id so retries of the
- * same feedback source do not replay durable side effects, while memory and skill fan-out actions
- * stay independent from each other.
- *
- * Before:
- * - rootSourceId="msg_1", target="skill", messageId="msg_1"
- *
- * After:
- * - "msg_1:skill:msg_1"
+ * Weak positive skill feedback needs repeated observations before the accumulator emits.
*/
-const createStableIdempotencyKey = (
- signal: BaseSignal,
- target: AgentSignalFeedbackDomainTarget,
- messageId: string,
-) => {
- return `${signal.chain.rootSourceId}:${target}:${messageId}`;
-};
+const SATISFIED_SKILL_CHEAP_SCORE_DELTA = 0.6;
/**
- * Weak positive skill feedback needs repeated observations before the accumulator emits.
+ * Marker reader dependency used by both legacy and procedure-state planner options.
*/
-const SATISFIED_SKILL_CHEAP_SCORE_DELTA = 0.6;
+interface FeedbackActionMarkerReader {
+ /** Checks whether an active handled marker suppresses the current feedback signal. */
+ shouldSuppress: (input: ProcedureMarkerSuppressInput) => Promise<boolean>;
+}
/**
* Procedure dependencies used by the feedback action planner.
@@ -52,10 +57,14 @@ export interface FeedbackActionProcedureDeps {
) => Promise<ProcedureAccumulatorScoreResult | undefined>;
appendRecord: (record: AgentSignalProcedureRecord) => Promise<void>;
};
+ /** Reads handled markers for suppression when a full procedure state service is not supplied. */
+ markerReader?: FeedbackActionMarkerReader;
/** Writes accumulated markers after a bucket score is emitted. */
markerStore?: { write: (marker: AgentSignalProcedureMarker) => Promise<void> };
/** Provides a consistent millisecond timestamp for procedure writes. */
now?: () => number;
+ /** Facade used by the migrated procedure processors. */
+ procedureState?: ProcedureStateService;
/** Writes candidate procedure records. */
recordStore?: { write: (record: AgentSignalProcedureRecord) => Promise<void> };
/** TTL used for marker expiration. */
@@ -66,329 +75,189 @@ export interface FeedbackActionProcedureDeps {
* Options for feedback action planning.
*/
export interface FeedbackActionPlannerOptions {
+ /** Optional action services used to prepare runtime action plans. */
+ actionServices?: AgentSignalActionServices;
/** Optional procedure marker reader used to suppress same-source duplicate actions. */
- markerReader?: {
- shouldSuppress: (input: {
- domainKey: string;
- intentClass?: string;
- intentClassCandidates?: string[];
- procedureKey: string;
- scopeKey: string;
- }) => Promise<boolean>;
- };
- /** Optional procedure dependencies used for weak-signal accumulation. */
+ markerReader?: FeedbackActionMarkerReader;
+ /** Optional procedure dependencies used for suppression and weak-signal accumulation. */
procedure?: FeedbackActionProcedureDeps;
}
-const toDomainKey = (target: AgentSignalFeedbackDomainTarget) => {
- if (target === 'memory') return 'memory:user-preference';
- if (target === 'skill') return 'skill';
- return target;
+const isSatisfiedSkillSignal = (
+ signal: FeedbackDomainSignal,
+): signal is SatisfiedSkillFeedbackDomainSignal => {
+ return signal.payload.target === 'skill' && signal.payload.satisfactionResult === 'satisfied';
};
-const toPlannerIntentClass = (
- result?: 'not_satisfied' | 'neutral' | 'satisfied',
-): 'implicit_positive' | 'unknown' => {
- return result === 'satisfied' ? 'implicit_positive' : 'unknown';
+const isMemorySignal = (signal: FeedbackDomainSignal): signal is SignalFeedbackDomainMemory => {
+ return signal.payload.target === 'memory';
};
-const toPlannerIntentClassCandidates = (
- target: AgentSignalFeedbackDomainTarget,
- result?: 'not_satisfied' | 'neutral' | 'satisfied',
-) => {
- const primary = toPlannerIntentClass(result);
- if (target === 'memory') return [primary, 'explicit_persistence', 'unknown'];
- if (target === 'skill') return [primary, 'tool_command', 'explicit_persistence', 'unknown'];
- return [primary, 'unknown'];
+const isNonSatisfiedSkillSignal = (
+ signal: FeedbackDomainSignal,
+): signal is SignalFeedbackDomainSkill & {
+ payload: SignalFeedbackDomainSkill['payload'] & {
+ satisfactionResult: Exclude<AgentSignalFeedbackSatisfactionResult, 'satisfied'>;
+ target: 'skill';
+ };
+} => {
+ return signal.payload.target === 'skill' && signal.payload.satisfactionResult !== 'satisfied';
};
-const buildActionNodes = (signal: BaseSignal): BaseAction[] => {
- const payload = signal.payload as {
- agentId?: string;
- conflictPolicy?: {
- forbiddenWith?: AgentSignalFeedbackDomainTarget[];
- mode: 'exclusive' | 'fanout';
- priority: number;
- };
- evidence?: Array<{
- cue: string;
- excerpt: string;
- }>;
- message: string;
- messageId: string;
- reason?: string;
- satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';
- sourceHints?: AgentSignalFeedbackSourceHints;
- target: AgentSignalFeedbackDomainTarget;
- topicId?: string;
- };
- const sourcePayload =
- signal.source && 'payload' in signal.source && signal.source.payload
- ? (signal.source.payload as Record<string, unknown>)
- : undefined;
- const serializedContext =
- typeof sourcePayload?.serializedContext === 'string'
- ? sourcePayload.serializedContext
- : undefined;
-
- const idempotencyKey = createStableIdempotencyKey(signal, payload.target, payload.messageId);
-
- if (payload.target === 'memory') {
- return [
- {
- actionId: `${signal.signalId}:action:memory`,
- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
- chain: {
- chainId: signal.chain.chainId,
- parentNodeId: signal.signalId,
- parentSignalId: signal.signalId,
- rootSourceId: signal.chain.rootSourceId,
- },
- payload: {
- agentId: payload.agentId,
- conflictPolicy: payload.conflictPolicy,
- evidence: payload.evidence,
- feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',
- idempotencyKey,
- message: payload.message,
- messageId: payload.messageId,
- reason: payload.reason,
- serializedContext,
- sourceHints: payload.sourceHints,
- topicId: payload.topicId,
- },
- signal: {
- signalId: signal.signalId,
- signalType: signal.signalType,
- },
- source: signal.source,
- timestamp: signal.timestamp,
+const createPlannerProcedureState = (
+ options: FeedbackActionPlannerOptions,
+): ProcedureProcessorStateService | undefined => {
+ const markerReader = options.markerReader ?? options.procedure?.markerReader;
+ const procedureState = options.procedure?.procedureState;
+
+ if (procedureState) {
+ if (!markerReader) return procedureState;
+
+ return {
+ ...procedureState,
+ markers: {
+ ...procedureState.markers,
+ shouldSuppress: markerReader.shouldSuppress,
},
- ];
+ };
}
- if (payload.target === 'skill') {
- if (payload.satisfactionResult === 'satisfied') return [];
-
- return [
- {
- actionId: `${signal.signalId}:action:skill-management`,
- actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
- chain: {
- chainId: signal.chain.chainId,
- parentNodeId: signal.signalId,
- parentSignalId: signal.signalId,
- rootSourceId: signal.chain.rootSourceId,
- },
- payload: {
- agentId: payload.agentId,
- conflictPolicy: payload.conflictPolicy,
- evidence: payload.evidence,
- feedbackHint: 'not_satisfied',
- idempotencyKey,
- message: payload.message,
- messageId: payload.messageId,
- reason: payload.reason,
- serializedContext,
- sourceHints: payload.sourceHints,
- topicId: payload.topicId,
- },
- signal: {
- signalId: signal.signalId,
- signalType: signal.signalType,
- },
- source: signal.source,
- timestamp: signal.timestamp,
- },
- ];
+ if (!markerReader && (!options.procedure?.recordStore || !options.procedure.accumulator)) {
+ return undefined;
}
- return [];
-};
-
-const buildSuppressedProcedureSignal = (signal: BaseSignal, context: RuntimeProcessorContext) => {
- const payload = signal.payload as {
- messageId: string;
- target: AgentSignalFeedbackDomainTarget;
- };
- const domain = toDomainKey(payload.target);
-
return {
- chain: {
- chainId: signal.chain.chainId,
- parentNodeId: signal.signalId,
- parentSignalId: signal.signalId,
- rootSourceId: signal.chain.rootSourceId,
- },
- payload: {
- aggregateScore: 0,
- bucketKey: `${context.scopeKey}:${domain}`,
- confidence: 1,
- domain,
- itemScores: [],
- recordIds: [],
- suggestedActions: ['suppressed'],
- },
- signalId: `${signal.signalId}:signal:procedure-suppressed`,
- signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored,
- source: signal.source,
- timestamp: context.now(),
- } satisfies BaseSignal;
+ accumulators:
+ options.procedure?.accumulator && options.procedure.recordStore
+ ? {
+ appendAndScore: async (record) => {
+ if (options.procedure?.accumulator?.appendAndScore) {
+ return options.procedure.accumulator.appendAndScore(record);
+ }
+
+ await options.procedure?.accumulator?.appendRecord(record);
+ return undefined;
+ },
+ }
+ : undefined,
+ markers: markerReader
+ ? {
+ shouldSuppress: markerReader.shouldSuppress,
+ write: options.procedure?.markerStore?.write,
+ }
+ : undefined,
+ records: options.procedure?.recordStore,
+ };
};
-const buildScoredProcedureSignal = (signal: BaseSignal, scored: ProcedureAccumulatorScoreResult) =>
- ({
- chain: {
- chainId: signal.chain.chainId,
- parentNodeId: signal.signalId,
- parentSignalId: signal.signalId,
- rootSourceId: signal.chain.rootSourceId,
- },
- payload: {
- aggregateScore: scored.score.aggregateScore,
- bucketKey: scored.bucket.bucketKey,
- confidence: scored.score.confidence,
- domain: scored.bucket.domain,
- itemScores: scored.score.itemScores,
- recordIds: scored.bucket.recordIds,
- suggestedActions: scored.score.suggestedActions,
- },
- signalId: `${signal.signalId}:signal:procedure-accumulated`,
- signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored,
- source: signal.source,
- timestamp: scored.score.scoredAt,
- }) satisfies BaseSignal;
-
-const createSatisfiedSkillCandidateRecord = (
- signal: BaseSignal,
+const createProcedureContext = (
context: RuntimeProcessorContext,
- now: number,
-) => {
- const payload = signal.payload as {
- message: string;
- messageId: string;
- reason?: string;
- satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';
- target: AgentSignalFeedbackDomainTarget;
- };
+ options: FeedbackActionPlannerOptions,
+): RuntimeProcessorContext => {
+ if (!options.procedure?.now) return context;
- return createProcedureRecord({
- accumulatorRole: 'candidate',
- cheapScoreDelta: SATISFIED_SKILL_CHEAP_SCORE_DELTA,
- createdAt: now,
- domainKey: 'skill',
- id: `procedure-record:${signal.signalId}:skill-candidate`,
- intentClass: toPlannerIntentClass(payload.satisfactionResult),
- refs: {
- signalIds: [signal.signalId],
- sourceIds: signal.source ? [signal.source.sourceId] : undefined,
- },
- scopeKey: context.scopeKey,
- status: 'observed',
- summary: payload.reason ?? payload.message,
- });
+ return { ...context, now: options.procedure.now };
};
-const maybeAccumulateSatisfiedSkillFeedback = async (
- signal: BaseSignal,
+const writeAccumulatedMarker = async (
+ signal: SatisfiedSkillFeedbackDomainSignal,
context: RuntimeProcessorContext,
options: FeedbackActionPlannerOptions,
+ scoredSignalId: string,
+ recordId: string,
) => {
- const payload = signal.payload as {
- messageId: string;
- satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';
- target: AgentSignalFeedbackDomainTarget;
- };
-
- if (payload.target !== 'skill' || payload.satisfactionResult !== 'satisfied') return undefined;
-
- const procedure = options.procedure;
- if (!procedure?.recordStore || !procedure.accumulator) return undefined;
+ const procedureStateAccumulatedMarkerWriter =
+ options.procedure?.procedureState?.markers.writeAccumulated;
+
+ if (procedureStateAccumulatedMarkerWriter) {
+ await procedureStateAccumulatedMarkerWriter({
+ domainKey: 'skill',
+ intentClass: 'implicit_positive',
+ procedureKey: createProcedureKey({
+ messageId: signal.payload.messageId,
+ rootSourceId: signal.chain.rootSourceId,
+ }),
+ recordId,
+ scopeKey: context.scopeKey,
+ signalId: scoredSignalId,
+ sourceId: signal.source?.sourceId,
+ });
- const now = procedure.now?.() ?? context.now();
- const record = createSatisfiedSkillCandidateRecord(signal, context, now);
+ return;
+ }
- await procedure.recordStore.write(record);
+ const markerWriter = options.procedure?.markerStore?.write;
+ const ttlSeconds = options.procedure?.ttlSeconds;
- if (!procedure.accumulator.appendAndScore) {
- await procedure.accumulator.appendRecord(record);
- return undefined;
- }
+ if (!markerWriter || !ttlSeconds) return;
- const scored = await procedure.accumulator.appendAndScore(record);
- if (!scored) return undefined;
- if (scored.score.aggregateScore < 1 && !scored.score.suggestedActions.includes('maintain')) {
- return undefined;
- }
+ const now = context.now();
- const scoredSignal = buildScoredProcedureSignal(signal, scored);
-
- if (procedure.markerStore && procedure.ttlSeconds) {
- await procedure.markerStore.write(
- createProcedureMarker({
- createdAt: now,
- domainKey: 'skill',
- expiresAt: now + procedure.ttlSeconds * 1000,
- intentClass: toPlannerIntentClass(payload.satisfactionResult),
- markerType: 'accumulated',
- procedureKey: createProcedureKey({
- messageId: payload.messageId,
- rootSourceId: signal.chain.rootSourceId,
- }),
- recordId: record.id,
- scopeKey: context.scopeKey,
- signalId: scoredSignal.signalId,
- sourceId: signal.source?.sourceId,
+ await markerWriter(
+ createProcedureMarker({
+ createdAt: now,
+ domainKey: 'skill',
+ expiresAt: now + ttlSeconds * 1000,
+ intentClass: 'implicit_positive',
+ markerType: 'accumulated',
+ procedureKey: createProcedureKey({
+ messageId: signal.payload.messageId,
+ rootSourceId: signal.chain.rootSourceId,
}),
- );
- }
-
- return scoredSignal;
+ recordId,
+ scopeKey: context.scopeKey,
+ signalId: scoredSignalId,
+ sourceId: signal.source?.sourceId,
+ }),
+ );
};
-/**
- * Builds planned action nodes unless procedure markers suppress the same-source work.
- *
- * Use when:
- * - Feedback domain signals may overlap with direct tool outcomes
- * - Planner suppression must read marker state only
- *
- * Expects:
- * - `messageId` is present on feedback domain signals
- *
- * Returns:
- * - Planned actions and whether they were suppressed
- */
-const buildPlannedActions = async (
- signal: BaseSignal,
+const handleSatisfiedSkillFeedback = async (
+ signal: SatisfiedSkillFeedbackDomainSignal,
context: RuntimeProcessorContext,
options: FeedbackActionPlannerOptions,
-) => {
- const payload = signal.payload as {
- messageId: string;
- satisfactionResult?: 'not_satisfied' | 'neutral' | 'satisfied';
- target: AgentSignalFeedbackDomainTarget;
- };
- const suppressed = await options.markerReader?.shouldSuppress({
- domainKey: toDomainKey(payload.target),
- intentClass: toPlannerIntentClass(payload.satisfactionResult),
- intentClassCandidates: toPlannerIntentClassCandidates(
- payload.target,
- payload.satisfactionResult,
- ),
- procedureKey: `message:${payload.messageId}`,
- scopeKey: context.scopeKey,
+ procedureState: ProcedureProcessorStateService | undefined,
+): Promise<RuntimeProcessorResult | undefined> => {
+ const accumulated = await accumulateSignal(
+ signal,
+ context,
+ { procedureState },
+ {
+ domain: 'skill',
+ scoreDelta: SATISFIED_SKILL_CHEAP_SCORE_DELTA,
+ },
+ );
+
+ // Legacy feedbackAction behavior treats procedure-unavailable and score-gate stops as no work.
+ if (accumulated.type !== 'continue') return;
+ if (!('value' in accumulated)) return;
+
+ const scored = scoreIncrease(accumulated.value.scored, {
+ minRecords: 2,
+ threshold: 1,
});
- if (suppressed) return { actions: [], suppressed: true };
+ if (scored.type !== 'continue') return;
+ if (!('value' in scored)) return;
+
+ const transitioned = transitionScoredProcedure(signal, scored.value);
- const scoredSignal = await maybeAccumulateSatisfiedSkillFeedback(signal, context, options);
+ if (transitioned.type !== 'transition') return;
+ if (transitioned.result.status !== 'dispatch') return;
+
+ const scoredSignal = transitioned.result.signals?.[0];
+ await writeAccumulatedMarker(
+ signal,
+ context,
+ options,
+ scoredSignal?.signalId ?? '',
+ accumulated.value.record.id,
+ );
return {
- actions: buildActionNodes(signal),
- signals: scoredSignal ? [scoredSignal] : [],
- suppressed: false,
- };
+ ...transitioned.result,
+ actions: transitioned.result.actions ?? [],
+ } satisfies RuntimeDispatchProcessorResult;
};
/**
@@ -406,10 +275,16 @@ const buildPlannedActions = async (
* Downstream:
* - `action.user-memory.handle`
* - `action.skill-management.handle`
+ * - `signal.procedure.bucket.scored`
*/
export const createFeedbackActionPlannerSignalHandler = (
options: FeedbackActionPlannerOptions = {},
) => {
+ const defaultActionServices = createDefaultActionServices();
+ const actionServices = {
+ memoryActions: options.actionServices?.memoryActions ?? defaultActionServices.memoryActions,
+ skillActions: options.actionServices?.skillActions ?? defaultActionServices.skillActions,
+ };
const listenedSignalTypes = [
AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory,
AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone,
@@ -421,28 +296,40 @@ export const createFeedbackActionPlannerSignalHandler = (
listenedSignalTypes,
'signal.feedback-action-planner',
async (signal, context): Promise<RuntimeProcessorResult | void> => {
- const {
- actions,
- signals = [],
- suppressed,
- } = await buildPlannedActions(signal, context, options);
+ const procedureContext = createProcedureContext(context, options);
+ const procedureState = createPlannerProcedureState(options);
+ const suppression = await suppressHandled(
+ signal,
+ procedureContext,
+ { procedureState },
+ { onSuppress: () => transitionSuppressedProcedure(signal, procedureContext) },
+ );
+
+ if (suppression.type === 'transition' || suppression.type === 'stop') {
+ return suppression.result;
+ }
+
+ if (isMemorySignal(signal)) {
+ const plan = actionServices.memoryActions.prepare(signal);
- if (suppressed) {
return {
- signals: [buildSuppressedProcedureSignal(signal, context)],
+ actions: [plan.action],
status: 'dispatch',
};
}
- if (actions.length === 0 && signals.length === 0) {
- return;
+ if (isNonSatisfiedSkillSignal(signal)) {
+ const plan = actionServices.skillActions.prepare(signal);
+
+ return {
+ actions: [plan.action],
+ status: 'dispatch',
+ };
}
- return {
- actions,
- signals,
- status: 'dispatch',
- };
+ if (isSatisfiedSkillSignal(signal)) {
+ return handleSatisfiedSkillFeedback(signal, procedureContext, options, procedureState);
+ }
},
);
};
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts
index fb1006783a3..1036eeea690 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomain.ts
@@ -1,14 +1,11 @@
-import { type BaseSignal, type RuntimeProcessorResult } from '@lobechat/agent-signal';
+import type { RuntimeProcessorResult } from '@lobechat/agent-signal';
import type { LobeChatDatabase } from '@/database/type';
+import { classifyDomain, transitionToSignals } from '../../processors';
import { defineSignalHandler } from '../../runtime/middleware';
-import {
- AGENT_SIGNAL_POLICY_SIGNAL_TYPES,
- type AgentSignalFeedbackDomainConflictPolicy,
- type AgentSignalFeedbackEvidence,
- type SignalFeedbackSatisfaction,
-} from '../types';
+import type { ClassifierDiagnosticsService, DomainClassifierService } from '../../services';
+import { AGENT_SIGNAL_POLICY_SIGNAL_TYPES, type SignalFeedbackSatisfaction } from '../types';
import {
type FeedbackDomainJudgeAgentModelConfig,
type FeedbackDomainJudgeAgentResult,
@@ -30,6 +27,8 @@ interface FeedbackDomainJudgeResolverInput {
* Dependencies for the feedback-domain judge signal handler.
*/
export interface CreateFeedbackDomainJudgeSignalHandlerOptions {
+ /** Optional diagnostics sink for malformed structured classifier output. */
+ classifierDiagnostics?: ClassifierDiagnosticsService;
resolveDomains?: (
input: FeedbackDomainJudgeResolverInput,
) => Promise<FeedbackDomainJudgeAgentResult['targets']>;
@@ -45,79 +44,6 @@ export interface CreateFeedbackDomainJudgePolicyOptions {
};
}
-const toConflictPolicy = (
- target: FeedbackDomainJudgeAgentResult['targets'][number]['target'],
-): AgentSignalFeedbackDomainConflictPolicy => {
- switch (target) {
- case 'memory': {
- return { forbiddenWith: ['none'], mode: 'fanout', priority: 100 };
- }
- case 'prompt': {
- return { forbiddenWith: ['memory', 'none', 'skill'], mode: 'exclusive', priority: 90 };
- }
- case 'skill': {
- return { forbiddenWith: ['none'], mode: 'fanout', priority: 80 };
- }
- default: {
- return {
- forbiddenWith: ['memory', 'prompt', 'skill'],
- mode: 'exclusive',
- priority: 0,
- };
- }
- }
-};
-
-const toSignalType = (target: FeedbackDomainJudgeAgentResult['targets'][number]['target']) => {
- switch (target) {
- case 'memory': {
- return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory;
- }
- case 'skill': {
- return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill;
- }
- case 'prompt': {
- return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt;
- }
- default: {
- return AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone;
- }
- }
-};
-
-const buildDomainSignals = (
- signal: SignalFeedbackSatisfaction,
- targets: FeedbackDomainJudgeAgentResult['targets'],
-): BaseSignal[] => {
- return targets.map((target) => ({
- chain: {
- chainId: signal.chain.chainId,
- parentNodeId: signal.signalId,
- rootSourceId: signal.chain.rootSourceId,
- },
- payload: {
- agentId: signal.payload.agentId,
- confidence: target.confidence,
- conflictPolicy: toConflictPolicy(target.target),
- evidence:
- target.evidence.length > 0
- ? (target.evidence as AgentSignalFeedbackEvidence[])
- : signal.payload.evidence,
- message: signal.payload.message,
- messageId: signal.payload.messageId,
- reason: target.reason,
- satisfactionResult: signal.payload.result,
- sourceHints: signal.payload.sourceHints,
- target: target.target,
- topicId: signal.payload.topicId,
- },
- signalId: `${signal.signalId}:domain:${target.target}`,
- signalType: toSignalType(target.target),
- source: signal.source,
- timestamp: Date.now(),
- }));
-};
-
const createDomainResolver = (
options: CreateFeedbackDomainJudgePolicyOptions = {},
): CreateFeedbackDomainJudgeSignalHandlerOptions['resolveDomains'] => {
@@ -169,30 +95,50 @@ export const createFeedbackDomainJudgeSignalHandler = (
return defineSignalHandler(
AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,
'signal.feedback-domain-judge',
- async (signal): Promise<RuntimeProcessorResult | void> => {
- if (!resolveDomains || signal.payload.result === 'neutral') {
+ async (signal, ctx): Promise<RuntimeProcessorResult | void> => {
+ const classifier: DomainClassifierService | undefined = resolveDomains
+ ? {
+ async classify(input) {
+ const targets = await resolveDomains({
+ chain: input.chain,
+ feedback: {
+ confidence: input.payload.confidence,
+ evidence: input.payload.evidence,
+ message: input.payload.message,
+ messageId: input.payload.messageId,
+ reason: input.payload.reason,
+ result: input.payload.result,
+ },
+ source: input.source,
+ sourceHints: input.payload.sourceHints,
+ topicId: input.payload.topicId,
+ });
+
+ return targets;
+ },
+ }
+ : undefined;
+ const result = await classifyDomain(signal, ctx, {
+ diagnostics: options.classifierDiagnostics,
+ domainClassifier: classifier,
+ });
+
+ if (result.type === 'continue') {
+ return transitionToSignals(result.value, {
+ maxSignals: 4,
+ reason: result.reason,
+ }).result;
+ }
+
+ if (result.reason === 'neutral feedback satisfaction') {
return;
}
- const domainTargets = await resolveDomains({
- chain: signal.chain,
- feedback: {
- confidence: signal.payload.confidence,
- evidence: signal.payload.evidence,
- message: signal.payload.message,
- messageId: signal.payload.messageId,
- reason: signal.payload.reason,
- result: signal.payload.result,
- },
- source: signal.source,
- sourceHints: signal.payload.sourceHints,
- topicId: signal.payload.topicId,
- });
+ if (result.reason === 'domain classifier unavailable') {
+ return;
+ }
- return {
- signals: buildDomainSignals(signal, domainTargets),
- status: 'dispatch',
- };
+ return result.result;
},
);
};
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts
index a97f71a6c1b..01608fb1280 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackDomainAgent.ts
@@ -1,5 +1,5 @@
import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
-import type { GenerateObjectSchema } from '@lobechat/model-runtime';
+import type { GenerateObjectPayload, GenerateObjectSchema } from '@lobechat/model-runtime';
import { chainAgentSignalAnalyzeIntentRoute } from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
@@ -75,6 +75,52 @@ const FeedbackDomainGenerateObjectSchema = {
strict: true,
} satisfies GenerateObjectSchema;
+const generateObjectRoles = ['assistant', 'system', 'user'] as const;
+
+const isGenerateObjectRole = (
+ role: string,
+): role is GenerateObjectPayload['messages'][number]['role'] => {
+ return generateObjectRoles.includes(role as (typeof generateObjectRoles)[number]);
+};
+
+/**
+ * Normalizes prompt-chain messages for generateObject.
+ *
+ * Before:
+ * - `{ role: "system", content: "Route feedback" }`
+ * - `{ role: "tool", content: "Unsupported role" }`
+ *
+ * After:
+ * - `{ role: "system", content: "Route feedback" }`
+ * - Throws `TypeError` for roles or content shapes generateObject cannot consume
+ */
+const normalizeGenerateObjectMessages = (
+ messages: NonNullable<ReturnType<typeof chainAgentSignalAnalyzeIntentRoute>['messages']>,
+): GenerateObjectPayload['messages'] => {
+ return messages.map((message) => {
+ if (!isGenerateObjectRole(message.role)) {
+ throw new TypeError(`Unsupported feedback domain message role: ${message.role}`);
+ }
+
+ if (typeof message.content !== 'string') {
+ throw new TypeError('Feedback domain message content must be a string.');
+ }
+
+ if (message.name) {
+ return {
+ content: message.content,
+ name: message.name,
+ role: message.role,
+ };
+ }
+
+ return {
+ content: message.content,
+ role: message.role,
+ };
+ });
+};
+
export interface FeedbackDomainJudgeAgentModelConfig {
model: string;
provider: string;
@@ -144,7 +190,7 @@ export class FeedbackDomainJudgeAgentService {
const result = await modelRuntime.generateObject(
{
- messages: payload.messages as any[],
+ messages: normalizeGenerateObjectMessages(payload.messages ?? []),
model: this.modelConfig.model,
schema: FeedbackDomainGenerateObjectSchema,
},
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
index 7159a3fd9d2..bec7bd063d1 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts
@@ -4,7 +4,7 @@ import {
type SourceAgentUserMessage,
} from '@lobechat/agent-signal/source';
import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
-import type { GenerateObjectSchema } from '@lobechat/model-runtime';
+import type { GenerateObjectPayload, GenerateObjectSchema } from '@lobechat/model-runtime';
import { chainAgentSignalAnalyzeIntentFeedbackSatisfaction } from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
@@ -13,13 +13,10 @@ import { z } from 'zod';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import { classifySatisfaction, transitionToSignals } from '../../processors';
import { defineSourceHandler } from '../../runtime/middleware';
-import {
- AGENT_SIGNAL_POLICY_SIGNAL_TYPES,
- type AgentSignalFeedbackEvidence,
- type AgentSignalFeedbackSatisfactionStagePayload,
- type SignalFeedbackSatisfaction,
-} from '../types';
+import type { ClassifierDiagnosticsService, SatisfactionClassifierService } from '../../services';
+import type { AgentSignalFeedbackSatisfactionStagePayload } from '../types';
const log = debug('lobe-server:agent-signal:feedback-satisfaction:agent');
@@ -66,6 +63,54 @@ const FeedbackSatisfactionGenerateObjectSchema = {
strict: true,
} satisfies GenerateObjectSchema;
+const generateObjectRoles = ['assistant', 'system', 'user'] as const;
+
+const isGenerateObjectRole = (
+ role: string,
+): role is GenerateObjectPayload['messages'][number]['role'] => {
+ return generateObjectRoles.includes(role as (typeof generateObjectRoles)[number]);
+};
+
+/**
+ * Normalizes prompt-chain messages for generateObject.
+ *
+ * Before:
+ * - `{ role: "system", content: "Judge feedback" }`
+ * - `{ role: "tool", content: "Unsupported role" }`
+ *
+ * After:
+ * - `{ role: "system", content: "Judge feedback" }`
+ * - Throws `TypeError` for roles or content shapes generateObject cannot consume
+ */
+const normalizeGenerateObjectMessages = (
+ messages: NonNullable<
+ ReturnType<typeof chainAgentSignalAnalyzeIntentFeedbackSatisfaction>['messages']
+ >,
+): GenerateObjectPayload['messages'] => {
+ return messages.map((message) => {
+ if (!isGenerateObjectRole(message.role)) {
+ throw new TypeError(`Unsupported feedback satisfaction message role: ${message.role}`);
+ }
+
+ if (typeof message.content !== 'string') {
+ throw new TypeError('Feedback satisfaction message content must be a string.');
+ }
+
+ if (message.name) {
+ return {
+ content: message.content,
+ name: message.name,
+ role: message.role,
+ };
+ }
+
+ return {
+ content: message.content,
+ role: message.role,
+ };
+ });
+};
+
/**
* One normalized satisfaction-judge input.
*/
@@ -108,6 +153,8 @@ export interface FeedbackSatisfactionJudgeAgentModelConfig {
* Options for constructing the feedback satisfaction source handler.
*/
export interface CreateFeedbackSatisfactionJudgePolicyOptions {
+ /** Optional diagnostics sink for malformed structured classifier output. */
+ classifierDiagnostics?: ClassifierDiagnosticsService;
db?: LobeChatDatabase;
judge?: FeedbackSatisfactionJudge;
model?: string;
@@ -176,7 +223,7 @@ export class FeedbackSatisfactionJudgeAgentService implements FeedbackSatisfacti
const result = await modelRuntime.generateObject(
{
- messages: payload.messages as any[],
+ messages: normalizeGenerateObjectMessages(payload.messages ?? []),
model: this.modelConfig.model,
schema: FeedbackSatisfactionGenerateObjectSchema,
},
@@ -206,54 +253,6 @@ const resolveJudge = (
});
};
-const normalizeEvidence = (
- evidence: FeedbackSatisfactionStagePayloadResult['evidence'],
-): AgentSignalFeedbackEvidence[] => {
- return evidence.map((item) => ({
- cue: item.cue,
- excerpt: item.excerpt,
- }));
-};
-
-const buildSignal = (
- source: SourceAgentUserMessage,
- payload: FeedbackSatisfactionStagePayloadResult,
- timestamp: number,
-): SignalFeedbackSatisfaction => {
- const normalizedMessage = source.payload.message.trim();
-
- return {
- chain: {
- chainId: source.chain.chainId,
- parentNodeId: source.sourceId,
- rootSourceId: source.chain.rootSourceId,
- },
- payload: {
- agentId: source.payload.agentId,
- confidence: payload.confidence,
- evidence: normalizeEvidence(payload.evidence),
- message: normalizedMessage,
- messageId: source.payload.messageId,
- reason: payload.reason,
- result: payload.result,
- serializedContext: source.payload.serializedContext,
- sourceHints: {
- documentPayload: source.payload.documentPayload,
- intents: source.payload.intents,
- memoryPayload: source.payload.memoryPayload,
- },
- topicId: source.payload.topicId,
- },
- signalId: `${source.sourceId}:signal:feedback-satisfaction`,
- signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,
- source: {
- sourceId: source.sourceId,
- sourceType: source.sourceType,
- },
- timestamp,
- };
-};
-
const explicitSkillChangePattern =
/create|update|refine|merge|consolidate|combine|deduplicate|reorganize|创建|更新|合并|去重|整理/i;
@@ -307,20 +306,24 @@ export const createFeedbackSatisfactionJudgeProcessor = (
AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
`${AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage}:feedback-satisfaction-judge`,
async (source, ctx): Promise<RuntimeProcessorResult | void> => {
- const normalizedMessage = source.payload.message.trim();
- const payload =
- resolveSkillHintSatisfaction(source) ??
- (await judge.judgeSatisfaction({
- message: normalizedMessage,
- serializedContext: source.payload.serializedContext,
- }));
+ const classifier: SatisfactionClassifierService = {
+ async classify(input) {
+ const payload =
+ resolveSkillHintSatisfaction(source) ?? (await judge.judgeSatisfaction(input));
- return {
- signals: [
- buildSignal(source, FeedbackSatisfactionStagePayloadSchema.parse(payload), ctx.now()),
- ],
- status: 'dispatch',
+ return FeedbackSatisfactionStagePayloadSchema.parse(payload);
+ },
};
+ const result = await classifySatisfaction(source, ctx, {
+ diagnostics: options.classifierDiagnostics,
+ satisfactionClassifier: classifier,
+ });
+
+ if (result.type === 'continue') {
+ return transitionToSignals(result.value).result;
+ }
+
+ return result.result;
},
);
};
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/index.ts b/src/server/services/agentSignal/policies/analyzeIntent/index.ts
index ff6858963da..7f73d3fd226 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/index.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/index.ts
@@ -1,6 +1,8 @@
import type { ToolOutcomeProcedureDeps } from '../../procedure/toolOutcome';
import { createToolOutcomeSourceHandler } from '../../procedure/toolOutcome';
import { defineAgentSignalHandlers } from '../../runtime/middleware';
+import type { ClassifierDiagnosticsService } from '../../services/classifierServices';
+import type { ProcedureStateService } from '../../services/types';
import type {
SkillManagementActionHandlerOptions,
UserMemoryActionHandlerOptions,
@@ -15,21 +17,37 @@ import {
import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './feedbackSatisfaction';
import { createFeedbackSatisfactionJudgeProcessor } from './feedbackSatisfaction';
+interface AnalyzeIntentProcedureOptions extends ToolOutcomeProcedureDeps {
+ /** Reads handled procedure markers for feedback-action suppression. */
+ markerReader: {
+ /** Checks whether an active marker suppresses the current procedure candidate. */
+ shouldSuppress: (input: {
+ domainKey: string;
+ intentClass?: string;
+ intentClassCandidates?: string[];
+ procedureKey: string;
+ scopeKey: string;
+ }) => Promise<boolean>;
+ };
+ /** Composed procedure service bundle for migrated procedure processors. */
+ procedureState?: ProcedureStateService;
+}
+
+/**
+ * Options for composing the analyze-intent agent signal policy.
+ */
export interface CreateAnalyzeIntentPolicyOptions {
+ /** Optional diagnostics sink for recoverable classifier structured-output failures. */
+ classifierDiagnostics?: ClassifierDiagnosticsService;
+ /** Optional domain judge dependency used by feedback domain classification. */
feedbackDomainJudge?: CreateFeedbackDomainJudgePolicyOptions['feedbackDomainJudge'];
+ /** Optional satisfaction judge dependencies used by feedback satisfaction classification. */
feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;
- procedure?: ToolOutcomeProcedureDeps & {
- markerReader: {
- shouldSuppress: (input: {
- domainKey: string;
- intentClass?: string;
- intentClassCandidates?: string[];
- procedureKey: string;
- scopeKey: string;
- }) => Promise<boolean>;
- };
- };
+ /** Optional procedure dependencies shared by tool-outcome projection and action planning. */
+ procedure?: AnalyzeIntentProcedureOptions;
+ /** Optional skill-management action handler dependencies. */
skillManagement?: SkillManagementActionHandlerOptions;
+ /** Optional user-memory action handler dependencies. */
userMemory?: UserMemoryActionHandlerOptions;
}
@@ -40,8 +58,13 @@ export const createAnalyzeIntentPolicy = (options: CreateAnalyzeIntentPolicyOpti
return defineAgentSignalHandlers([
...(options.procedure ? [createToolOutcomeSourceHandler(options.procedure)] : []),
- createFeedbackSatisfactionJudgeProcessor(options.feedbackSatisfactionJudge),
+ createFeedbackSatisfactionJudgeProcessor({
+ ...options.feedbackSatisfactionJudge,
+ classifierDiagnostics:
+ options.feedbackSatisfactionJudge?.classifierDiagnostics ?? options.classifierDiagnostics,
+ }),
createFeedbackDomainJudgeSignalHandler({
+ classifierDiagnostics: options.classifierDiagnostics,
resolveDomains: feedbackDomainResolver,
}),
createFeedbackActionPlannerSignalHandler({
diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.ts
index 82360c30eb5..dbc2842c561 100644
--- a/src/server/services/agentSignal/policies/index.ts
+++ b/src/server/services/agentSignal/policies/index.ts
@@ -18,6 +18,7 @@ export * from './analyzeIntent/feedbackSatisfaction';
export * from './types';
export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDomainJudgePolicyOptions {
+ classifierDiagnostics?: CreateAnalyzeIntentPolicyOptions['classifierDiagnostics'];
feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;
procedure?: CreateAnalyzeIntentPolicyOptions['procedure'];
skillManagement?: SkillManagementActionHandlerOptions;
diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.ts
index 997532ca9c1..c3c7c47bd26 100644
--- a/src/server/services/agentSignal/policies/types.ts
+++ b/src/server/services/agentSignal/policies/types.ts
@@ -67,7 +67,7 @@ export interface AgentSignalFeedbackSatisfactionStagePayload {
/** Future-facing slim payload for one domain stage result. */
export interface AgentSignalFeedbackDomainStagePayload<
- TTarget extends AgentSignalFeedbackPhase1DomainTarget,
+ TTarget extends AgentSignalFeedbackDomainTarget,
> {
confidence: number;
evidence: AgentSignalFeedbackEvidence[];
diff --git a/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts b/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts
index 85030d4ad01..9188e71f096 100644
--- a/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts
+++ b/src/server/services/agentSignal/procedure/__tests__/toolOutcome.test.ts
@@ -69,6 +69,103 @@ describe('tool outcome procedure handler', () => {
expect(accumulatorRecords).toHaveLength(1);
});
+ /**
+ * @example
+ * completed explicit memory outcome writes direct procedure state before dispatch.
+ */
+ it('awaits direct outcome procedure writes in golden turn order before returning dispatch', async () => {
+ const writes: string[] = [];
+ const recordWrite = Promise.withResolvers<void>();
+ const receiptWrite = Promise.withResolvers<void>();
+ const markerWrite = Promise.withResolvers<void>();
+ let isSettled = false;
+ const markerStoreWrite = vi.fn(async () => {
+ await markerWrite.promise;
+ writes.push('marker');
+ });
+ const receiptStoreAppend = vi.fn(async () => {
+ await receiptWrite.promise;
+ writes.push('receipt');
+ });
+ const recordStoreWrite = vi.fn(async () => {
+ await recordWrite.promise;
+ writes.push('record');
+ });
+ const handler = createToolOutcomeSourceHandler({
+ accumulator: { appendRecord: async () => {} },
+ markerStore: {
+ write: markerStoreWrite,
+ },
+ now: () => 100,
+ receiptStore: {
+ append: receiptStoreAppend,
+ },
+ recordStore: {
+ write: recordStoreWrite,
+ },
+ ttlSeconds: 3600,
+ });
+ const source = createSource({
+ payload: {
+ domainKey: 'memory:user-preference',
+ intentClass: 'explicit_persistence',
+ messageId: 'm1',
+ outcome: { action: 'create', status: 'succeeded', summary: 'Saved preference.' },
+ tool: { apiName: 'addPreferenceMemory', identifier: 'lobe-user-memory' },
+ },
+ scope: { topicId: 't1', userId: 'u1' },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_ordering',
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,
+ }) as SourceToolOutcomeCompleted;
+
+ // ROOT CAUSE:
+ //
+ // If the source handler returns dispatch before direct procedure writes settle, turn-end
+ // processing can observe the async tool outcome signal while direct outcome state is incomplete.
+ //
+ // We prevent that by awaiting each direct procedure write before returning dispatch:
+ // record -> receipt -> marker -> dispatch.
+ //
+ // NOTE:
+ // Completed handled outcomes also keep receipt before marker so golden-turn consumers see the
+ // compact receipt state before the handled marker is visible.
+ const pending = Promise.resolve(
+ handler.handle(source, { now: () => 100, scopeKey: 'topic:t1' } as never),
+ ).then((result) => {
+ isSettled = true;
+ return result;
+ });
+
+ await vi.waitFor(() => expect(recordStoreWrite).toHaveBeenCalledTimes(1));
+ expect(receiptStoreAppend).not.toHaveBeenCalled();
+ expect(markerStoreWrite).not.toHaveBeenCalled();
+ expect(isSettled).toBe(false);
+
+ recordWrite.resolve();
+ await vi.waitFor(() => expect(receiptStoreAppend).toHaveBeenCalledTimes(1));
+ expect(markerStoreWrite).not.toHaveBeenCalled();
+ expect(isSettled).toBe(false);
+
+ receiptWrite.resolve();
+ await vi.waitFor(() => expect(markerStoreWrite).toHaveBeenCalledTimes(1));
+ expect(isSettled).toBe(false);
+
+ markerWrite.resolve();
+ const result = await pending;
+
+ expect(recordStoreWrite).toHaveBeenCalledTimes(1);
+ expect(receiptStoreAppend).toHaveBeenCalledTimes(1);
+ expect(markerStoreWrite).toHaveBeenCalledTimes(1);
+ expect(writes).toEqual(['record', 'receipt', 'marker']);
+ expect(result).toEqual(
+ expect.objectContaining({
+ signals: [expect.objectContaining({ signalType: 'signal.tool.outcome' })],
+ status: 'dispatch',
+ }),
+ );
+ });
+
/**
* @example
* failed direct tool outcomes never suppress future actions by default.
diff --git a/src/server/services/agentSignal/procedure/index.ts b/src/server/services/agentSignal/procedure/index.ts
index ae198cb9156..af62244f22e 100644
--- a/src/server/services/agentSignal/procedure/index.ts
+++ b/src/server/services/agentSignal/procedure/index.ts
@@ -1,14 +1,8 @@
+import { createProcedureStateService } from '../services/procedureStateService';
import type { AgentSignalPolicyStateStore } from '../store/types';
-import {
- appendAndScoreProcedureAccumulatorRecord,
- appendProcedureAccumulatorRecord,
-} from './accumulator';
-import { createProcedureMarkerKeysForRead } from './keys';
-import { readFirstActiveHandledProcedureMarker, writeProcedureMarker } from './marker';
-import { appendProcedureReceipt } from './receipt';
-import { writeProcedureRecordField } from './record';
import type { AgentSignalProcedureRecord } from './types';
+export { createProcedureStateService } from '../services/procedureStateService';
export * from './accumulator';
export * from './batchScorer';
export * from './emitToolOutcome';
@@ -47,50 +41,34 @@ export interface CreateProcedurePolicyOptionsInput {
*/
export const createProcedurePolicyOptions = (input: CreateProcedurePolicyOptionsInput) => {
const now = input.now ?? (() => Date.now());
- const appendRecord = async (record: AgentSignalProcedureRecord) => {
- await appendProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds);
- };
+ const procedureState = createProcedureStateService({ ...input, now });
return {
accumulator: {
appendAndScore: (record: AgentSignalProcedureRecord) =>
- appendAndScoreProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds, {
- now: now(),
- }),
- appendRecord,
+ procedureState.accumulators.appendAndScore(record),
+ appendRecord: (record: AgentSignalProcedureRecord) =>
+ procedureState.accumulators.append(record),
},
markerReader: {
- shouldSuppress: async (markerInput: {
+ shouldSuppress: (markerInput: {
domainKey: string;
intentClass?: string;
intentClassCandidates?: string[];
procedureKey: string;
scopeKey: string;
- }) => {
- const marker = await readFirstActiveHandledProcedureMarker(
- input.policyStateStore,
- createProcedureMarkerKeysForRead(markerInput),
- now(),
- );
-
- return Boolean(marker);
- },
+ }) => procedureState.markers.shouldSuppress(markerInput),
},
markerStore: {
- write: (marker: Parameters<typeof writeProcedureMarker>[1]) =>
- writeProcedureMarker(input.policyStateStore, marker, input.ttlSeconds),
+ write: procedureState.markers.write,
},
now,
+ procedureState,
receiptStore: {
- append: (receipt: Parameters<typeof appendProcedureReceipt>[1]) =>
- appendProcedureReceipt(input.policyStateStore, receipt, {
- maxItems: 8,
- ttlSeconds: input.ttlSeconds,
- }),
+ append: procedureState.receipts.append,
},
recordStore: {
- write: (record: AgentSignalProcedureRecord) =>
- writeProcedureRecordField(input.policyStateStore, record, input.ttlSeconds),
+ write: (record: AgentSignalProcedureRecord) => procedureState.records.write(record),
},
ttlSeconds: input.ttlSeconds,
};
diff --git a/src/server/services/agentSignal/procedure/toolOutcome.ts b/src/server/services/agentSignal/procedure/toolOutcome.ts
index d5ca4f5c9f7..3261b190a81 100644
--- a/src/server/services/agentSignal/procedure/toolOutcome.ts
+++ b/src/server/services/agentSignal/procedure/toolOutcome.ts
@@ -122,6 +122,21 @@ export const createToolOutcomeSourceHandler = (deps: ToolOutcomeProcedureDeps) =
toolCallId: payload.toolCallId,
});
+ await deps.receiptStore.append({
+ createdAt: now,
+ domainKey: payload.domainKey,
+ id: `procedure-receipt:${record.id}`,
+ intentClass: payload.intentClass,
+ messageId: payload.messageId,
+ recordIds: [record.id],
+ relatedObjects: payload.relatedObjects,
+ scopeKey: context.scopeKey,
+ sourceId: source.sourceId,
+ status: payload.outcome.status === 'failed' ? 'failed' : 'handled',
+ summary: payload.outcome.summary ?? `${payload.domainKey} tool outcome handled.`,
+ updatedAt: now,
+ });
+
if (
shouldWriteHandledMarker({
domainKey: payload.domainKey,
@@ -145,21 +160,6 @@ export const createToolOutcomeSourceHandler = (deps: ToolOutcomeProcedureDeps) =
);
}
- await deps.receiptStore.append({
- createdAt: now,
- domainKey: payload.domainKey,
- id: `procedure-receipt:${record.id}`,
- intentClass: payload.intentClass,
- messageId: payload.messageId,
- recordIds: [record.id],
- relatedObjects: payload.relatedObjects,
- scopeKey: context.scopeKey,
- sourceId: source.sourceId,
- status: payload.outcome.status === 'failed' ? 'failed' : 'handled',
- summary: payload.outcome.summary ?? `${payload.domainKey} tool outcome handled.`,
- updatedAt: now,
- });
-
return { signals: [signal], status: 'dispatch' };
},
);
diff --git a/src/server/services/agentSignal/processors/__tests__/actions.test.ts b/src/server/services/agentSignal/processors/__tests__/actions.test.ts
new file mode 100644
index 00000000000..8ca976b3871
--- /dev/null
+++ b/src/server/services/agentSignal/processors/__tests__/actions.test.ts
@@ -0,0 +1,322 @@
+// @vitest-environment node
+import { describe, expect, expectTypeOf, it } from 'vitest';
+
+import type { SignalFeedbackDomainMemory, SignalFeedbackDomainSkill } from '../../policies/types';
+import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../../policies/types';
+import {
+ type NonSatisfiedSkillFeedbackDomainSignal,
+ planSkillManagement,
+ planUserMemory,
+} from '../actions';
+
+const sourceSerializedContext =
+ '<feedback_analysis_context><message>source context</message></feedback_analysis_context>';
+const payloadSerializedContext =
+ '<feedback_analysis_context><message>payload context</message></feedback_analysis_context>';
+
+const createMemorySignal = (
+ input: Partial<{
+ message: string;
+ messageId: string;
+ payloadSerializedContext: string;
+ reason: string;
+ satisfactionResult: 'neutral' | 'not_satisfied' | 'satisfied';
+ signalId: string;
+ sourceSerializedContext: unknown;
+ sourceId: string;
+ }> = {},
+) => {
+ const base = {
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'source_1',
+ rootSourceId: input.sourceId ?? 'source_1',
+ },
+ source: {
+ payload:
+ 'sourceSerializedContext' in input
+ ? { serializedContext: input.sourceSerializedContext }
+ : { serializedContext: sourceSerializedContext },
+ sourceId: input.sourceId ?? 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1,
+ };
+
+ return {
+ ...base,
+ payload: {
+ agentId: 'agent_1',
+ confidence: 0.9,
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },
+ evidence: [{ cue: 'test', excerpt: input.message ?? 'Remember this.' }],
+ message: input.message ?? 'Remember this.',
+ messageId: input.messageId ?? 'msg_1',
+ reason: input.reason ?? 'test-reason',
+ satisfactionResult: input.satisfactionResult ?? 'satisfied',
+ serializedContext: input.payloadSerializedContext,
+ sourceHints: { intents: ['memory'] },
+ target: 'memory',
+ topicId: 'topic_1',
+ },
+ signalId: input.signalId ?? 'sig_1',
+ signalType: 'signal.feedback.domain.memory',
+ } satisfies SignalFeedbackDomainMemory;
+};
+
+const createSkillSignal = (
+ input: Partial<{
+ message: string;
+ messageId: string;
+ payloadSerializedContext: string;
+ reason: string;
+ satisfactionResult: 'neutral' | 'not_satisfied' | 'satisfied';
+ signalId: string;
+ sourceSerializedContext: unknown;
+ sourceId: string;
+ }> = {},
+) => {
+ const base = {
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'source_1',
+ rootSourceId: input.sourceId ?? 'source_1',
+ },
+ source: {
+ payload:
+ 'sourceSerializedContext' in input
+ ? { serializedContext: input.sourceSerializedContext }
+ : { serializedContext: sourceSerializedContext },
+ sourceId: input.sourceId ?? 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1,
+ };
+
+ return {
+ ...base,
+ payload: {
+ agentId: 'agent_1',
+ confidence: 0.9,
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },
+ evidence: [{ cue: 'test', excerpt: input.message ?? 'Keep this workflow as a skill.' }],
+ message: input.message ?? 'Keep this workflow as a skill.',
+ messageId: input.messageId ?? 'msg_1',
+ reason: input.reason ?? 'test-reason',
+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',
+ serializedContext: input.payloadSerializedContext,
+ sourceHints: { intents: ['skill'] },
+ target: 'skill',
+ topicId: 'topic_1',
+ },
+ signalId: input.signalId ?? 'sig_1',
+ signalType: 'signal.feedback.domain.skill',
+ } satisfies SignalFeedbackDomainSkill;
+};
+
+const createNonSatisfiedSkillSignal = (
+ input: Parameters<typeof createSkillSignal>[0] = {},
+): NonSatisfiedSkillFeedbackDomainSignal => {
+ const signal = createSkillSignal({
+ ...input,
+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',
+ });
+
+ return {
+ ...signal,
+ payload: {
+ ...signal.payload,
+ satisfactionResult:
+ signal.payload.satisfactionResult === 'satisfied'
+ ? 'neutral'
+ : signal.payload.satisfactionResult,
+ target: 'skill',
+ },
+ };
+};
+
+const createSatisfiedSkillSignal = (
+ input: Parameters<typeof createSkillSignal>[0] = {},
+): SignalFeedbackDomainSkill & {
+ payload: SignalFeedbackDomainSkill['payload'] & { satisfactionResult: 'satisfied' };
+} => {
+ const signal = createSkillSignal({ ...input, satisfactionResult: 'satisfied' });
+
+ return {
+ ...signal,
+ payload: {
+ ...signal.payload,
+ satisfactionResult: 'satisfied',
+ target: 'skill',
+ },
+ };
+};
+
+describe('action planning processors', () => {
+ /**
+ * @example
+ * planUserMemory(memorySignal) produces a stable user-memory action plan.
+ */
+ it('plans a user memory action from a memory feedback signal', () => {
+ const signal = createMemorySignal({
+ message: 'Remember that I prefer concise answers.',
+ messageId: 'msg_memory_1',
+ payloadSerializedContext,
+ reason: 'The user stated a persistent preference.',
+ satisfactionResult: 'satisfied',
+ signalId: 'sig_memory_1',
+ sourceId: 'root_source_1',
+ });
+
+ const action = planUserMemory(signal);
+
+ expect(action.actionId).toBe('sig_memory_1:action:memory');
+ expect(action.actionType).toBe(AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle);
+ expect(action.chain).toEqual({
+ chainId: 'chain_1',
+ parentNodeId: 'sig_memory_1',
+ parentSignalId: 'sig_memory_1',
+ rootSourceId: 'root_source_1',
+ });
+ expect(action.payload).toEqual({
+ agentId: 'agent_1',
+ conflictPolicy: signal.payload.conflictPolicy,
+ evidence: signal.payload.evidence,
+ feedbackHint: 'satisfied',
+ idempotencyKey: 'root_source_1:memory:msg_memory_1',
+ message: 'Remember that I prefer concise answers.',
+ messageId: 'msg_memory_1',
+ reason: 'The user stated a persistent preference.',
+ serializedContext: payloadSerializedContext,
+ sourceHints: signal.payload.sourceHints,
+ topicId: 'topic_1',
+ });
+ expect(action.signal).toEqual({
+ signalId: 'sig_memory_1',
+ signalType: 'signal.feedback.domain.memory',
+ });
+ expect(action.source).toBe(signal.source);
+ expect(action.timestamp).toBe(1);
+ });
+
+ /**
+ * @example
+ * planUserMemory(memorySignal) maps neutral memory feedback to `not_satisfied`.
+ */
+ it('maps neutral memory feedback to a not-satisfied action hint', () => {
+ const signal = createMemorySignal({ satisfactionResult: 'neutral' });
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.feedbackHint).toBe('not_satisfied');
+ });
+
+ /**
+ * @example
+ * planUserMemory(memorySignal) preserves explicit `not_satisfied` feedback.
+ */
+ it('maps not-satisfied memory feedback to a not-satisfied action hint', () => {
+ const signal = createMemorySignal({ satisfactionResult: 'not_satisfied' });
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.feedbackHint).toBe('not_satisfied');
+ });
+
+ /**
+ * @example
+ * planUserMemory(memorySignal) falls back to legacy source payload context.
+ */
+ it('falls back to source serialized context when payload context is absent', () => {
+ const signal = createMemorySignal();
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.serializedContext).toBe(sourceSerializedContext);
+ });
+
+ /**
+ * @example
+ * planUserMemory(memorySignal) preserves an empty payload serialized context instead of falling back.
+ */
+ it('preserves an empty payload serialized context', () => {
+ const signal = createMemorySignal({ payloadSerializedContext: '' });
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.serializedContext).toBe('');
+ });
+
+ /**
+ * @example
+ * planUserMemory(memorySignal) ignores non-string legacy source context.
+ */
+ it('omits serialized context when payload context is absent and source context is not a string', () => {
+ const signal = createMemorySignal({ sourceSerializedContext: { ignored: true } });
+
+ const action = planUserMemory(signal);
+
+ expect(action.payload.serializedContext).toBeUndefined();
+ });
+
+ /**
+ * @example
+ * Satisfied skill feedback cannot be passed to planSkillManagement.
+ */
+ it('narrows skill action planning to non-satisfied skill feedback signals', () => {
+ const satisfiedSignal = createSatisfiedSkillSignal();
+
+ expectTypeOf<
+ Parameters<typeof planSkillManagement>[0]
+ >().toMatchTypeOf<NonSatisfiedSkillFeedbackDomainSignal>();
+ expectTypeOf<typeof satisfiedSignal>().not.toMatchTypeOf<
+ Parameters<typeof planSkillManagement>[0]
+ >();
+ expect(satisfiedSignal.payload.satisfactionResult).toBe('satisfied');
+ });
+
+ /**
+ * @example
+ * planSkillManagement(skillSignal) produces a stable skill-management action plan.
+ */
+ it('plans a skill management action from a skill feedback signal', () => {
+ const signal = createNonSatisfiedSkillSignal({
+ message: 'Turn this workflow into a reusable skill.',
+ messageId: 'msg_skill_1',
+ payloadSerializedContext,
+ reason: 'The user requested durable workflow behavior.',
+ signalId: 'sig_skill_1',
+ sourceId: 'root_source_2',
+ });
+
+ const action = planSkillManagement(signal);
+
+ expect(action.actionId).toBe('sig_skill_1:action:skill-management');
+ expect(action.actionType).toBe(AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle);
+ expect(action.chain).toEqual({
+ chainId: 'chain_1',
+ parentNodeId: 'sig_skill_1',
+ parentSignalId: 'sig_skill_1',
+ rootSourceId: 'root_source_2',
+ });
+ expect(action.payload).toEqual({
+ agentId: 'agent_1',
+ conflictPolicy: signal.payload.conflictPolicy,
+ evidence: signal.payload.evidence,
+ feedbackHint: 'not_satisfied',
+ idempotencyKey: 'root_source_2:skill:msg_skill_1',
+ message: 'Turn this workflow into a reusable skill.',
+ messageId: 'msg_skill_1',
+ reason: 'The user requested durable workflow behavior.',
+ serializedContext: payloadSerializedContext,
+ sourceHints: signal.payload.sourceHints,
+ topicId: 'topic_1',
+ });
+ expect(action.signal).toEqual({
+ signalId: 'sig_skill_1',
+ signalType: 'signal.feedback.domain.skill',
+ });
+ expect(action.source).toBe(signal.source);
+ expect(action.timestamp).toBe(1);
+ });
+});
diff --git a/src/server/services/agentSignal/processors/__tests__/classifiers.test.ts b/src/server/services/agentSignal/processors/__tests__/classifiers.test.ts
new file mode 100644
index 00000000000..bb1cc934ad8
--- /dev/null
+++ b/src/server/services/agentSignal/processors/__tests__/classifiers.test.ts
@@ -0,0 +1,381 @@
+// @vitest-environment node
+import type { SourceAgentUserMessage } from '@lobechat/agent-signal/source';
+import { describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
+
+import type { SignalFeedbackSatisfaction } from '../../policies/types';
+import { createRuntimeProcessorContext } from '../../runtime/context';
+import { classifyDomain, classifySatisfaction } from '../classifiers';
+
+const context = createRuntimeProcessorContext({
+ backend: {
+ async getGuardState() {
+ return {};
+ },
+ async touchGuardState() {
+ return {};
+ },
+ },
+ now: () => 1234,
+ scopeKey: 'topic:thread_1',
+});
+
+const createUserMessageSource = (
+ input: Partial<{
+ message: string;
+ sourceId: string;
+ }> = {},
+): SourceAgentUserMessage => ({
+ chain: {
+ chainId: `chain:${input.sourceId ?? 'source_1'}`,
+ rootSourceId: input.sourceId ?? 'source_1',
+ },
+ payload: {
+ agentId: 'agent_1',
+ documentPayload: { section: 'style' },
+ intents: ['document', 'memory'],
+ memoryPayload: { shouldRemember: true },
+ message: input.message ?? ' Please keep replies tighter. ',
+ messageId: `msg:${input.sourceId ?? 'source_1'}`,
+ serializedContext: 'topic=repo-review',
+ topicId: 'topic_1',
+ },
+ scopeKey: 'topic:thread_1',
+ sourceId: input.sourceId ?? 'source_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+});
+
+const createSatisfactionSignal = (
+ input: Partial<SignalFeedbackSatisfaction['payload']> = {},
+): SignalFeedbackSatisfaction => ({
+ chain: {
+ chainId: 'chain:source_1',
+ parentNodeId: 'source_1',
+ rootSourceId: 'source_1',
+ },
+ payload: {
+ agentId: 'agent_1',
+ confidence: 0.9,
+ evidence: [{ cue: 'prefer', excerpt: 'I prefer concise code review.' }],
+ message: 'I prefer concise code review.',
+ messageId: 'msg:source_1',
+ reason: 'durable preference',
+ result: 'not_satisfied',
+ sourceHints: { intents: ['memory', 'skill'] },
+ topicId: 'topic_1',
+ ...input,
+ },
+ signalId: 'source_1:signal:feedback-satisfaction',
+ signalType: 'signal.feedback.satisfaction',
+ source: {
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1,
+});
+
+const createZodError = () => {
+ const result = z.object({ value: z.string() }).safeParse({});
+
+ if (result.success) {
+ throw new Error('Expected test schema parsing to fail.');
+ }
+
+ return result.error;
+};
+
+describe('classifier processors', () => {
+ /**
+ * @example
+ * classifySatisfaction(userMessage, context, service) trims the message and returns one satisfaction signal.
+ */
+ it('turns service output into a feedback satisfaction signal with trimmed message and source hints', async () => {
+ const classify = vi.fn().mockResolvedValue({
+ confidence: 0.94,
+ evidence: [{ cue: 'too long', excerpt: 'Please keep replies tighter.' }],
+ reason: 'explicit style feedback',
+ result: 'not_satisfied',
+ });
+ const source = createUserMessageSource();
+
+ const result = await classifySatisfaction(source, context, {
+ satisfactionClassifier: { classify },
+ });
+
+ expect(classify).toHaveBeenCalledWith({
+ message: 'Please keep replies tighter.',
+ serializedContext: 'topic=repo-review',
+ });
+ expect(result).toEqual({
+ reason: 'classified feedback satisfaction',
+ type: 'continue',
+ value: expect.objectContaining({
+ chain: {
+ chainId: 'chain:source_1',
+ parentNodeId: 'source_1',
+ rootSourceId: 'source_1',
+ },
+ payload: expect.objectContaining({
+ agentId: 'agent_1',
+ message: 'Please keep replies tighter.',
+ messageId: 'msg:source_1',
+ serializedContext: 'topic=repo-review',
+ sourceHints: {
+ documentPayload: { section: 'style' },
+ intents: ['document', 'memory'],
+ memoryPayload: { shouldRemember: true },
+ },
+ topicId: 'topic_1',
+ }),
+ signalId: 'source_1:signal:feedback-satisfaction',
+ signalType: 'signal.feedback.satisfaction',
+ source: {
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1234,
+ }),
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(satisfaction, context, service) fans out memory and skill domain signals.
+ */
+ it('can return multiple domain signals with target-specific signal types', async () => {
+ const classify = vi.fn().mockResolvedValue([
+ {
+ confidence: 0.86,
+ evidence: [],
+ reason: 'future personal preference',
+ target: 'memory',
+ },
+ {
+ confidence: 0.78,
+ evidence: [{ cue: 'template', excerpt: 'reusable template' }],
+ reason: 'reusable workflow idea',
+ target: 'skill',
+ },
+ ]);
+ const signal = createSatisfactionSignal();
+
+ const result = await classifyDomain(signal, context, {
+ domainClassifier: { classify },
+ });
+
+ expect(classify).toHaveBeenCalledWith(signal);
+ expect(result).toEqual({
+ reason: 'classified feedback domains',
+ type: 'continue',
+ value: [
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },
+ evidence: signal.payload.evidence,
+ satisfactionResult: 'not_satisfied',
+ target: 'memory',
+ }),
+ signalId: 'source_1:signal:feedback-satisfaction:domain:memory',
+ signalType: 'signal.feedback.domain.memory',
+ timestamp: 1234,
+ }),
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },
+ evidence: [{ cue: 'template', excerpt: 'reusable template' }],
+ satisfactionResult: 'not_satisfied',
+ target: 'skill',
+ }),
+ signalId: 'source_1:signal:feedback-satisfaction:domain:skill',
+ signalType: 'signal.feedback.domain.skill',
+ timestamp: 1234,
+ }),
+ ],
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(satisfaction, context, service) preserves an explicit none target.
+ */
+ it('can return an explicit none domain signal', async () => {
+ const classify = vi.fn().mockResolvedValue([
+ {
+ confidence: 0.91,
+ evidence: [],
+ reason: 'non-actionable feedback',
+ target: 'none',
+ },
+ ]);
+ const signal = createSatisfactionSignal();
+
+ const result = await classifyDomain(signal, context, {
+ domainClassifier: { classify },
+ });
+
+ expect(result).toEqual({
+ reason: 'classified feedback domains',
+ type: 'continue',
+ value: [
+ expect.objectContaining({
+ payload: expect.objectContaining({
+ conflictPolicy: {
+ forbiddenWith: ['memory', 'prompt', 'skill'],
+ mode: 'exclusive',
+ priority: 0,
+ },
+ evidence: signal.payload.evidence,
+ satisfactionResult: 'not_satisfied',
+ target: 'none',
+ }),
+ signalId: 'source_1:signal:feedback-satisfaction:domain:none',
+ signalType: 'signal.feedback.domain.none',
+ timestamp: 1234,
+ }),
+ ],
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(neutralSignal, context, service) stops before invoking the classifier.
+ */
+ it('stops when the satisfaction result is neutral', async () => {
+ const classify = vi.fn();
+
+ const result = await classifyDomain(createSatisfactionSignal({ result: 'neutral' }), context, {
+ domainClassifier: { classify },
+ });
+
+ expect(classify).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ reason: 'neutral feedback satisfaction',
+ result: { concluded: { reason: 'neutral feedback satisfaction' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(signal, context, emptyService) stops with a reason for empty fanout.
+ */
+ it('stops when no feedback domains are classified', async () => {
+ const classify = vi.fn().mockResolvedValue([]);
+
+ const result = await classifyDomain(createSatisfactionSignal(), context, {
+ domainClassifier: { classify },
+ });
+
+ expect(result).toEqual({
+ reason: 'no feedback domains classified',
+ result: { concluded: { reason: 'no feedback domains classified' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(signal, context, {}) stops with an explicit no-op result.
+ */
+ it('stops with an explicit no-op when a classifier service is missing', async () => {
+ const result = await classifyDomain(createSatisfactionSignal(), context, {});
+
+ expect(result).toEqual({
+ reason: 'domain classifier unavailable',
+ result: { concluded: { reason: 'domain classifier unavailable' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * classifySatisfaction(source, context, malformedService).result.status === "conclude"
+ */
+ it('downgrades malformed satisfaction classifier output to a skipped no-op and records diagnostics', async () => {
+ const error = createZodError();
+ const recordMalformedOutput = vi.fn(async () => {});
+ const source = createUserMessageSource();
+
+ const result = await classifySatisfaction(source, context, {
+ diagnostics: { recordMalformedOutput },
+ satisfactionClassifier: {
+ classify: vi.fn().mockRejectedValue(error),
+ },
+ });
+
+ expect(recordMalformedOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error,
+ reason: 'malformed satisfaction classifier output',
+ scopeKey: 'topic:thread_1',
+ sourceId: 'source_1',
+ stage: 'satisfaction',
+ }),
+ );
+ expect(result).toEqual({
+ reason: 'malformed satisfaction classifier output',
+ result: {
+ concluded: {
+ reason: 'malformed satisfaction classifier output',
+ },
+ status: 'conclude',
+ },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(signal, context, malformedService).result.status === "conclude"
+ */
+ it('downgrades malformed domain classifier output to a skipped no-op and records diagnostics', async () => {
+ const error = createZodError();
+ const recordMalformedOutput = vi.fn(async () => {});
+ const signal = createSatisfactionSignal();
+
+ const result = await classifyDomain(signal, context, {
+ diagnostics: { recordMalformedOutput },
+ domainClassifier: {
+ classify: vi.fn().mockRejectedValue(error),
+ },
+ });
+
+ expect(recordMalformedOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error,
+ reason: 'malformed domain classifier output',
+ scopeKey: 'topic:thread_1',
+ signalId: 'source_1:signal:feedback-satisfaction',
+ sourceId: 'source_1',
+ stage: 'domain',
+ }),
+ );
+ expect(result).toEqual({
+ reason: 'malformed domain classifier output',
+ result: {
+ concluded: {
+ reason: 'malformed domain classifier output',
+ },
+ status: 'conclude',
+ },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * classifyDomain(signal, context, providerOutageService) rejects the provider outage.
+ */
+ it('does not swallow non-malformed classifier service errors', async () => {
+ const error = new Error('provider temporarily unavailable');
+
+ await expect(
+ classifyDomain(createSatisfactionSignal(), context, {
+ domainClassifier: {
+ classify: vi.fn().mockRejectedValue(error),
+ },
+ }),
+ ).rejects.toThrow(error);
+ });
+});
diff --git a/src/server/services/agentSignal/processors/__tests__/procedure.test.ts b/src/server/services/agentSignal/processors/__tests__/procedure.test.ts
new file mode 100644
index 00000000000..07bcb537d9c
--- /dev/null
+++ b/src/server/services/agentSignal/processors/__tests__/procedure.test.ts
@@ -0,0 +1,474 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import type { SignalFeedbackDomainMemory, SignalFeedbackDomainSkill } from '../../policies/types';
+import type { ProcedureAccumulatorScoreResult } from '../../procedure';
+import { createRuntimeProcessorContext } from '../../runtime/context';
+import type { ProcedureStateService } from '../../services/types';
+import {
+ accumulateSignal,
+ type FeedbackDomainSignal,
+ type SatisfiedSkillFeedbackDomainSignal,
+ scoreIncrease,
+ suppressHandled,
+ transitionScoredProcedure,
+ transitionSuppressedProcedure,
+} from '../procedure';
+import { transitionToSignals } from '../runtimeResults';
+
+const context = createRuntimeProcessorContext({
+ backend: {
+ async getGuardState() {
+ return {};
+ },
+ async touchGuardState() {
+ return {};
+ },
+ },
+ now: () => 1000,
+ scopeKey: 'topic:thread_1',
+});
+
+const createMemorySignal = (
+ input: Partial<{
+ message: string;
+ messageId: string;
+ reason: string;
+ satisfactionResult: 'neutral' | 'not_satisfied' | 'satisfied';
+ signalId: string;
+ sourceId: string;
+ }> = {},
+) =>
+ ({
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'source_1',
+ rootSourceId: input.sourceId ?? 'source_1',
+ },
+ payload: {
+ confidence: 0.9,
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 100 },
+ evidence: [{ cue: 'test', excerpt: input.message ?? 'Remember this.' }],
+ message: input.message ?? 'Remember this.',
+ messageId: input.messageId ?? 'msg_1',
+ reason: input.reason ?? 'test-reason',
+ satisfactionResult: input.satisfactionResult ?? 'satisfied',
+ target: 'memory',
+ },
+ signalId: input.signalId ?? 'sig_1',
+ signalType: 'signal.feedback.domain.memory',
+ source: {
+ sourceId: input.sourceId ?? 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1,
+ }) satisfies SignalFeedbackDomainMemory;
+
+const createSkillSignal = (
+ input: Partial<{
+ message: string;
+ messageId: string;
+ reason: string;
+ satisfactionResult: 'neutral' | 'not_satisfied' | 'satisfied';
+ signalId: string;
+ sourceId: string;
+ }> = {},
+) =>
+ ({
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'source_1',
+ rootSourceId: input.sourceId ?? 'source_1',
+ },
+ payload: {
+ confidence: 0.9,
+ conflictPolicy: { forbiddenWith: ['none'], mode: 'fanout', priority: 80 },
+ evidence: [{ cue: 'test', excerpt: input.message ?? 'Keep this workflow as a skill.' }],
+ message: input.message ?? 'Keep this workflow as a skill.',
+ messageId: input.messageId ?? 'msg_1',
+ reason: input.reason ?? 'test-reason',
+ satisfactionResult: input.satisfactionResult ?? 'not_satisfied',
+ target: 'skill',
+ },
+ signalId: input.signalId ?? 'sig_1',
+ signalType: 'signal.feedback.domain.skill',
+ source: {
+ sourceId: input.sourceId ?? 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1,
+ }) satisfies SignalFeedbackDomainSkill;
+
+const createSatisfiedSkillSignal = (
+ input: Parameters<typeof createSkillSignal>[0] = {},
+): SatisfiedSkillFeedbackDomainSignal => {
+ const signal = createSkillSignal({ ...input, satisfactionResult: 'satisfied' });
+
+ return {
+ ...signal,
+ payload: {
+ ...signal.payload,
+ satisfactionResult: 'satisfied',
+ target: 'skill',
+ },
+ };
+};
+
+interface ProcedureStateServiceTestOverrides extends Partial<
+ Omit<ProcedureStateService, 'markers'>
+> {
+ markers?: Partial<ProcedureStateService['markers']>;
+}
+
+const createProcedureStateService = (
+ overrides: ProcedureStateServiceTestOverrides = {},
+): ProcedureStateService => {
+ const service: ProcedureStateService = {
+ accumulators: {
+ append: vi.fn(),
+ appendAndScore: vi.fn(),
+ },
+ inspect: {
+ scope: vi.fn(),
+ },
+ markers: {
+ shouldSuppress: vi.fn(),
+ write: vi.fn(),
+ writeAccumulated: vi.fn(),
+ },
+ receipts: {
+ append: vi.fn(),
+ },
+ records: {
+ write: vi.fn(),
+ },
+ };
+
+ return {
+ ...service,
+ ...overrides,
+ markers: {
+ ...service.markers,
+ ...overrides.markers,
+ },
+ };
+};
+
+const createScored = (
+ overrides: Partial<{
+ aggregateScore: number;
+ recordIds: string[];
+ scoredAt: number;
+ }> = {},
+): ProcedureAccumulatorScoreResult => {
+ const recordIds = overrides.recordIds ?? ['record_1', 'record_2'];
+
+ return {
+ bucket: {
+ bucketKey: 'topic:thread_1:skill',
+ cheapScore: 1.2,
+ domain: 'skill',
+ firstSeenAt: 900,
+ lastSeenAt: 1000,
+ recordCount: recordIds.length,
+ recordIds,
+ scopeKey: 'topic:thread_1',
+ version: '1',
+ },
+ records: [],
+ score: {
+ aggregateScore: overrides.aggregateScore ?? 1.2,
+ confidence: 0.8,
+ itemScores: recordIds.map((recordId) => ({
+ reasons: ['repeated-positive-feedback'],
+ recordId,
+ score: 0.6,
+ suggestedAction: 'handle',
+ })),
+ scoredAt: overrides.scoredAt ?? 1200,
+ suggestedActions: ['handle'],
+ },
+ };
+};
+
+describe('procedure processors', () => {
+ /**
+ * @example
+ * Exact policy signal fixtures compile against the processor input contracts.
+ */
+ it('uses exact policy signal fixtures for processor inputs', () => {
+ const feedbackSignal: FeedbackDomainSignal = createMemorySignal();
+ const skillSignal: SatisfiedSkillFeedbackDomainSignal = createSatisfiedSkillSignal();
+
+ expect(feedbackSignal.signalType).toBe('signal.feedback.domain.memory');
+ expect(skillSignal.payload.satisfactionResult).toBe('satisfied');
+ });
+
+ /**
+ * @example
+ * A satisfied memory signal checks `memory:user-preference` handled markers, then stops with a no-op.
+ */
+ it('stops with noop when an active handled marker exists and no onSuppress is provided', async () => {
+ const shouldSuppress = vi.fn().mockResolvedValue(true);
+ const procedureState = createProcedureStateService({
+ markers: {
+ shouldSuppress,
+ write: vi.fn(),
+ },
+ });
+ const signal = createMemorySignal();
+
+ const result = await suppressHandled(signal, context, { procedureState });
+
+ expect(shouldSuppress).toHaveBeenCalledWith({
+ domainKey: 'memory:user-preference',
+ intentClass: 'implicit_positive',
+ intentClassCandidates: ['implicit_positive', 'explicit_persistence', 'unknown'],
+ procedureKey: 'message:msg_1',
+ scopeKey: 'topic:thread_1',
+ });
+ expect(result).toEqual({
+ reason: 'suppressed by handled procedure marker',
+ result: {
+ concluded: { reason: 'suppressed by handled procedure marker' },
+ status: 'conclude',
+ },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * A caller-provided transition is returned when suppression matches.
+ */
+ it('uses onSuppress transition when provided', async () => {
+ const procedureState = createProcedureStateService({
+ markers: {
+ shouldSuppress: vi.fn().mockResolvedValue(true),
+ write: vi.fn(),
+ },
+ });
+ const signal = createSkillSignal();
+ const onSuppress = vi.fn(() => transitionSuppressedProcedure(signal, context));
+
+ const result = await suppressHandled(signal, context, { procedureState }, { onSuppress });
+
+ expect(onSuppress).toHaveBeenCalledTimes(1);
+ expect(result).toEqual(transitionSuppressedProcedure(signal, context));
+ });
+
+ /**
+ * @example
+ * A signal continues unchanged when no handled marker matches.
+ */
+ it('continues when no handled marker exists', async () => {
+ const procedureState = createProcedureStateService({
+ markers: {
+ shouldSuppress: vi.fn().mockResolvedValue(false),
+ write: vi.fn(),
+ },
+ });
+ const signal = createSkillSignal({ satisfactionResult: 'not_satisfied' });
+
+ await expect(suppressHandled(signal, context, { procedureState })).resolves.toEqual({
+ reason: 'no handled marker matched',
+ type: 'continue',
+ value: signal,
+ });
+ });
+
+ /**
+ * @example
+ * Satisfied skill feedback writes a candidate record and exposes the accumulator result.
+ */
+ it('writes satisfied skill candidates and returns record with scored value', async () => {
+ const appendAndScore = vi.fn().mockResolvedValue(undefined);
+ const write = vi.fn().mockResolvedValue(undefined);
+ const procedureState = createProcedureStateService({
+ accumulators: {
+ append: vi.fn(),
+ appendAndScore,
+ },
+ records: {
+ write,
+ },
+ });
+ const signal = createSatisfiedSkillSignal({
+ message: 'Keep this workflow as a reusable skill.',
+ reason: 'successful workflow',
+ signalId: 'sig_skill',
+ sourceId: 'source_skill',
+ });
+
+ const result = await accumulateSignal(
+ signal,
+ context,
+ { procedureState },
+ { domain: 'skill', scoreDelta: 0.6 },
+ );
+
+ const expectedRecord = {
+ accumulatorRole: 'candidate',
+ cheapScoreDelta: 0.6,
+ createdAt: 1000,
+ domainKey: 'skill',
+ id: 'procedure-record:sig_skill:skill-candidate',
+ intentClass: 'implicit_positive',
+ refs: {
+ signalIds: ['sig_skill'],
+ sourceIds: ['source_skill'],
+ },
+ scopeKey: 'topic:thread_1',
+ status: 'observed',
+ summary: 'successful workflow',
+ };
+
+ expect(write).toHaveBeenCalledWith(expectedRecord);
+ expect(appendAndScore).toHaveBeenCalledWith(expectedRecord);
+ expect(result).toEqual({
+ reason: 'accumulated skill candidate',
+ type: 'continue',
+ value: { record: expectedRecord, scored: undefined },
+ });
+ });
+
+ /**
+ * @example
+ * Missing accumulator score data stops with a no-op gate result.
+ */
+ it('stops score increase when scored value is undefined', () => {
+ expect(scoreIncrease(undefined, { minRecords: 2, threshold: 1 })).toEqual({
+ reason: 'score gates not met',
+ result: { concluded: { reason: 'score gates not met' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * Scores below threshold or record count stop before dispatching.
+ */
+ it('stops score increase below threshold or below minimum record count', () => {
+ expect(
+ scoreIncrease(createScored({ aggregateScore: 0.5 }), { minRecords: 2, threshold: 1 }),
+ ).toEqual({
+ reason: 'score gates not met',
+ result: { concluded: { reason: 'score gates not met' }, status: 'conclude' },
+ type: 'stop',
+ });
+ expect(
+ scoreIncrease(createScored({ recordIds: ['record_1'] }), { minRecords: 2, threshold: 1 }),
+ ).toEqual({
+ reason: 'score gates not met',
+ result: { concluded: { reason: 'score gates not met' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * Scores meeting both gates continue with the scored bucket.
+ */
+ it('continues score increase when gates are met', () => {
+ const scored = createScored();
+
+ expect(scoreIncrease(scored, { minRecords: 2, threshold: 1 })).toEqual({
+ reason: 'score gates met',
+ type: 'continue',
+ value: scored,
+ });
+ });
+
+ /**
+ * @example
+ * Suppressed procedure transitions dispatch a zero-score procedure bucket signal.
+ */
+ it('dispatches suppressed procedure score signal', () => {
+ const signal = createMemorySignal({ signalId: 'sig_memory' });
+
+ expect(transitionSuppressedProcedure(signal, context)).toEqual(
+ transitionToSignals(
+ {
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'sig_memory',
+ parentSignalId: 'sig_memory',
+ rootSourceId: 'source_1',
+ },
+ payload: {
+ aggregateScore: 0,
+ bucketKey: 'topic:thread_1:memory:user-preference',
+ confidence: 1,
+ domain: 'memory:user-preference',
+ itemScores: [],
+ recordIds: [],
+ suggestedActions: ['suppressed'],
+ },
+ signalId: 'sig_memory:signal:procedure-suppressed',
+ signalType: 'signal.procedure.bucket.scored',
+ source: {
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1000,
+ },
+ { reason: 'dispatch suppressed procedure score signal' },
+ ),
+ );
+ });
+
+ /**
+ * @example
+ * Scored procedure transitions dispatch the accumulated score payload.
+ */
+ it('dispatches accumulated procedure score signal', () => {
+ const signal = createSatisfiedSkillSignal({
+ signalId: 'sig_skill',
+ sourceId: 'source_skill',
+ });
+ const scored = createScored({ scoredAt: 1500 });
+
+ expect(transitionScoredProcedure(signal, scored)).toEqual(
+ transitionToSignals(
+ {
+ chain: {
+ chainId: 'chain_1',
+ parentNodeId: 'sig_skill',
+ parentSignalId: 'sig_skill',
+ rootSourceId: 'source_skill',
+ },
+ payload: {
+ aggregateScore: 1.2,
+ bucketKey: 'topic:thread_1:skill',
+ confidence: 0.8,
+ domain: 'skill',
+ itemScores: [
+ {
+ reasons: ['repeated-positive-feedback'],
+ recordId: 'record_1',
+ score: 0.6,
+ suggestedAction: 'handle',
+ },
+ {
+ reasons: ['repeated-positive-feedback'],
+ recordId: 'record_2',
+ score: 0.6,
+ suggestedAction: 'handle',
+ },
+ ],
+ recordIds: ['record_1', 'record_2'],
+ suggestedActions: ['handle'],
+ },
+ signalId: 'sig_skill:signal:procedure-accumulated',
+ signalType: 'signal.procedure.bucket.scored',
+ source: {
+ sourceId: 'source_skill',
+ sourceType: 'agent.user.message',
+ },
+ timestamp: 1500,
+ },
+ { reason: 'dispatch accumulated procedure score signal' },
+ ),
+ );
+ });
+});
diff --git a/src/server/services/agentSignal/processors/__tests__/runtimeResults.test.ts b/src/server/services/agentSignal/processors/__tests__/runtimeResults.test.ts
new file mode 100644
index 00000000000..2bce11ab9a6
--- /dev/null
+++ b/src/server/services/agentSignal/processors/__tests__/runtimeResults.test.ts
@@ -0,0 +1,204 @@
+import type { BaseAction, BaseSignal } from '@lobechat/agent-signal';
+import { describe, expect, it } from 'vitest';
+
+import {
+ continueWith,
+ noopResult,
+ stop,
+ transition,
+ transitionToAction,
+ transitionToSignals,
+} from '../runtimeResults';
+
+const signal = {
+ chain: {
+ rootSourceId: 'source-1',
+ },
+ payload: {
+ domain: 'memory',
+ },
+ signalId: 'signal-1',
+ signalType: 'plan.memory',
+ source: {
+ sourceId: 'source-1',
+ sourceType: 'user.message',
+ },
+ timestamp: 1,
+} satisfies BaseSignal;
+
+const action = {
+ actionId: 'action-1',
+ actionType: 'memory.write',
+ chain: {
+ rootSourceId: 'source-1',
+ },
+ payload: {
+ content: 'remember this',
+ },
+ signal: {
+ signalId: signal.signalId,
+ signalType: signal.signalType,
+ },
+ source: signal.source,
+ timestamp: 2,
+} satisfies BaseAction;
+
+describe('runtimeResults', () => {
+ /**
+ * @example
+ * continueWith('ok', { count: 1 }) returns a continue result with that value.
+ */
+ it('continues with a reason and value', () => {
+ const result = continueWith('ok', { count: 1 });
+
+ expect(result.value).toEqual({ count: 1 });
+ expect(result).toEqual({
+ reason: 'ok',
+ type: 'continue',
+ value: { count: 1 },
+ });
+ });
+
+ /**
+ * @example
+ * continueWith('ok') returns a continue result without a value property.
+ */
+ it('continues without a value when no value is provided', () => {
+ expect(continueWith('ok')).toEqual({
+ reason: 'ok',
+ type: 'continue',
+ });
+ });
+
+ /**
+ * @example
+ * stop('no-op', noopResult('no-op')) returns a stop result with a conclusion payload.
+ */
+ it('stops with a runtime processor result', () => {
+ expect(stop('no-op', noopResult('no-op'))).toEqual({
+ reason: 'no-op',
+ result: { concluded: { reason: 'no-op' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * stop('done') defaults to noopResult('done').
+ */
+ it('stops with a default no-op runtime processor result', () => {
+ expect(stop('done')).toEqual({
+ reason: 'done',
+ result: { concluded: { reason: 'done' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * transition('dispatch later', result) returns a transition result with that runtime result.
+ */
+ it('transitions with a runtime processor result', () => {
+ expect(transition('dispatch later', { signals: [signal], status: 'dispatch' })).toEqual({
+ reason: 'dispatch later',
+ result: { signals: [signal], status: 'dispatch' },
+ type: 'transition',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToSignals([signal], { reason: 'domain fanout' }) dispatches the signal list.
+ */
+ it('transitions to signals for runtime dispatch', () => {
+ expect(transitionToSignals([signal], { reason: 'domain fanout' })).toEqual({
+ reason: 'domain fanout',
+ result: { signals: [signal], status: 'dispatch' },
+ type: 'transition',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToSignals(signal) normalizes one signal to a dispatch list.
+ */
+ it('transitions a single signal to a runtime dispatch list', () => {
+ expect(transitionToSignals(signal)).toEqual({
+ reason: 'dispatch signals',
+ result: { signals: [signal], status: 'dispatch' },
+ type: 'transition',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToSignals([]) stops with the default empty-signal reason.
+ */
+ it('stops empty signal dispatch with the default reason', () => {
+ expect(transitionToSignals([])).toEqual({
+ reason: 'no signals to dispatch',
+ result: { concluded: { reason: 'no signals to dispatch' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToSignals([a, b], { maxSignals: 1 }) stops instead of dispatching fanout.
+ */
+ it('stops signal fanout that exceeds the configured budget', () => {
+ const secondSignal = { ...signal, signalId: 'signal-2' } satisfies BaseSignal;
+
+ expect(
+ transitionToSignals([signal, secondSignal], {
+ maxSignals: 1,
+ reason: 'domain fanout',
+ }),
+ ).toEqual({
+ reason: 'signal fanout budget exceeded',
+ result: {
+ concluded: {
+ reason: 'signal fanout budget exceeded',
+ },
+ status: 'conclude',
+ },
+ type: 'stop',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToAction(action, { reason: 'plan memory' }) dispatches the action list.
+ */
+ it('transitions to actions for runtime dispatch', () => {
+ expect(transitionToAction(action, { reason: 'plan memory' })).toEqual({
+ reason: 'plan memory',
+ result: { actions: [action], status: 'dispatch' },
+ type: 'transition',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToAction(action) defaults to the action dispatch reason.
+ */
+ it('transitions actions with the default dispatch reason', () => {
+ expect(transitionToAction(action)).toEqual({
+ reason: 'dispatch actions',
+ result: { actions: [action], status: 'dispatch' },
+ type: 'transition',
+ });
+ });
+
+ /**
+ * @example
+ * transitionToAction([]) stops with the default empty-action reason.
+ */
+ it('stops empty action dispatch with the default reason', () => {
+ expect(transitionToAction([])).toEqual({
+ reason: 'no actions to dispatch',
+ result: { concluded: { reason: 'no actions to dispatch' }, status: 'conclude' },
+ type: 'stop',
+ });
+ });
+});
diff --git a/src/server/services/agentSignal/processors/actions.ts b/src/server/services/agentSignal/processors/actions.ts
new file mode 100644
index 00000000000..cbce354ff89
--- /dev/null
+++ b/src/server/services/agentSignal/processors/actions.ts
@@ -0,0 +1,138 @@
+import type {
+ ActionSkillManagementHandle,
+ ActionUserMemoryHandle,
+ SignalFeedbackDomainMemory,
+ SignalFeedbackDomainSkill,
+} from '../policies/types';
+import { AGENT_SIGNAL_POLICY_ACTION_TYPES } from '../policies/types';
+
+interface SerializedContextPayload {
+ serializedContext?: unknown;
+}
+
+interface SourcePayloadCarrier {
+ payload?: SerializedContextPayload;
+}
+
+/**
+ * Skill-domain feedback signal that is eligible for direct skill-management action planning.
+ */
+export type NonSatisfiedSkillFeedbackDomainSignal = SignalFeedbackDomainSkill & {
+ payload: SignalFeedbackDomainSkill['payload'] & {
+ satisfactionResult: 'neutral' | 'not_satisfied';
+ target: 'skill';
+ };
+};
+
+const getSerializedContext = (signal: SignalFeedbackDomainMemory | SignalFeedbackDomainSkill) => {
+ if (typeof signal.payload.serializedContext === 'string') {
+ return signal.payload.serializedContext;
+ }
+
+ const source = signal.source as SignalFeedbackDomainMemory['source'] & SourcePayloadCarrier;
+
+ return typeof source.payload?.serializedContext === 'string'
+ ? source.payload.serializedContext
+ : undefined;
+};
+
+/**
+ * Plans a user-memory action from one memory feedback-domain signal.
+ *
+ * Use when:
+ * - Feedback-domain analysis selected the memory target
+ * - The runtime needs a durable user-memory action node
+ *
+ * Expects:
+ * - `signal.payload.target` is `memory`
+ * - `signal.payload.messageId` is stable for idempotency
+ * - Optional serialized context is carried on `signal.payload.serializedContext`
+ *
+ * Returns:
+ * - A typed user-memory action node with stable chain, signal, source, and idempotency metadata
+ */
+export const planUserMemory = (signal: SignalFeedbackDomainMemory): ActionUserMemoryHandle => {
+ const { payload } = signal;
+
+ return {
+ actionId: `${signal.signalId}:action:memory`,
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle,
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ parentSignalId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: payload.agentId,
+ conflictPolicy: payload.conflictPolicy,
+ evidence: payload.evidence,
+ feedbackHint: payload.satisfactionResult === 'satisfied' ? 'satisfied' : 'not_satisfied',
+ idempotencyKey: `${signal.chain.rootSourceId}:memory:${payload.messageId}`,
+ message: payload.message,
+ messageId: payload.messageId,
+ reason: payload.reason,
+ serializedContext: getSerializedContext(signal),
+ sourceHints: payload.sourceHints,
+ topicId: payload.topicId,
+ },
+ signal: {
+ signalId: signal.signalId,
+ signalType: signal.signalType,
+ },
+ source: signal.source,
+ timestamp: signal.timestamp,
+ } satisfies ActionUserMemoryHandle;
+};
+
+/**
+ * Plans a skill-management action from one skill feedback-domain signal.
+ *
+ * Use when:
+ * - Feedback-domain analysis selected the skill target
+ * - The runtime needs a durable skill-management action node
+ *
+ * Expects:
+ * - `signal.payload.target` is `skill`
+ * - `signal.payload.satisfactionResult` is `neutral` or `not_satisfied`
+ * - `signal.payload.messageId` is stable for idempotency
+ * - Optional serialized context is carried on `signal.payload.serializedContext`
+ *
+ * Returns:
+ * - A typed skill-management action node with stable chain, signal, source, and idempotency metadata
+ */
+export const planSkillManagement = (
+ signal: NonSatisfiedSkillFeedbackDomainSignal,
+): ActionSkillManagementHandle => {
+ const { payload } = signal;
+
+ return {
+ actionId: `${signal.signalId}:action:skill-management`,
+ actionType: AGENT_SIGNAL_POLICY_ACTION_TYPES.skillManagementHandle,
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ parentSignalId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: payload.agentId,
+ conflictPolicy: payload.conflictPolicy,
+ evidence: payload.evidence,
+ feedbackHint: 'not_satisfied',
+ idempotencyKey: `${signal.chain.rootSourceId}:skill:${payload.messageId}`,
+ message: payload.message,
+ messageId: payload.messageId,
+ reason: payload.reason,
+ serializedContext: getSerializedContext(signal),
+ sourceHints: payload.sourceHints,
+ topicId: payload.topicId,
+ },
+ signal: {
+ signalId: signal.signalId,
+ signalType: signal.signalType,
+ },
+ source: signal.source,
+ timestamp: signal.timestamp,
+ } satisfies ActionSkillManagementHandle;
+};
diff --git a/src/server/services/agentSignal/processors/classifiers.ts b/src/server/services/agentSignal/processors/classifiers.ts
new file mode 100644
index 00000000000..7f4975f9b0b
--- /dev/null
+++ b/src/server/services/agentSignal/processors/classifiers.ts
@@ -0,0 +1,414 @@
+import {
+ AGENT_SIGNAL_SOURCE_TYPES,
+ type AgentSignalSourceVariants,
+ type SourceAgentUserMessage,
+} from '@lobechat/agent-signal/source';
+
+import {
+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES,
+ type AgentSignalFeedbackDomainConflictPolicy,
+ type AgentSignalFeedbackDomainStagePayload,
+ type AgentSignalFeedbackDomainTarget,
+ type AgentSignalFeedbackEvidence,
+ type SignalFeedbackDomainMemory,
+ type SignalFeedbackDomainNone,
+ type SignalFeedbackDomainPrompt,
+ type SignalFeedbackDomainSkill,
+ type SignalFeedbackSatisfaction,
+} from '../policies/types';
+import type { RuntimeProcessorContext } from '../runtime/context';
+import type {
+ ClassifierDiagnosticsService,
+ DomainClassifierService,
+ SatisfactionClassifierService,
+} from '../services/classifierServices';
+import { continueWith, stop } from './runtimeResults';
+
+/**
+ * Classifier dependencies used by feedback classifier processors.
+ */
+export interface ClassifierProcessorServices {
+ /**
+ * Optional diagnostics sink for recoverable malformed structured classifier output.
+ */
+ diagnostics?: ClassifierDiagnosticsService;
+ /**
+ * Optional domain classifier for routing non-neutral satisfaction signals.
+ */
+ domainClassifier?: DomainClassifierService;
+ /**
+ * Optional satisfaction classifier for classifying `agent.user.message` sources.
+ */
+ satisfactionClassifier?: SatisfactionClassifierService;
+}
+
+/**
+ * Feedback-domain signal variants emitted by classifier processors.
+ */
+export type FeedbackDomainClassifierSignal =
+ | SignalFeedbackDomainMemory
+ | SignalFeedbackDomainNone
+ | SignalFeedbackDomainPrompt
+ | SignalFeedbackDomainSkill;
+
+const isAgentUserMessageSource = (
+ source: AgentSignalSourceVariants,
+): source is SourceAgentUserMessage => {
+ return source.sourceType === AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage;
+};
+
+const isRecordLike = (value: unknown): value is Record<PropertyKey, unknown> => {
+ return typeof value === 'object' && value !== null;
+};
+
+const isMalformedStructuredOutputError = (error: unknown) => {
+ if (!isRecordLike(error)) return false;
+
+ if (error.name === 'ZodError') return true;
+ if ('issues' in error && Array.isArray(error.issues)) return true;
+
+ return (
+ typeof error.message === 'string' &&
+ /structured output|schema|parse|invalid_type|validation/i.test(error.message)
+ );
+};
+
+const recordMalformedOutput = async (
+ diagnostics: ClassifierDiagnosticsService | undefined,
+ input: Parameters<ClassifierDiagnosticsService['recordMalformedOutput']>[0],
+) => {
+ if (!diagnostics) {
+ console.error('[AgentSignal] Malformed classifier output:', {
+ error: input.error,
+ reason: input.reason,
+ scopeKey: input.scopeKey,
+ signalId: input.signalId,
+ sourceId: input.sourceId,
+ stage: input.stage,
+ });
+ return;
+ }
+
+ try {
+ await diagnostics.recordMalformedOutput(input);
+ } catch (error) {
+ console.error('[AgentSignal] Failed to record malformed classifier output:', error);
+ }
+};
+
+const toConflictPolicy = (
+ target: AgentSignalFeedbackDomainTarget,
+): AgentSignalFeedbackDomainConflictPolicy => {
+ switch (target) {
+ case 'memory': {
+ return { forbiddenWith: ['none'], mode: 'fanout', priority: 100 };
+ }
+ case 'none': {
+ return {
+ forbiddenWith: ['memory', 'prompt', 'skill'],
+ mode: 'exclusive',
+ priority: 0,
+ };
+ }
+ case 'prompt': {
+ return { forbiddenWith: ['memory', 'none', 'skill'], mode: 'exclusive', priority: 90 };
+ }
+ case 'skill': {
+ return { forbiddenWith: ['none'], mode: 'fanout', priority: 80 };
+ }
+ }
+};
+
+const normalizeEvidence = (
+ evidence: AgentSignalFeedbackDomainStagePayload<AgentSignalFeedbackDomainTarget>['evidence'],
+): AgentSignalFeedbackEvidence[] => {
+ return evidence.map((item) => ({
+ cue: item.cue,
+ excerpt: item.excerpt,
+ }));
+};
+
+const resolveDomainEvidence = (
+ target: AgentSignalFeedbackDomainStagePayload<AgentSignalFeedbackDomainTarget>,
+ signal: SignalFeedbackSatisfaction,
+) => {
+ return target.evidence.length > 0 ? normalizeEvidence(target.evidence) : signal.payload.evidence;
+};
+
+const buildDomainSignal = (
+ signal: SignalFeedbackSatisfaction,
+ target: AgentSignalFeedbackDomainStagePayload<AgentSignalFeedbackDomainTarget>,
+ timestamp: number,
+): FeedbackDomainClassifierSignal => {
+ switch (target.target) {
+ case 'memory': {
+ return {
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: signal.payload.agentId,
+ confidence: target.confidence,
+ conflictPolicy: toConflictPolicy('memory'),
+ evidence: resolveDomainEvidence(target, signal),
+ message: signal.payload.message,
+ messageId: signal.payload.messageId,
+ reason: target.reason,
+ satisfactionResult: signal.payload.result,
+ sourceHints: signal.payload.sourceHints,
+ target: 'memory',
+ topicId: signal.payload.topicId,
+ },
+ signalId: `${signal.signalId}:domain:memory`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainMemory,
+ source: signal.source,
+ timestamp,
+ } satisfies SignalFeedbackDomainMemory;
+ }
+ case 'none': {
+ return {
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: signal.payload.agentId,
+ confidence: target.confidence,
+ conflictPolicy: toConflictPolicy('none'),
+ evidence: resolveDomainEvidence(target, signal),
+ message: signal.payload.message,
+ messageId: signal.payload.messageId,
+ reason: target.reason,
+ satisfactionResult: signal.payload.result,
+ sourceHints: signal.payload.sourceHints,
+ target: 'none',
+ topicId: signal.payload.topicId,
+ },
+ signalId: `${signal.signalId}:domain:none`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainNone,
+ source: signal.source,
+ timestamp,
+ } satisfies SignalFeedbackDomainNone;
+ }
+ case 'prompt': {
+ return {
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: signal.payload.agentId,
+ confidence: target.confidence,
+ conflictPolicy: toConflictPolicy('prompt'),
+ evidence: resolveDomainEvidence(target, signal),
+ message: signal.payload.message,
+ messageId: signal.payload.messageId,
+ reason: target.reason,
+ satisfactionResult: signal.payload.result,
+ sourceHints: signal.payload.sourceHints,
+ target: 'prompt',
+ topicId: signal.payload.topicId,
+ },
+ signalId: `${signal.signalId}:domain:prompt`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainPrompt,
+ source: signal.source,
+ timestamp,
+ } satisfies SignalFeedbackDomainPrompt;
+ }
+ case 'skill': {
+ return {
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ agentId: signal.payload.agentId,
+ confidence: target.confidence,
+ conflictPolicy: toConflictPolicy('skill'),
+ evidence: resolveDomainEvidence(target, signal),
+ message: signal.payload.message,
+ messageId: signal.payload.messageId,
+ reason: target.reason,
+ satisfactionResult: signal.payload.result,
+ sourceHints: signal.payload.sourceHints,
+ target: 'skill',
+ topicId: signal.payload.topicId,
+ },
+ signalId: `${signal.signalId}:domain:skill`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackDomainSkill,
+ source: signal.source,
+ timestamp,
+ } satisfies SignalFeedbackDomainSkill;
+ }
+ }
+};
+
+/**
+ * Classifies one supported source into a feedback satisfaction signal.
+ *
+ * Use when:
+ * - An `agent.user.message` source should advance through satisfaction classification
+ * - Source handlers need a service-independent signal construction path
+ *
+ * Expects:
+ * - `source` may be any runtime source, but only `agent.user.message` is supported
+ * - `services.satisfactionClassifier` is provided by the caller when classification is enabled
+ *
+ * Returns:
+ * - A continue result with `signal.feedback.satisfaction`, otherwise a no-op stop result
+ *
+ * Triggering workflow:
+ *
+ * `agent.user.message`
+ * -> {@link classifySatisfaction}
+ * -> {@link SatisfactionClassifierService.classify}
+ * -> `signal.feedback.satisfaction`
+ *
+ * Upstream:
+ * - `agent.user.message`
+ *
+ * Downstream:
+ * - {@link SatisfactionClassifierService.classify}
+ */
+export const classifySatisfaction = async (
+ source: AgentSignalSourceVariants,
+ context: RuntimeProcessorContext,
+ services: ClassifierProcessorServices,
+) => {
+ if (!isAgentUserMessageSource(source)) {
+ return stop('unsupported satisfaction classifier source');
+ }
+
+ if (!services.satisfactionClassifier) {
+ return stop('satisfaction classifier unavailable');
+ }
+
+ const message = source.payload.message.trim();
+ let payload: Awaited<ReturnType<SatisfactionClassifierService['classify']>>;
+
+ try {
+ payload = await services.satisfactionClassifier.classify({
+ message,
+ serializedContext: source.payload.serializedContext,
+ });
+ } catch (error) {
+ if (!isMalformedStructuredOutputError(error)) throw error;
+
+ const reason = 'malformed satisfaction classifier output';
+ await recordMalformedOutput(services.diagnostics, {
+ error,
+ reason,
+ scopeKey: context.scopeKey,
+ sourceId: source.sourceId,
+ stage: 'satisfaction',
+ });
+
+ return stop(reason);
+ }
+ const signal: SignalFeedbackSatisfaction = {
+ chain: {
+ chainId: source.chain.chainId,
+ parentNodeId: source.sourceId,
+ rootSourceId: source.chain.rootSourceId,
+ },
+ payload: {
+ agentId: source.payload.agentId,
+ confidence: payload.confidence,
+ evidence: normalizeEvidence(payload.evidence),
+ message,
+ messageId: source.payload.messageId,
+ reason: payload.reason,
+ result: payload.result,
+ serializedContext: source.payload.serializedContext,
+ sourceHints: {
+ documentPayload: source.payload.documentPayload,
+ intents: source.payload.intents,
+ memoryPayload: source.payload.memoryPayload,
+ },
+ topicId: source.payload.topicId,
+ },
+ signalId: `${source.sourceId}:signal:feedback-satisfaction`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.feedbackSatisfaction,
+ source: {
+ sourceId: source.sourceId,
+ sourceType: source.sourceType,
+ },
+ timestamp: context.now(),
+ };
+
+ return continueWith('classified feedback satisfaction', signal);
+};
+
+/**
+ * Classifies one satisfaction signal into domain fan-out signals.
+ *
+ * Use when:
+ * - A non-neutral satisfaction signal should route to memory, prompt, or skill domains
+ * - The caller needs a reusable processor before runtime dispatch conversion
+ *
+ * Expects:
+ * - `signal.payload` contains satisfaction-stage evidence, reason, message, and result
+ * - `services.domainClassifier` returns domain targets, including explicit `none`
+ *
+ * Returns:
+ * - A continue result with domain signals, otherwise a no-op stop result
+ *
+ * Triggering workflow:
+ *
+ * `signal.feedback.satisfaction`
+ * -> {@link classifyDomain}
+ * -> {@link DomainClassifierService.classify}
+ * -> `signal.feedback.domain.*`
+ *
+ * Upstream:
+ * - `signal.feedback.satisfaction`
+ *
+ * Downstream:
+ * - {@link DomainClassifierService.classify}
+ */
+export const classifyDomain = async (
+ signal: SignalFeedbackSatisfaction,
+ context: RuntimeProcessorContext,
+ services: ClassifierProcessorServices,
+) => {
+ if (signal.payload.result === 'neutral') {
+ return stop('neutral feedback satisfaction');
+ }
+
+ if (!services.domainClassifier) {
+ return stop('domain classifier unavailable');
+ }
+
+ let targets: Awaited<ReturnType<DomainClassifierService['classify']>>;
+
+ try {
+ targets = await services.domainClassifier.classify(signal);
+ } catch (error) {
+ if (!isMalformedStructuredOutputError(error)) throw error;
+
+ const reason = 'malformed domain classifier output';
+ await recordMalformedOutput(services.diagnostics, {
+ error,
+ reason,
+ scopeKey: context.scopeKey,
+ signalId: signal.signalId,
+ sourceId: signal.source?.sourceId,
+ stage: 'domain',
+ });
+
+ return stop(reason);
+ }
+ if (targets.length === 0) {
+ return stop('no feedback domains classified');
+ }
+
+ const timestamp = context.now();
+ const signals = targets.map((target) => buildDomainSignal(signal, target, timestamp));
+
+ return continueWith('classified feedback domains', signals);
+};
diff --git a/src/server/services/agentSignal/processors/index.ts b/src/server/services/agentSignal/processors/index.ts
new file mode 100644
index 00000000000..04f642f71a5
--- /dev/null
+++ b/src/server/services/agentSignal/processors/index.ts
@@ -0,0 +1,5 @@
+export * from './actions';
+export * from './classifiers';
+export * from './procedure';
+export * from './runtimeResults';
+export * from './types';
diff --git a/src/server/services/agentSignal/processors/procedure.ts b/src/server/services/agentSignal/processors/procedure.ts
new file mode 100644
index 00000000000..3a3bee56abc
--- /dev/null
+++ b/src/server/services/agentSignal/processors/procedure.ts
@@ -0,0 +1,389 @@
+import {
+ AGENT_SIGNAL_POLICY_SIGNAL_TYPES,
+ type AgentSignalFeedbackDomainTarget,
+ type AgentSignalFeedbackSatisfactionResult,
+ type AgentSignalPolicySignalVariant,
+ type SignalFeedbackDomainMemory,
+ type SignalFeedbackDomainNone,
+ type SignalFeedbackDomainPrompt,
+ type SignalFeedbackDomainSkill,
+} from '../policies/types';
+import type {
+ AgentSignalProcedureMarker,
+ AgentSignalProcedureRecord,
+ ProcedureAccumulatorScoreResult,
+} from '../procedure';
+import { createProcedureRecord } from '../procedure';
+import type { RuntimeProcessorContext } from '../runtime/context';
+import type { ProcedureMarkerSuppressInput } from '../services/types';
+import { continueWith, noopResult, stop, transitionToSignals } from './runtimeResults';
+import type { SignalProcessorResult } from './types';
+
+/**
+ * Minimal procedure state surface consumed by procedure processors.
+ */
+export interface ProcedureProcessorStateService {
+ /** Procedure accumulator operations used by weak-signal accumulation. */
+ accumulators?: {
+ /** Appends one record and returns a score result when the bucket crosses scoring gates. */
+ appendAndScore: (
+ record: AgentSignalProcedureRecord,
+ ) => Promise<ProcedureAccumulatorScoreResult | undefined>;
+ };
+ /** Procedure marker operations used by suppression reads and optional marker writes. */
+ markers?: {
+ /** Checks whether an active handled marker suppresses the current procedure candidate. */
+ shouldSuppress: (input: ProcedureMarkerSuppressInput) => Promise<boolean>;
+ /** Writes one procedure marker when callers need to persist transition state. */
+ write?: (marker: AgentSignalProcedureMarker) => Promise<void>;
+ };
+ /** Scope-local procedure record operations. */
+ records?: {
+ /** Writes one compact procedure record field. */
+ write: (record: AgentSignalProcedureRecord) => Promise<void>;
+ };
+}
+
+/**
+ * Procedure state dependencies used by procedure processors.
+ */
+export interface ProcedureProcessorServices {
+ /** Optional procedure-state facade for marker reads and record writes. */
+ procedureState?: ProcedureProcessorStateService;
+}
+
+/**
+ * Options for suppressing already-handled procedure candidates.
+ */
+export interface SuppressHandledOptions {
+ /** Optional transition returned when a handled procedure marker suppresses this signal. */
+ onSuppress?: () => SignalProcessorResult;
+}
+
+/**
+ * Options for accumulating weak procedure signals.
+ */
+export interface AccumulateSignalOptions {
+ /** Domain that is allowed to accumulate through this processor. */
+ domain: 'skill';
+ /** Cheap deterministic score delta written to the candidate record. */
+ scoreDelta: number;
+}
+
+/**
+ * Options for deciding whether an accumulated score should advance.
+ */
+export interface ScoreIncreaseOptions {
+ /** Minimum number of records required before a score can advance. */
+ minRecords: number;
+ /** Minimum aggregate score required before a score can advance. */
+ threshold: number;
+}
+
+/**
+ * Feedback domain signal variants accepted by procedure processors.
+ */
+export type FeedbackDomainSignal =
+ | SignalFeedbackDomainMemory
+ | SignalFeedbackDomainNone
+ | SignalFeedbackDomainPrompt
+ | SignalFeedbackDomainSkill;
+
+/**
+ * Skill-domain feedback signal after callers have narrowed to satisfied feedback.
+ */
+export type SatisfiedSkillFeedbackDomainSignal = SignalFeedbackDomainSkill & {
+ payload: SignalFeedbackDomainSkill['payload'] & {
+ satisfactionResult: 'satisfied';
+ target: 'skill';
+ };
+};
+
+/**
+ * Synthetic procedure bucket score signal emitted by procedure processors.
+ */
+export type ProcedureBucketScoredSignal = AgentSignalPolicySignalVariant<
+ typeof AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored
+>;
+
+const toDomainKey = (target: AgentSignalFeedbackDomainTarget) => {
+ if (target === 'memory') return 'memory:user-preference';
+ if (target === 'skill') return 'skill';
+ return target;
+};
+
+const toPlannerIntentClass = (
+ result?: AgentSignalFeedbackSatisfactionResult,
+): 'implicit_positive' | 'unknown' => {
+ return result === 'satisfied' ? 'implicit_positive' : 'unknown';
+};
+
+const toPlannerIntentClassCandidates = (
+ target: AgentSignalFeedbackDomainTarget,
+ result?: AgentSignalFeedbackSatisfactionResult,
+) => {
+ const primary = toPlannerIntentClass(result);
+ if (target === 'memory') return [primary, 'explicit_persistence', 'unknown'];
+ if (target === 'skill') return [primary, 'tool_command', 'explicit_persistence', 'unknown'];
+ return [primary, 'unknown'];
+};
+
+/**
+ * Stops procedure work when an active handled marker already covers the signal.
+ *
+ * Use when:
+ * - Feedback-domain signals need to avoid replaying direct tool outcomes
+ * - Procedure marker state is the source of truth for planner suppression
+ *
+ * Expects:
+ * - `signal.payload` contains a feedback domain payload with `messageId` and `target`
+ * - `context.scopeKey` identifies the shared runtime scope
+ *
+ * Returns:
+ * - A stop result when marker state suppresses the signal, otherwise the original signal
+ *
+ * Triggering workflow:
+ *
+ * `signal.feedback.domain.*`
+ * -> {@link suppressHandled}
+ * -> {@link ProcedureStateService.markers.shouldSuppress}
+ *
+ * Upstream:
+ * - `signal.feedback.domain.*`
+ *
+ * Downstream:
+ * - {@link ProcedureStateService.markers.shouldSuppress}
+ */
+export const suppressHandled = async (
+ signal: FeedbackDomainSignal,
+ context: RuntimeProcessorContext,
+ services: ProcedureProcessorServices,
+ options: SuppressHandledOptions = {},
+) => {
+ const { payload } = signal;
+ const suppressed = await services.procedureState?.markers?.shouldSuppress({
+ domainKey: toDomainKey(payload.target),
+ intentClass: toPlannerIntentClass(payload.satisfactionResult),
+ intentClassCandidates: toPlannerIntentClassCandidates(
+ payload.target,
+ payload.satisfactionResult,
+ ),
+ procedureKey: `message:${payload.messageId}`,
+ scopeKey: context.scopeKey,
+ });
+
+ if (suppressed) {
+ return (
+ options.onSuppress?.() ??
+ stop(
+ 'suppressed by handled procedure marker',
+ noopResult('suppressed by handled procedure marker'),
+ )
+ );
+ }
+
+ return continueWith('no handled marker matched', signal);
+};
+
+/**
+ * Writes and scores one satisfied skill procedure candidate.
+ *
+ * Use when:
+ * - Weak positive skill feedback should accumulate before action planning
+ * - A procedure-state service is available for record and accumulator persistence
+ *
+ * Expects:
+ * - `options.domain` is `skill`
+ * - `signal.payload.target` is `skill` and `satisfactionResult` is `satisfied`
+ *
+ * Returns:
+ * - A continue result with the written record and optional score result
+ *
+ * Triggering workflow:
+ *
+ * `signal.feedback.domain.skill`
+ * -> {@link accumulateSignal}
+ * -> {@link ProcedureStateService.records.write}
+ * -> {@link ProcedureStateService.accumulators.appendAndScore}
+ *
+ * Upstream:
+ * - `signal.feedback.domain.skill`
+ *
+ * Downstream:
+ * - {@link ProcedureStateService.records.write}
+ * - {@link ProcedureStateService.accumulators.appendAndScore}
+ */
+export const accumulateSignal = async (
+ signal: SatisfiedSkillFeedbackDomainSignal,
+ context: RuntimeProcessorContext,
+ services: ProcedureProcessorServices,
+ options: AccumulateSignalOptions,
+) => {
+ const { payload } = signal;
+
+ if (!services.procedureState?.records || !services.procedureState.accumulators) {
+ return stop('procedure state unavailable');
+ }
+
+ const record = createProcedureRecord({
+ accumulatorRole: 'candidate',
+ cheapScoreDelta: options.scoreDelta,
+ createdAt: context.now(),
+ domainKey: 'skill',
+ id: `procedure-record:${signal.signalId}:skill-candidate`,
+ intentClass: toPlannerIntentClass(payload.satisfactionResult),
+ refs: {
+ signalIds: [signal.signalId],
+ sourceIds: signal.source ? [signal.source.sourceId] : undefined,
+ },
+ scopeKey: context.scopeKey,
+ status: 'observed',
+ summary: payload.reason ?? payload.message,
+ });
+
+ await services.procedureState.records.write(record);
+ const scored = await services.procedureState.accumulators.appendAndScore(record);
+
+ return continueWith('accumulated skill candidate', { record, scored });
+};
+
+/**
+ * Checks whether an accumulator score crosses local promotion gates.
+ *
+ * Use when:
+ * - A scored procedure bucket should only dispatch after enough evidence
+ * - Deterministic score thresholds protect downstream handlers from weak signals
+ *
+ * Expects:
+ * - `scored` is either undefined or a full procedure accumulator score result
+ * - `options.minRecords` and `options.threshold` are already domain-specific
+ *
+ * Returns:
+ * - A continue result with the score when gates pass, otherwise a no-op stop
+ */
+export const scoreIncrease = (
+ scored: ProcedureAccumulatorScoreResult | undefined,
+ options: ScoreIncreaseOptions,
+) => {
+ if (!scored) return stop('score gates not met');
+ if (scored.bucket.recordIds.length < options.minRecords) return stop('score gates not met');
+ if (scored.score.aggregateScore < options.threshold) return stop('score gates not met');
+
+ return continueWith('score gates met', scored);
+};
+
+/**
+ * Dispatches a synthetic score signal for a suppressed procedure candidate.
+ *
+ * Use when:
+ * - A handled marker suppresses action planning
+ * - Downstream observers still need a procedure score signal for continuity
+ *
+ * Expects:
+ * - `signal.payload.target` contains the suppressed feedback domain
+ * - `signal.chain.rootSourceId` is present for trace continuity
+ *
+ * Returns:
+ * - A transition result that dispatches one suppressed procedure score signal
+ *
+ * Triggering workflow:
+ *
+ * {@link suppressHandled}
+ * -> {@link transitionSuppressedProcedure}
+ * -> `signal.procedure.bucket.scored`
+ *
+ * Upstream:
+ * - {@link suppressHandled}
+ *
+ * Downstream:
+ * - `signal.procedure.bucket.scored`
+ */
+export const transitionSuppressedProcedure = (
+ signal: FeedbackDomainSignal,
+ context: RuntimeProcessorContext,
+) => {
+ const { payload } = signal;
+ const domain = toDomainKey(payload.target);
+ const suppressedSignal: ProcedureBucketScoredSignal = {
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ parentSignalId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ aggregateScore: 0,
+ bucketKey: `${context.scopeKey}:${domain}`,
+ confidence: 1,
+ domain,
+ itemScores: [],
+ recordIds: [],
+ suggestedActions: ['suppressed'],
+ },
+ signalId: `${signal.signalId}:signal:procedure-suppressed`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored,
+ source: signal.source,
+ timestamp: context.now(),
+ };
+
+ return transitionToSignals(suppressedSignal, {
+ reason: 'dispatch suppressed procedure score signal',
+ });
+};
+
+/**
+ * Dispatches a synthetic score signal for an accumulated procedure bucket.
+ *
+ * Use when:
+ * - A scored accumulator bucket passes promotion gates
+ * - Downstream handlers need the compact procedure score payload
+ *
+ * Expects:
+ * - `scored` contains the bucket and batch score returned by procedure state
+ * - `signal.chain.rootSourceId` is present for trace continuity
+ *
+ * Returns:
+ * - A transition result that dispatches one accumulated procedure score signal
+ *
+ * Triggering workflow:
+ *
+ * {@link scoreIncrease}
+ * -> {@link transitionScoredProcedure}
+ * -> `signal.procedure.bucket.scored`
+ *
+ * Upstream:
+ * - {@link scoreIncrease}
+ *
+ * Downstream:
+ * - `signal.procedure.bucket.scored`
+ */
+export const transitionScoredProcedure = (
+ signal: SatisfiedSkillFeedbackDomainSignal,
+ scored: ProcedureAccumulatorScoreResult,
+) => {
+ const scoredSignal: ProcedureBucketScoredSignal = {
+ chain: {
+ chainId: signal.chain.chainId,
+ parentNodeId: signal.signalId,
+ parentSignalId: signal.signalId,
+ rootSourceId: signal.chain.rootSourceId,
+ },
+ payload: {
+ aggregateScore: scored.score.aggregateScore,
+ bucketKey: scored.bucket.bucketKey,
+ confidence: scored.score.confidence,
+ domain: scored.bucket.domain,
+ itemScores: scored.score.itemScores,
+ recordIds: scored.bucket.recordIds,
+ suggestedActions: scored.score.suggestedActions,
+ },
+ signalId: `${signal.signalId}:signal:procedure-accumulated`,
+ signalType: AGENT_SIGNAL_POLICY_SIGNAL_TYPES.procedureBucketScored,
+ source: signal.source,
+ timestamp: scored.score.scoredAt,
+ };
+
+ return transitionToSignals(scoredSignal, {
+ reason: 'dispatch accumulated procedure score signal',
+ });
+};
diff --git a/src/server/services/agentSignal/processors/runtimeResults.ts b/src/server/services/agentSignal/processors/runtimeResults.ts
new file mode 100644
index 00000000000..333b90a8158
--- /dev/null
+++ b/src/server/services/agentSignal/processors/runtimeResults.ts
@@ -0,0 +1,173 @@
+import type { BaseAction, BaseSignal, RuntimeProcessorResult } from '@lobechat/agent-signal';
+
+import type {
+ RuntimeTransitionOptions,
+ SignalProcessorContinueResult,
+ SignalProcessorStopResult,
+ SignalProcessorTransitionResult,
+ SignalProcessorValuedContinueResult,
+ SignalProcessorValuelessContinueResult,
+} from './types';
+
+/**
+ * Creates a no-op conclusion result for runtime processors.
+ *
+ * Use when:
+ * - A processor has nothing else to dispatch
+ * - A stop result needs a consistent conclusion payload
+ *
+ * Expects:
+ * - `reason` describes why the processor concluded
+ *
+ * Returns:
+ * - A runtime conclusion result with the reason stored in `concluded.reason`
+ */
+export function noopResult(reason: string): RuntimeProcessorResult {
+ return { concluded: { reason }, status: 'conclude' };
+}
+
+/**
+ * Creates a processor result that lets local processing continue.
+ *
+ * Use when:
+ * - A processor has produced a value for the next local step
+ * - Runtime dispatch or conclusion is not needed yet
+ *
+ * Expects:
+ * - `reason` describes the continue decision
+ * - `value` is safe for the next processor step to consume
+ *
+ * Returns:
+ * - A continue result carrying the value when one is provided
+ */
+export function continueWith(reason: string): SignalProcessorValuelessContinueResult;
+export function continueWith<TValue>(
+ reason: string,
+ value: TValue,
+): SignalProcessorValuedContinueResult<TValue>;
+export function continueWith<TValue>(
+ reason: string,
+ value?: TValue,
+): SignalProcessorContinueResult<TValue> {
+ if (arguments.length === 1) {
+ return { reason, type: 'continue' };
+ }
+
+ return { reason, type: 'continue', value };
+}
+
+/**
+ * Creates a processor result that stops local processing.
+ *
+ * Use when:
+ * - A processor has reached a terminal local state
+ * - A runtime conclusion, wait, schedule, or dispatch result should be returned immediately
+ *
+ * Expects:
+ * - `reason` describes the stop decision
+ * - `result` is the runtime result the host should consume
+ *
+ * Returns:
+ * - A stop result with a no-op conclusion by default
+ */
+export function stop(
+ reason: string,
+ result: RuntimeProcessorResult = noopResult(reason),
+): SignalProcessorStopResult {
+ return { reason, result, type: 'stop' };
+}
+
+/**
+ * Creates a processor result that transitions through the runtime host.
+ *
+ * Use when:
+ * - A processor needs the runtime host to dispatch, wait, schedule, or conclude
+ * - The caller wants to distinguish transition from terminal stop semantics
+ *
+ * Expects:
+ * - `reason` describes the transition decision
+ * - `result` is the runtime result the host should consume
+ *
+ * Returns:
+ * - A transition result carrying the runtime processor result
+ */
+export function transition(
+ reason: string,
+ result: RuntimeProcessorResult,
+): SignalProcessorTransitionResult {
+ return { reason, result, type: 'transition' };
+}
+
+/**
+ * Creates a transition result that dispatches one or more signals.
+ *
+ * Use when:
+ * - A processor fans out from one signal domain to more signals
+ * - The runtime host should continue by dispatching signal handlers
+ *
+ * Expects:
+ * - `signalOrSignals` is either one signal or a prebuilt signal list
+ * - Empty arrays indicate there is nothing to dispatch
+ *
+ * Returns:
+ * - A dispatch transition when signals exist, otherwise a stop result
+ */
+export function transitionToSignals(
+ signalOrSignals: BaseSignal,
+ options?: RuntimeTransitionOptions,
+): SignalProcessorTransitionResult;
+export function transitionToSignals(
+ signalOrSignals: BaseSignal[],
+ options?: RuntimeTransitionOptions,
+): SignalProcessorStopResult | SignalProcessorTransitionResult;
+export function transitionToSignals(
+ signalOrSignals: BaseSignal | BaseSignal[],
+ options: RuntimeTransitionOptions = {},
+): SignalProcessorStopResult | SignalProcessorTransitionResult {
+ const signals = Array.isArray(signalOrSignals) ? signalOrSignals : [signalOrSignals];
+
+ if (signals.length === 0) {
+ return stop(options.reason ?? 'no signals to dispatch');
+ }
+
+ if (typeof options.maxSignals === 'number' && signals.length > options.maxSignals) {
+ return stop('signal fanout budget exceeded');
+ }
+
+ return transition(options.reason ?? 'dispatch signals', { signals, status: 'dispatch' });
+}
+
+/**
+ * Creates a transition result that dispatches one or more actions.
+ *
+ * Use when:
+ * - A processor converts planned work into executable actions
+ * - The runtime host should continue by dispatching action handlers
+ *
+ * Expects:
+ * - `actionOrActions` is either one action or a prebuilt action list
+ * - Empty arrays indicate there is nothing to dispatch
+ *
+ * Returns:
+ * - A dispatch transition when actions exist, otherwise a stop result
+ */
+export function transitionToAction(
+ actionOrActions: BaseAction,
+ options?: RuntimeTransitionOptions,
+): SignalProcessorTransitionResult;
+export function transitionToAction(
+ actionOrActions: BaseAction[],
+ options?: RuntimeTransitionOptions,
+): SignalProcessorStopResult | SignalProcessorTransitionResult;
+export function transitionToAction(
+ actionOrActions: BaseAction | BaseAction[],
+ options: RuntimeTransitionOptions = {},
+): SignalProcessorStopResult | SignalProcessorTransitionResult {
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
+
+ if (actions.length === 0) {
+ return stop(options.reason ?? 'no actions to dispatch');
+ }
+
+ return transition(options.reason ?? 'dispatch actions', { actions, status: 'dispatch' });
+}
diff --git a/src/server/services/agentSignal/processors/types.ts b/src/server/services/agentSignal/processors/types.ts
new file mode 100644
index 00000000000..ac0e57a9886
--- /dev/null
+++ b/src/server/services/agentSignal/processors/types.ts
@@ -0,0 +1,120 @@
+import type { RuntimeProcessorResult } from '@lobechat/agent-signal';
+
+/**
+ * Represents a continue decision without a local value.
+ */
+export interface SignalProcessorValuelessContinueResult {
+ /**
+ * Stable reason used for tracing, metrics, and tests.
+ */
+ reason: string;
+ /**
+ * Discriminates local continue decisions from runtime stop or transition decisions.
+ */
+ type: 'continue';
+}
+
+/**
+ * Represents a continue decision with a local value.
+ *
+ * @param TValue - Value shape produced for the next local processor step.
+ */
+export interface SignalProcessorValuedContinueResult<TValue> {
+ /**
+ * Stable reason used for tracing, metrics, and tests.
+ */
+ reason: string;
+ /**
+ * Discriminates local continue decisions from runtime stop or transition decisions.
+ */
+ type: 'continue';
+ /**
+ * Value produced for the next local processor step.
+ */
+ value: TValue;
+}
+
+/**
+ * Represents any continue decision before the runtime host consumes it.
+ *
+ * @param TValue - Optional value shape produced for the next local processor step.
+ */
+export type SignalProcessorContinueResult<TValue = unknown> =
+ | SignalProcessorValuedContinueResult<TValue>
+ | SignalProcessorValuelessContinueResult;
+
+/**
+ * Represents a processor decision that stops local processing.
+ */
+export interface SignalProcessorStopResult {
+ /**
+ * Stable reason used for tracing, metrics, and tests.
+ */
+ reason: string;
+ /**
+ * Runtime result the host should consume.
+ */
+ result: RuntimeProcessorResult;
+ /**
+ * Discriminates terminal stop decisions from continue and transition decisions.
+ */
+ type: 'stop';
+}
+
+/**
+ * Represents a processor decision that transitions through the runtime host.
+ */
+export interface SignalProcessorTransitionResult {
+ /**
+ * Stable reason used for tracing, metrics, and tests.
+ */
+ reason: string;
+ /**
+ * Runtime result the host should consume.
+ */
+ result: RuntimeProcessorResult;
+ /**
+ * Discriminates runtime transition decisions from continue and stop decisions.
+ */
+ type: 'transition';
+}
+
+/**
+ * Represents a processor decision before the runtime host consumes it.
+ *
+ * Use when:
+ * - A signal processor needs to keep local processing going with a typed value
+ * - A signal processor needs to stop or transition through a runtime result
+ *
+ * Expects:
+ * - `reason` is stable enough for logs, metrics, and tests
+ * - `result` is provided whenever the runtime host must perform a terminal or dispatch action
+ *
+ * Returns:
+ * - A discriminated union keyed by `type`
+ */
+export type SignalProcessorResult<TValue = unknown> =
+ | SignalProcessorContinueResult<TValue>
+ | SignalProcessorStopResult
+ | SignalProcessorTransitionResult;
+
+/**
+ * Options shared by helpers that create runtime transition results.
+ */
+export interface RuntimeTransitionOptions {
+ /**
+ * Maximum number of signals a transition may dispatch.
+ *
+ * @default undefined, meaning no local helper limit. Callers that perform domain fanout should
+ * set this explicitly from their per-source or per-chain budget.
+ */
+ maxSignals?: number;
+ /**
+ * Optional reason used for tracing the transition decision.
+ *
+ * @default Helper-specific reason. Signal dispatch defaults to `dispatch signals` or
+ * `no signals to dispatch`; action dispatch defaults to `dispatch actions` or
+ * `no actions to dispatch`.
+ */
+ reason?: string;
+}
diff --git a/src/server/services/agentSignal/services/__tests__/procedureStateService.test.ts b/src/server/services/agentSignal/services/__tests__/procedureStateService.test.ts
new file mode 100644
index 00000000000..fc967117498
--- /dev/null
+++ b/src/server/services/agentSignal/services/__tests__/procedureStateService.test.ts
@@ -0,0 +1,157 @@
+import { createProcedureMarker } from '../../procedure';
+import type { AgentSignalPolicyStateStore } from '../../store/types';
+import { createProcedureStateService } from '../procedureStateService';
+
+const createStore = (): AgentSignalPolicyStateStore => {
+ const state = new Map<string, Record<string, string>>();
+
+ return {
+ readPolicyState: async (policyId, scopeKey) => state.get(`${policyId}:${scopeKey}`),
+ writePolicyState: async (policyId, scopeKey, data) => {
+ const key = `${policyId}:${scopeKey}`;
+ state.set(key, { ...state.get(key), ...data });
+ },
+ };
+};
+
+describe('ProcedureStateService', () => {
+ /**
+ * @example
+ * service markers suppress after writing an active handled marker.
+ */
+ it('writes procedure state and suppresses an active handled marker', async () => {
+ const service = createProcedureStateService({
+ now: () => 150,
+ policyStateStore: createStore(),
+ ttlSeconds: 60,
+ });
+ const record = {
+ accumulatorRole: 'context' as const,
+ createdAt: 100,
+ domainKey: 'memory:user-preference',
+ id: 'procedure-record:memory-1',
+ intentClass: 'explicit_persistence',
+ refs: { sourceIds: ['source_1'] },
+ scopeKey: 'topic:t1',
+ status: 'handled' as const,
+ summary: 'Saved preference.',
+ };
+ const marker = createProcedureMarker({
+ createdAt: 110,
+ domainKey: record.domainKey,
+ expiresAt: 300,
+ intentClass: record.intentClass,
+ markerType: 'handled',
+ procedureKey: 'message:m1',
+ recordId: record.id,
+ scopeKey: record.scopeKey,
+ });
+ const receipt = {
+ createdAt: 120,
+ domainKey: record.domainKey,
+ id: 'procedure-receipt:memory-1',
+ intentClass: record.intentClass,
+ recordIds: [record.id],
+ scopeKey: record.scopeKey,
+ status: 'handled' as const,
+ summary: 'Saved preference.',
+ updatedAt: 120,
+ };
+
+ await service.records.write(record);
+ await service.accumulators.append(record);
+ await service.receipts.append(receipt);
+ await service.markers.write(marker);
+
+ await expect(
+ service.markers.shouldSuppress({
+ domainKey: record.domainKey,
+ intentClass: record.intentClass,
+ procedureKey: 'message:m1',
+ scopeKey: record.scopeKey,
+ }),
+ ).resolves.toBe(true);
+ await expect(service.inspect.scope(record.scopeKey)).resolves.toEqual(
+ expect.objectContaining({
+ markers: [marker],
+ receipts: [receipt],
+ records: [record],
+ }),
+ );
+ });
+
+ /**
+ * @example
+ * service.markers.writeAccumulated(input) writes an accumulated marker with facade-owned expiry.
+ */
+ it('writes accumulated markers without exposing marker expiry to callers', async () => {
+ const store = createStore();
+ const service = createProcedureStateService({
+ now: () => 100,
+ policyStateStore: store,
+ ttlSeconds: 60,
+ });
+
+ await service.markers.writeAccumulated({
+ domainKey: 'skill',
+ intentClass: 'implicit_positive',
+ procedureKey: 'message:msg_1',
+ recordId: 'procedure-record:skill-1',
+ scopeKey: 'topic:t1',
+ signalId: 'signal:score-1',
+ sourceId: 'source_1',
+ });
+
+ const snapshot = await service.inspect.scope('topic:t1');
+
+ expect(snapshot.markers).toEqual([
+ expect.objectContaining({
+ domainKey: 'skill',
+ expiresAt: 60_100,
+ markerType: 'accumulated',
+ signalId: 'signal:score-1',
+ }),
+ ]);
+ });
+
+ /**
+ * @example
+ * second weak skill candidate crosses the scoring gate and emits maintain.
+ */
+ it('appends and scores repeated weak skill candidate records', async () => {
+ const service = createProcedureStateService({
+ now: () => 200,
+ policyStateStore: createStore(),
+ ttlSeconds: 60,
+ });
+ const firstRecord = {
+ accumulatorRole: 'candidate' as const,
+ cheapScoreDelta: 0.6,
+ createdAt: 100,
+ domainKey: 'skill:managed-skill',
+ id: 'procedure-record:skill-1',
+ refs: {},
+ scopeKey: 'topic:t1',
+ status: 'observed' as const,
+ };
+ const secondRecord = {
+ ...firstRecord,
+ createdAt: 110,
+ id: 'procedure-record:skill-2',
+ };
+
+ await expect(service.accumulators.appendAndScore(firstRecord)).resolves.toBeUndefined();
+ await expect(service.accumulators.appendAndScore(secondRecord)).resolves.toEqual(
+ expect.objectContaining({
+ bucket: expect.objectContaining({
+ bucketKey: 'topic:t1:skill',
+ recordIds: ['procedure-record:skill-1', 'procedure-record:skill-2'],
+ }),
+ score: expect.objectContaining({
+ aggregateScore: 1.2,
+ suggestedActions: ['maintain'],
+ }),
+ }),
+ );
+ });
+});
diff --git a/src/server/services/agentSignal/services/actionServices.ts b/src/server/services/agentSignal/services/actionServices.ts
new file mode 100644
index 00000000000..d5c88f67cf2
--- /dev/null
+++ b/src/server/services/agentSignal/services/actionServices.ts
@@ -0,0 +1,96 @@
+import type {
+ ActionSkillManagementHandle,
+ ActionUserMemoryHandle,
+ AgentSignalPolicyAction,
+ SignalFeedbackDomainMemory,
+ SignalFeedbackDomainSkill,
+} from '../policies/types';
+import { planSkillManagement, planUserMemory } from '../processors/actions';
+
+/**
+ * Skill-domain feedback signal that is eligible for direct skill-management action services.
+ */
+export type NonSatisfiedSkillActionServiceSignal = SignalFeedbackDomainSkill & {
+ payload: SignalFeedbackDomainSkill['payload'] & {
+ /** Direct skill-management planning handles unresolved or neutral skill feedback only. */
+ satisfactionResult: 'neutral' | 'not_satisfied';
+ /** Skill-domain discriminator preserved from the policy signal. */
+ target: 'skill';
+ };
+};
+
+/**
+ * Describes one prepared agent-signal action and its execution risk.
+ *
+ * @param TAction - Exact policy action variant produced by the service.
+ */
+export interface AgentSignalActionPlan<TAction extends AgentSignalPolicyAction> {
+ /** Exact action node prepared for runtime dispatch. */
+ action: TAction;
+ /** Human-readable explanation for why the action was planned. */
+ reason: string;
+ /** Estimated side-effect risk for orchestration, review, or gating. */
+ risk: 'high' | 'low' | 'medium';
+}
+
+/**
+ * Prepares user-memory actions from memory feedback-domain signals.
+ */
+export interface MemoryActionService {
+ /**
+ * Converts one memory feedback-domain signal into a dispatchable memory action plan.
+ */
+ prepare: (signal: SignalFeedbackDomainMemory) => AgentSignalActionPlan<ActionUserMemoryHandle>;
+}
+
+/**
+ * Prepares skill-management actions from skill feedback-domain signals.
+ */
+export interface SkillActionService {
+ /**
+ * Converts one skill feedback-domain signal into a dispatchable skill-management action plan.
+ */
+ prepare: (
+ signal: NonSatisfiedSkillActionServiceSignal,
+ ) => AgentSignalActionPlan<ActionSkillManagementHandle>;
+}
+
+/**
+ * Groups action services used by feedback action handlers.
+ */
+export interface AgentSignalActionServices {
+ /** Service that prepares user-memory action plans. */
+ memoryActions?: MemoryActionService;
+ /** Service that prepares skill-management action plans. */
+ skillActions?: SkillActionService;
+}
+
+/**
+ * Creates the default action data-plane services for Agent Signal feedback actions.
+ *
+ * Use when:
+ * - Handlers need stable memory and skill action planning without owning payload construction
+ * - Tests need injectable action services while preserving production defaults
+ *
+ * Expects:
+ * - Input signals have already been narrowed by the handler control flow
+ *
+ * Returns:
+ * - Memory and skill action services that prepare dispatchable action plans
+ */
+export const createDefaultActionServices = (): Required<AgentSignalActionServices> => ({
+ memoryActions: {
+ prepare: (signal) => ({
+ action: planUserMemory(signal),
+ reason: signal.payload.reason,
+ risk: 'medium',
+ }),
+ },
+ skillActions: {
+ prepare: (signal) => ({
+ action: planSkillManagement(signal),
+ reason: signal.payload.reason,
+ risk: 'medium',
+ }),
+ },
+});
diff --git a/src/server/services/agentSignal/services/classifierServices.ts b/src/server/services/agentSignal/services/classifierServices.ts
new file mode 100644
index 00000000000..f2f3580c6d9
--- /dev/null
+++ b/src/server/services/agentSignal/services/classifierServices.ts
@@ -0,0 +1,94 @@
+import type {
+ AgentSignalFeedbackDomainStagePayload,
+ AgentSignalFeedbackDomainTarget,
+ AgentSignalFeedbackSatisfactionStagePayload,
+ SignalFeedbackSatisfaction,
+} from '../policies/types';
+
+/**
+ * Input consumed by satisfaction classifier services.
+ */
+export interface SatisfactionClassifierInput {
+ /**
+ * Trimmed user feedback message to classify.
+ */
+ message: string;
+ /**
+ * Optional serialized runtime context captured with the source event.
+ */
+ serializedContext?: string;
+}
+
+/**
+ * Input recorded when classifier structured output is malformed.
+ */
+export interface ClassifierMalformedOutputDiagnosticInput {
+ /** Error thrown by the model-output parser or schema validator. */
+ error: unknown;
+ /** Stable reason used by the processor stop result. */
+ reason: string;
+ /** Runtime scope key for correlating policy-state and traces. */
+ scopeKey: string;
+ /** Signal id when the malformed output happened after signal creation. */
+ signalId?: string;
+ /** Source id for the source or current signal root. */
+ sourceId?: string;
+ /** Classifier stage that produced malformed structured output. */
+ stage: 'domain' | 'satisfaction';
+}
+
+/**
+ * Records recoverable classifier diagnostics outside the processor control path.
+ */
+export interface ClassifierDiagnosticsService {
+ /**
+ * Records malformed structured classifier output for later debugging.
+ */
+ recordMalformedOutput: (input: ClassifierMalformedOutputDiagnosticInput) => Promise<void>;
+}
+
+/**
+ * Classifies a user message into the feedback satisfaction stage.
+ */
+export interface SatisfactionClassifierService {
+ /**
+ * Classifies one feedback message for overall satisfaction.
+ *
+ * Use when:
+ * - A user-message source should produce one satisfaction signal
+ * - The caller has already normalized the text passed to the classifier
+ *
+ * Expects:
+ * - `input.message` is trimmed and belongs to the same source event as the context
+ * - `input.serializedContext` is omitted when no context was captured
+ *
+ * Returns:
+ * - One stage payload ready to embed in `signal.feedback.satisfaction`
+ */
+ classify: (
+ input: SatisfactionClassifierInput,
+ ) => Promise<AgentSignalFeedbackSatisfactionStagePayload>;
+}
+
+/**
+ * Classifies satisfaction signals into actionable feedback domains.
+ */
+export interface DomainClassifierService {
+ /**
+ * Classifies one satisfaction signal into one or more phase-one domain targets.
+ *
+ * Use when:
+ * - A non-neutral satisfaction signal should fan out into domain-specific signals
+ * - Domain routing should remain independent from runtime signal construction
+ *
+ * Expects:
+ * - `input.payload.result` is non-neutral before callers invoke the classifier
+ * - `input.payload.message`, evidence, and reason come from the satisfaction stage
+ *
+ * Returns:
+ * - Zero or more domain payloads for memory, none, prompt, or skill routing
+ */
+ classify: (
+ input: SignalFeedbackSatisfaction,
+ ) => Promise<Array<AgentSignalFeedbackDomainStagePayload<AgentSignalFeedbackDomainTarget>>>;
+}
diff --git a/src/server/services/agentSignal/services/index.ts b/src/server/services/agentSignal/services/index.ts
new file mode 100644
index 00000000000..b3f472b2040
--- /dev/null
+++ b/src/server/services/agentSignal/services/index.ts
@@ -0,0 +1,4 @@
+export * from './actionServices';
+export * from './classifierServices';
+export * from './procedureStateService';
+export * from './types';
diff --git a/src/server/services/agentSignal/services/procedureStateService.ts b/src/server/services/agentSignal/services/procedureStateService.ts
new file mode 100644
index 00000000000..137ac6a27d0
--- /dev/null
+++ b/src/server/services/agentSignal/services/procedureStateService.ts
@@ -0,0 +1,98 @@
+import {
+ appendAndScoreProcedureAccumulatorRecord,
+ appendProcedureAccumulatorRecord,
+} from '../procedure/accumulator';
+import { AgentSignalProcedureInspector } from '../procedure/inspector';
+import { createProcedureMarkerKeysForRead } from '../procedure/keys';
+import {
+ createProcedureMarker,
+ readFirstActiveHandledProcedureMarker,
+ writeProcedureMarker,
+} from '../procedure/marker';
+import { appendProcedureReceipt } from '../procedure/receipt';
+import { writeProcedureRecordField } from '../procedure/record';
+import type { AgentSignalPolicyStateStore } from '../store/types';
+import type { ProcedureStateService } from './types';
+
+/**
+ * Input for creating the procedure state facade.
+ */
+export interface CreateProcedureStateServiceInput {
+ /** Optional current-time provider for deterministic tests and eval runs. */
+ now?: () => number;
+ /** Policy-state store shared by procedure projections. */
+ policyStateStore: AgentSignalPolicyStateStore;
+ /** TTL in seconds for procedure policy-state fields. */
+ ttlSeconds: number;
+}
+
+/**
+ * Creates the data-plane facade for Agent Signal procedure policy state.
+ *
+ * Use when:
+ * - Policy handlers need to persist or inspect procedure projections
+ * - Tests need one injectable boundary over procedure helper functions
+ *
+ * Expects:
+ * - One policy-state store backs records, markers, receipts, and accumulators
+ *
+ * Returns:
+ * - Procedure state service backed by the provided policy-state store
+ */
+export const createProcedureStateService = (
+ input: CreateProcedureStateServiceInput,
+): ProcedureStateService => {
+ const now = input.now ?? (() => Date.now());
+ const inspector = new AgentSignalProcedureInspector(input.policyStateStore);
+
+ return {
+ accumulators: {
+ append: (record) =>
+ appendProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds),
+ appendAndScore: (record) =>
+ appendAndScoreProcedureAccumulatorRecord(input.policyStateStore, record, input.ttlSeconds, {
+ now: now(),
+ }),
+ },
+ inspect: {
+ scope: (scopeKey) => inspector.inspectScope(scopeKey),
+ },
+ markers: {
+ shouldSuppress: async (markerInput) => {
+ const marker = await readFirstActiveHandledProcedureMarker(
+ input.policyStateStore,
+ createProcedureMarkerKeysForRead(markerInput),
+ now(),
+ );
+
+ return Boolean(marker);
+ },
+ write: (marker) => writeProcedureMarker(input.policyStateStore, marker, input.ttlSeconds),
+ writeAccumulated: (markerInput) => {
+ const createdAt = now();
+
+ return writeProcedureMarker(
+ input.policyStateStore,
+ createProcedureMarker({
+ ...markerInput,
+ createdAt,
+ expiresAt: createdAt + input.ttlSeconds * 1000,
+ markerType: 'accumulated',
+ }),
+ input.ttlSeconds,
+ );
+ },
+ },
+ records: {
+ write: (record) =>
+ writeProcedureRecordField(input.policyStateStore, record, input.ttlSeconds),
+ },
+ receipts: {
+ append: (receipt) =>
+ appendProcedureReceipt(input.policyStateStore, receipt, {
+ maxItems: 8,
+ ttlSeconds: input.ttlSeconds,
+ }),
+ },
+ };
+};
diff --git a/src/server/services/agentSignal/services/types.ts b/src/server/services/agentSignal/services/types.ts
new file mode 100644
index 00000000000..a5376cdb8c2
--- /dev/null
+++ b/src/server/services/agentSignal/services/types.ts
@@ -0,0 +1,78 @@
+import type { ProcedureAccumulatorScoreResult } from '../procedure/accumulator';
+import type { AgentSignalProcedureInspectionSnapshot } from '../procedure/inspector';
+import type { ProcedureMarkerKeyInput } from '../procedure/keys';
+import type {
+ AgentSignalProcedureMarker,
+ AgentSignalProcedureReceipt,
+ AgentSignalProcedureRecord,
+} from '../procedure/types';
+
+/**
+ * Input for checking active handled procedure markers.
+ */
+export interface ProcedureMarkerSuppressInput extends ProcedureMarkerKeyInput {
+ /** Ordered intent-class fallbacks used to find compatible handled markers. */
+ intentClassCandidates?: string[];
+}
+
+/**
+ * Business input for writing an accumulated procedure marker.
+ */
+export interface ProcedureAccumulatedMarkerInput {
+ /** Domain bucket that accumulated enough evidence. */
+ domainKey: string;
+ /** Procedure intent class represented by the accumulated score. */
+ intentClass?: string;
+ /** Stable key linking the accumulated marker to a procedure source. */
+ procedureKey: string;
+ /** Procedure record id that caused this accumulated marker. */
+ recordId: string;
+ /** Runtime scope where the marker is visible. */
+ scopeKey: string;
+ /** Scored procedure signal id emitted for this accumulated marker. */
+ signalId: string;
+ /** Source id that produced the accumulated marker. */
+ sourceId?: string;
+}
+
+/**
+ * Facade for procedure policy-state persistence and inspection.
+ *
+ * This service is the data-plane boundary for procedure records, accumulators, receipts, markers,
+ * and snapshots. It keeps policy handlers from depending on individual storage helper functions.
+ */
+export interface ProcedureStateService {
+ /** Procedure accumulator operations for weak-signal bucket storage and scoring. */
+ accumulators: {
+ /** Appends one record into the scope/domain accumulator bucket. */
+ append: (record: AgentSignalProcedureRecord) => Promise<void>;
+ /** Appends one record and returns a score result when the bucket crosses scoring gates. */
+ appendAndScore: (
+ record: AgentSignalProcedureRecord,
+ ) => Promise<ProcedureAccumulatorScoreResult | undefined>;
+ };
+ /** Read-only procedure inspection operations. */
+ inspect: {
+ /** Reads records, markers, receipts, and accumulator fields for one runtime scope. */
+ scope: (scopeKey: string) => Promise<AgentSignalProcedureInspectionSnapshot>;
+ };
+ /** Procedure marker operations for write-side gates and suppression reads. */
+ markers: {
+ /** Checks whether an active handled marker suppresses the current procedure candidate. */
+ shouldSuppress: (input: ProcedureMarkerSuppressInput) => Promise<boolean>;
+ /** Writes one accumulated marker using facade-owned expiry semantics. */
+ writeAccumulated: (input: ProcedureAccumulatedMarkerInput) => Promise<void>;
+ /** Writes one marker and its scope-local marker index entry. */
+ write: (marker: AgentSignalProcedureMarker) => Promise<void>;
+ };
+ /** Scope-local procedure receipt operations. */
+ receipts: {
+ /** Appends one compact procedure receipt field. */
+ append: (receipt: AgentSignalProcedureReceipt) => Promise<void>;
+ };
+ /** Scope-local procedure record operations. */
+ records: {
+ /** Writes one compact procedure record field. */
+ write: (record: AgentSignalProcedureRecord) => Promise<void>;
+ };
+}