Skip to content

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

✨ feat: expand nightly review self-improvement (#18393)

Arvin Xue6d4acba9771
diff --git a/apps/server/src/services/agentSignal/services/briefs/selfReview.ts b/apps/server/src/services/agentSignal/services/briefs/selfReview.ts
index 5a4bebd8c96..66d853cac74 100644
--- a/apps/server/src/services/agentSignal/services/briefs/selfReview.ts
+++ b/apps/server/src/services/agentSignal/services/briefs/selfReview.ts
@@ -1,3 +1,6 @@
+import { createHash } from 'node:crypto';
+
+import { AgentModel } from '@/database/models/agent';
import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
import { BriefModel } from '@/database/models/brief';
import type { BriefItem } from '@/database/schemas';
@@ -219,6 +222,17 @@ export class AgentSignalSelfReviewBriefService {
this.userId,
this.workspaceId,
);
+ const agentModel = new AgentModel(this.db, this.userId, this.workspaceId);
+ const readAgentPromptSnapshot = async (agentId: string) => {
+ if (agentId !== brief.agentId) return;
+ const agent = await agentModel.getAgentConfigById(agentId);
+ if (!agent) return;
+ return {
+ promptHash: createHash('sha256')
+ .update(agent.systemRole ?? '')
+ .digest('hex'),
+ };
+ };
const preflight = createSelfReviewProposalPreflightService({
isSkillNameAvailable: async ({ name }) => {
const skill = await skillDocumentService.getSkill({
@@ -228,6 +242,7 @@ export class AgentSignalSelfReviewBriefService {
return !skill;
},
+ readAgentPromptSnapshot,
readSkillTargetSnapshot: (agentDocumentId) =>
skillDocumentService.readSkillTargetSnapshot({
agentDocumentId,
@@ -390,6 +405,10 @@ export class AgentSignalSelfReviewBriefService {
checkServerGate: () => true,
checkUserGate: () => isAgentSignalEnabledForUser(this.db, this.userId),
}),
+ replaceAgentPrompt: async ({ agentId, systemRole }) => {
+ if (agentId !== brief.agentId) throw new Error('Prompt proposal target changed.');
+ await agentModel.update(agentId, { systemRole });
+ },
tools,
updateProposal: async (nextProposal) => {
await this.updateProposal(brief, nextProposal);
diff --git a/apps/server/src/services/agentSignal/services/receiptService.ts b/apps/server/src/services/agentSignal/services/receiptService.ts
index 54179a9d11e..454376305b7 100644
--- a/apps/server/src/services/agentSignal/services/receiptService.ts
+++ b/apps/server/src/services/agentSignal/services/receiptService.ts
@@ -40,12 +40,7 @@ export interface AgentSignalReceiptMetadata {
reviewScope?: Scope;
/** Rollback availability/status for the linked mutation. */
rollbackStatus?:
- | 'available'
- | 'conflict'
- | 'failed'
- | 'not_found'
- | 'rolled_back'
- | 'unsupported';
+ 'available' | 'conflict' | 'failed' | 'not_found' | 'rolled_back' | 'unsupported';
/** Scoped self-reflection id for non-nightly review receipts. */
scopeId?: string;
/** Scoped self-reflection namespace for non-nightly review receipts. */
@@ -331,7 +326,9 @@ const getReceiptTopicId = (input: { sourceId: string; topicId?: string }) =>
input.topicId ?? input.sourceId;
const getActionReceiptKind = (action: ActionPlan): AgentSignalReceipt['kind'] =>
- action.operation?.domain ?? 'review';
+ action.operation?.domain === 'memory' || action.operation?.domain === 'skill'
+ ? action.operation.domain
+ : 'review';
const getActionReceiptStatus = (status: ActionStatus): AgentSignalReceipt['status'] | undefined => {
if (status === ActionStatus.Applied) return 'applied';
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts b/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
index 51fe8e5f1a0..aed56e51ebe 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/completion/buildSelfIterationReceipts.ts
@@ -4,6 +4,7 @@ import type { AgentSignalOperationMarker } from '@/server/services/agentSignal/o
import type { AgentSignalReceipt } from '../../receiptService';
import type { ToolResultWithKind } from '../finalStateExtractor';
+import type { Idea } from '../types';
/**
* Maps a durable mutation tool's api name to the user-facing receipt domain.
@@ -53,6 +54,15 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
const str = (value: unknown): string | undefined =>
typeof value === 'string' && value.length > 0 ? value : undefined;
+const getIdeas = (artifacts: ToolResultWithKind[]): Idea[] =>
+ artifacts.flatMap((artifact) => {
+ if (artifact.apiName !== 'recordSelfReviewIdea' || !isRecord(artifact.data)) return [];
+ const value = isRecord(artifact.data.idea) ? artifact.data.idea : artifact.data;
+ return typeof value.idempotencyKey === 'string' && typeof value.rationale === 'string'
+ ? [value as unknown as Idea]
+ : [];
+ });
+
/** A `skipped_unsupported` / `skipped_stale` tool status collapses to `skipped`. */
const isSkippedStatus = (status: unknown): boolean =>
typeof status === 'string' && status.startsWith('skipped');
@@ -141,6 +151,15 @@ export const buildSelfIterationReceipts = (
kind: 'review',
metadata: {
actionCount: mutations.length,
+ ...(artifacts.length > 0
+ ? {
+ selfIteration: {
+ ideas: getIdeas(artifacts),
+ mode: 'review' as const,
+ sourceId,
+ },
+ }
+ : {}),
...(marker.localDate ? { localDate: marker.localDate } : {}),
sourceType,
},
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/projection.ts b/apps/server/src/services/agentSignal/services/selfIteration/projection.ts
index 8bf507b191f..4299b4e6abd 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/projection.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/projection.ts
@@ -6,7 +6,7 @@ import type {
SelfReviewProposalBaseSnapshot,
SelfReviewProposalPlan,
} from './review/proposal';
-import type { ToolWriteResult } from './tools/shared';
+import type { SkillTargetSnapshot, ToolWriteResult } from './tools/shared';
import type {
ActionPlan,
ActionStatus as ActionStatusValue,
@@ -226,19 +226,29 @@ const getBaseSnapshot = (value: unknown): SelfReviewProposalBaseSnapshot | undef
return {
absent: getBoolean(record.absent),
agentDocumentId: pickTrimmedString(record.agentDocumentId),
+ agentId: pickTrimmedString(record.agentId),
contentHash: pickTrimmedString(record.contentHash),
+ promptHash: pickTrimmedString(record.promptHash),
documentId: pickTrimmedString(record.documentId),
documentUpdatedAt: pickTrimmedString(record.documentUpdatedAt),
managed: getBoolean(record.managed),
skillName: pickTrimmedString(record.skillName),
targetTitle: pickTrimmedString(record.targetTitle),
- targetType: record.targetType === 'skill' ? 'skill' : undefined,
+ targetType:
+ record.targetType === 'skill' || record.targetType === 'agent_prompt'
+ ? record.targetType
+ : undefined,
writable: getBoolean(record.writable),
};
};
-const getBaseSnapshots = (value: unknown): SelfReviewProposalBaseSnapshot[] =>
- Array.isArray(value) ? value.flatMap((item) => getBaseSnapshot(item) ?? []) : [];
+const getBaseSnapshots = (value: unknown): SkillTargetSnapshot[] =>
+ Array.isArray(value)
+ ? value.flatMap((item) => {
+ const snapshot = getBaseSnapshot(item);
+ return snapshot?.targetType === 'skill' ? [snapshot as SkillTargetSnapshot] : [];
+ })
+ : [];
const toActionStatus = (status: ToolWriteResult['status']): ActionStatusValue => {
if (status === 'applied') return ActionStatus.Applied;
@@ -377,14 +387,17 @@ const toEvidenceRefs = (value: unknown): ActionPlan['evidenceRefs'] =>
const toTarget = (value: unknown): ActionTarget | undefined => {
const record = toRecordOrEmpty(value);
+ const agentId = pickTrimmedString(record.agentId);
const memoryId = pickTrimmedString(record.memoryId);
const skillDocumentId = pickTrimmedString(record.skillDocumentId);
const skillName = pickTrimmedString(record.skillName);
const targetReadonly = getBoolean(record.targetReadonly);
- if (!memoryId && !skillDocumentId && !skillName && targetReadonly === undefined) return;
+ if (!agentId && !memoryId && !skillDocumentId && !skillName && targetReadonly === undefined)
+ return;
return {
+ ...(agentId ? { agentId } : {}),
...(memoryId ? { memoryId } : {}),
...(skillDocumentId ? { skillDocumentId } : {}),
...(skillName ? { skillName } : {}),
@@ -410,12 +423,23 @@ const toApplyMode = (value: unknown, outcome: ToolOutcome) => {
const toConfidence = (value: unknown) =>
typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;
-const toSkillOperation = (value: unknown, userId: string): ActionPlan['operation'] => {
+const toDomainOperation = (value: unknown, userId: string): ActionPlan['operation'] => {
const record = toRecordOrEmpty(value);
- if (record.domain !== 'skill') return;
-
const input = toRecordOrEmpty(record.input);
+ if (record.domain === 'agent' && record.operation === 'refine_prompt') {
+ const agentId = pickTrimmedString(input.agentId);
+ const systemRole = pickTrimmedString(input.systemRole);
+ if (!agentId || !systemRole) return;
+ return {
+ domain: 'agent',
+ input: { agentId, systemRole, userId: pickTrimmedString(input.userId) ?? userId },
+ operation: 'refine_prompt',
+ };
+ }
+
+ if (record.domain !== 'skill') return;
+
if (record.operation === 'create') {
return {
domain: 'skill',
@@ -472,6 +496,7 @@ const getRawActionType = (value: unknown): ActionPlan['actionType'] | undefined
value === 'write_memory' ||
value === 'create_skill' ||
value === 'refine_skill' ||
+ value === 'refine_prompt' ||
value === 'consolidate_skill' ||
value === 'noop' ||
value === 'proposal_only'
@@ -505,7 +530,7 @@ const getCompleteBaseSnapshot = ({
};
}
- if (actionType === 'refine_skill') return baseSnapshot;
+ if (actionType === 'refine_skill' || actionType === 'refine_prompt') return baseSnapshot;
return baseSnapshot;
};
@@ -530,7 +555,7 @@ const getProjectionActionFromRaw = ({
if (!actionType || actionType === 'proposal_only') return;
- const operation = toSkillOperation(record.operation, userId);
+ const operation = toDomainOperation(record.operation, userId);
const target = toTarget(record.target);
const baseSnapshot = getCompleteBaseSnapshot({
actionType,
@@ -549,7 +574,9 @@ const getProjectionActionFromRaw = ({
? `skill:${target.skillName}`
: target?.memoryId
? `memory:${target.memoryId}`
- : actionType),
+ : target?.agentId
+ ? `agent-prompt:${target.agentId}`
+ : actionType),
evidenceRefs: toEvidenceRefs(record.evidenceRefs),
idempotencyKey,
rationale:
@@ -578,7 +605,7 @@ const getProjectionActionFromRaw = ({
};
}
- if (actionType === 'refine_skill') {
+ if (actionType === 'refine_skill' || actionType === 'refine_prompt') {
if (!baseSnapshot) return;
return {
@@ -726,6 +753,14 @@ const getProjectionAction = ({
};
}
+ if (actionType === 'refine_prompt') {
+ return {
+ ...baseAction,
+ actionType,
+ baseSnapshot: baseSnapshot ?? { targetType: 'agent_prompt' },
+ };
+ }
+
return {
...baseAction,
actionType,
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
index 312af526b6c..42baa0f6663 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
@@ -114,6 +114,9 @@ describe('nightly review source handler', () => {
);
expect(deps.collectContext).toHaveBeenCalledWith({
agentId: 'agent-1',
+ // The reviewed local date rides along so receipt lookback can start from the
+ // nightly run that actually exists instead of the window end's future day.
+ localDate: '2026-05-04',
reviewWindowEnd: reviewPayload.reviewWindowEnd,
reviewWindowStart: reviewPayload.reviewWindowStart,
userId: 'user-1',
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposal.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposal.test.ts
index 4c309ac13c0..07b73523f95 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposal.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposal.test.ts
@@ -6,6 +6,7 @@ import {
buildSelfReviewProposalFromPlan,
buildSelfReviewProposalKey,
getNextProposalExpiry,
+ getSelfReviewProposalFromBriefMetadata,
isSelfReviewProposalMetadata,
refreshSelfReviewProposal,
shouldRefreshSelfReviewProposal,
@@ -256,6 +257,39 @@ describe('self-review proposal metadata', () => {
});
});
+ /**
+ * @example
+ * getSelfReviewProposalFromBriefMetadata(metadata) returns the stored refine_prompt proposal.
+ */
+ it('accepts agent prompt base snapshots so refine_prompt proposals survive persistence', () => {
+ const promptProposal = validProposalMetadata({
+ actions: [
+ {
+ actionType: 'refine_prompt',
+ baseSnapshot: {
+ agentId: 'agt_1',
+ promptHash: 'sha256:prompt',
+ targetType: 'agent_prompt',
+ },
+ evidenceRefs: [{ id: 'topic_1', type: 'topic' }],
+ idempotencyKey: 'source:refine_prompt:agent:agt_1',
+ rationale: 'Refine the agent system prompt.',
+ risk: Risk.Medium,
+ target: { agentId: 'agt_1' },
+ },
+ ],
+ actionType: 'refine_prompt',
+ proposalKey: 'agt_1:refine_prompt:agent:agt_1',
+ });
+
+ expect(isSelfReviewProposalMetadata(promptProposal)).toBe(true);
+ expect(
+ getSelfReviewProposalFromBriefMetadata({
+ agentSignal: { nightlySelfReview: { selfReviewProposal: promptProposal } },
+ }),
+ ).toEqual(promptProposal);
+ });
+
/**
* @example
* isSelfReviewProposalMetadata({ status: 'pending' }) returns false.
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.ts
index 9fd7dc0413b..edaa46acf0c 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalApply.test.ts
@@ -82,6 +82,56 @@ describe('self-review proposal apply service', () => {
vi.clearAllMocks();
});
+ it('applies an approved refine_prompt action', async () => {
+ const replaceAgentPrompt = vi.fn().mockResolvedValue(undefined);
+ const proposal = createProposal({
+ actionType: 'refine_prompt',
+ actions: [
+ {
+ actionType: 'refine_prompt',
+ baseSnapshot: {
+ agentId: 'agt_1',
+ promptHash: 'sha256:old',
+ targetType: 'agent_prompt',
+ },
+ evidenceRefs: [{ id: 'msg_1', type: 'message' }],
+ idempotencyKey: 'nightly:refine_prompt:agt_1',
+ operation: {
+ domain: 'agent',
+ input: { agentId: 'agt_1', systemRole: 'Improved prompt', userId: 'user_1' },
+ operation: 'refine_prompt',
+ },
+ rationale: 'Honor repeated corrections.',
+ risk: Risk.Medium,
+ target: { agentId: 'agt_1' },
+ },
+ ],
+ proposalKey: 'agt_1:refine_prompt:agent:agt_1',
+ });
+ const updateProposal = vi.fn();
+ const service = createSelfReviewProposalApplyService({
+ checkAction: vi.fn().mockResolvedValue({ allowed: true }),
+ checkGates: vi.fn().mockResolvedValue({ allowed: true }),
+ replaceAgentPrompt,
+ tools: { createSkillIfAbsent: vi.fn(), replaceSkillContentCAS: vi.fn() },
+ updateProposal,
+ });
+
+ await service.apply({
+ agentId: 'agt_1',
+ proposal,
+ sourceId: 'nightly-review:user_1:agt_1:2026-05-09',
+ sourceType: 'agent.nightly_review.requested',
+ userId: 'user_1',
+ });
+
+ expect(replaceAgentPrompt).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ systemRole: 'Improved prompt',
+ });
+ expect(updateProposal).toHaveBeenCalledWith(expect.objectContaining({ status: 'applied' }));
+ });
+
/**
* @example
* expect(result.proposal.status).toBe('applied');
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.ts
index e79b0623e70..9cbadefd072 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalSnapshot.test.ts
@@ -3,6 +3,27 @@ import { describe, expect, it, vi } from 'vitest';
import { createSelfReviewProposalSnapshotService } from '../proposalSnapshot';
describe('self-review proposal snapshot service', () => {
+ it('captures the reviewed agent prompt hash', async () => {
+ const service = createSelfReviewProposalSnapshotService({
+ isSkillNameAvailable: async () => true,
+ readAgentPromptSnapshot: async () => ({ promptHash: 'sha256:prompt' }),
+ readSkillTargetSnapshot: async () => undefined,
+ });
+
+ await expect(
+ service.captureActionSnapshot({
+ actionType: 'refine_prompt',
+ agentId: 'agent-1',
+ input: { agentId: 'agent-1' },
+ userId: 'user-1',
+ }),
+ ).resolves.toEqual({
+ agentId: 'agent-1',
+ promptHash: 'sha256:prompt',
+ targetType: 'agent_prompt',
+ });
+ });
+
/**
* @example
* expect(snapshot).toEqual({ targetType: 'skill', contentHash: 'sha256:base' });
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/receiptActivity.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/receiptActivity.test.ts
new file mode 100644
index 00000000000..0be68c858a4
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/receiptActivity.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import type { AgentSignalReceiptMetadata } from '../../../receiptService';
+import { Risk } from '../../types';
+import type { NightlyReceiptDayPage } from '../receiptActivity';
+import { groupRecurringReviewIdeas, listNightlyReceiptLocalDates } from '../receiptActivity';
+
+const ideaMetadata = (idempotencyKeys: string[]): AgentSignalReceiptMetadata => ({
+ selfIteration: {
+ ideas: idempotencyKeys.map((idempotencyKey) => ({
+ evidenceRefs: [],
+ idempotencyKey,
+ rationale: 'Keep deck exports reusable.',
+ risk: Risk.Low,
+ })),
+ mode: 'review',
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
+ },
+});
+
+describe('listNightlyReceiptLocalDates', () => {
+ /**
+ * @example
+ * listNightlyReceiptLocalDates({ localDate: '2026-05-04' })[0] is '2026-05-04'.
+ */
+ it('starts at the reviewed local date instead of the review window end', () => {
+ expect(listNightlyReceiptLocalDates({ localDate: '2026-05-04' })).toEqual([
+ '2026-05-04',
+ '2026-05-03',
+ '2026-05-02',
+ '2026-05-01',
+ '2026-04-30',
+ '2026-04-29',
+ '2026-04-28',
+ ]);
+ });
+});
+
+describe('groupRecurringReviewIdeas', () => {
+ const pageFor = (localDate: string, receipts: NightlyReceiptDayPage['receipts']) => ({
+ localDate,
+ receipts,
+ });
+
+ /**
+ * @example
+ * groupRecurringReviewIdeas(pages) returns [] for one nightly run.
+ */
+ it('does not treat repeated ideas inside one nightly run as recurring', () => {
+ const pages = [
+ pageFor('2026-05-04', [
+ {
+ id: 'receipt-1',
+ metadata: ideaMetadata([
+ 'nightly-review:user-1:agent-1:2026-05-04:create_skill:skill:deck',
+ 'nightly-review:user-1:agent-1:2026-05-04:create_skill:skill:deck',
+ ]),
+ },
+ {
+ id: 'receipt-2',
+ metadata: ideaMetadata([
+ 'nightly-review:user-1:agent-1:2026-05-04:create_skill:skill:deck',
+ ]),
+ },
+ ]),
+ ];
+
+ expect(groupRecurringReviewIdeas(pages)).toEqual([]);
+ });
+
+ /**
+ * @example
+ * groupRecurringReviewIdeas(pages) returns [{ count: 2 }] across two nights.
+ */
+ it('counts one matching idea per distinct nightly run', () => {
+ const pages = [
+ pageFor('2026-05-04', [
+ {
+ id: 'receipt-1',
+ metadata: ideaMetadata([
+ 'nightly-review:user-1:agent-1:2026-05-04:create_skill:skill:deck',
+ 'nightly-review:user-1:agent-1:2026-05-04:create_skill:skill:deck',
+ ]),
+ },
+ ]),
+ pageFor('2026-05-03', [
+ {
+ id: 'receipt-2',
+ metadata: ideaMetadata([
+ 'nightly-review:user-1:agent-1:2026-05-03:create_skill:skill:deck',
+ ]),
+ },
+ ]),
+ ];
+
+ expect(groupRecurringReviewIdeas(pages)).toEqual([
+ {
+ count: 2,
+ key: 'nightly-review:create_skill:skill:deck',
+ receiptIds: ['receipt-1', 'receipt-2'],
+ },
+ ]);
+ });
+});
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/signals.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/signals.test.ts
index 38551200b14..47f760dce57 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/signals.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/signals.test.ts
@@ -30,6 +30,22 @@ const createEmptyReceiptActivityForTest = (): ReceiptActivityDigest => ({
});
describe('deriveSelfReviewSignals', () => {
+ it('promotes matching review ideas across days into a recurring signal', () => {
+ const signals = deriveSelfReviewSignals({
+ documentActivity: createEmptyDocumentActivityForTest(),
+ feedbackActivity: createEmptyFeedbackActivityForTest(),
+ receiptActivity: {
+ ...createEmptyReceiptActivityForTest(),
+ duplicateGroups: [{ count: 3, key: 'deck-workflow', receiptIds: ['r1', 'r2', 'r3'] }],
+ },
+ toolActivity: [],
+ });
+
+ expect(signals).toContainEqual(
+ expect.objectContaining({ kind: 'recurring_review_idea', strength: 'strong' }),
+ );
+ });
+
/**
* @example
* Tool activity by itself is telemetry only and should stay weak.
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts
index 9c6c2746701..91083948bc3 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/collect.ts
@@ -64,6 +64,8 @@ export interface NightlyReviewReadInput {
agentId: string;
/** Maximum summaries to return from the read adapter. */
limit?: number;
+ /** User-local calendar date (`YYYY-MM-DD`) this review covers. */
+ localDate?: string;
/** Review window end as an ISO string. */
reviewWindowEnd: string;
/** Review window start as an ISO string. */
@@ -381,6 +383,8 @@ export interface SelfReviewSignal {
export type SelfReviewSignalKind =
| 'durable_user_preference'
| 'frequent_tool_workflow'
+ | 'recurring_review_idea'
+ | 'repeated_user_correction'
| 'hinted_skill_document_changed'
| 'pending_related_proposal_exists'
| 'repeated_tool_failure'
@@ -463,6 +467,8 @@ export interface NightlyReviewReadAdapters {
export interface CollectNightlyReviewContextInput {
/** Stable agent id being reviewed. */
agentId: string;
+ /** User-local calendar date (`YYYY-MM-DD`) this review covers. */
+ localDate?: string;
/**
* Maximum managed skill summaries in the returned context.
*
@@ -944,6 +950,7 @@ export const createSelfReviewContextService = (
const maxRelevantMemories = input.maxRelevantMemories ?? DEFAULT_MAX_RELEVANT_MEMORIES;
const readInput = {
agentId: input.agentId,
+ localDate: input.localDate,
reviewWindowEnd: input.reviewWindowEnd,
reviewWindowStart: input.reviewWindowStart,
userId: input.userId,
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts
index a8cd3315b3d..e26d5a815d1 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/handler.ts
@@ -285,6 +285,7 @@ export const createNightlyReviewSourceHandler = (
() =>
deps.collectContext({
agentId: payload.agentId,
+ localDate: payload.localDate,
reviewWindowEnd: payload.reviewWindowEnd,
reviewWindowStart: payload.reviewWindowStart,
userId: payload.userId,
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts
index f0b2a6f0a06..897db771aa8 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposal.ts
@@ -29,6 +29,7 @@ const SELF_ITERATION_ACTION_TYPES = [
'write_memory',
'create_skill',
'refine_skill',
+ 'refine_prompt',
'consolidate_skill',
'noop',
'proposal_only',
@@ -71,7 +72,7 @@ export interface BuildSelfReviewProposalKeyInput {
/** Stable target id inside the selected target type. */
targetId: string;
/** Target namespace used to avoid collisions across resource tables. */
- targetType: 'agent_document' | 'memory' | 'skill' | 'unknown';
+ targetType: 'agent' | 'agent_document' | 'memory' | 'skill' | 'unknown';
}
export interface SelfReviewProposalBaseSnapshot {
@@ -79,6 +80,8 @@ export interface SelfReviewProposalBaseSnapshot {
absent?: boolean;
/** Agent document id when the proposal targets managed skill/document state. */
agentDocumentId?: string;
+ /** Agent id when the proposal targets its system prompt. */
+ agentId?: string;
/** Content hash observed when the proposal was created. */
contentHash?: string;
/** Canonical document id observed when the proposal was created. */
@@ -87,12 +90,14 @@ export interface SelfReviewProposalBaseSnapshot {
documentUpdatedAt?: string;
/** Whether the target was managed by Agent Signal. */
managed?: boolean;
+ /** Hash of the agent system prompt observed when the proposal was created. */
+ promptHash?: string;
/** Stable skill name observed or reserved when the proposal was created. */
skillName?: string;
/** Human-readable target title observed at proposal time. */
targetTitle?: string;
/** Target domain captured by the proposal snapshot. */
- targetType?: 'skill';
+ targetType?: 'agent_prompt' | 'skill';
/** Whether the target was writable at proposal time. */
writable?: boolean;
}
@@ -138,7 +143,8 @@ export interface SelfReviewIdea {
* @param TActionType - Mergeable action type that must carry a complete base snapshot.
*/
export type MergeableSelfReviewProposalActionPlan<
- TActionType extends 'create_skill' | 'refine_skill' = 'create_skill' | 'refine_skill',
+ TActionType extends 'create_skill' | 'refine_prompt' | 'refine_skill' =
+ 'create_skill' | 'refine_prompt' | 'refine_skill',
> = ActionPlan & {
/** Mergeable action type that will be applied from a frozen proposal. */
actionType: TActionType;
@@ -151,7 +157,7 @@ export type MergeableSelfReviewProposalActionPlan<
*/
export type NonMergeableSelfReviewProposalActionPlan = ActionPlan & {
/** Non-mergeable action type that can use legacy title-only fallback snapshots. */
- actionType: Exclude<ActionType, 'create_skill' | 'refine_skill'>;
+ actionType: Exclude<ActionType, 'create_skill' | 'refine_prompt' | 'refine_skill'>;
/** Optional proposal snapshot supplied by callers before projection. */
baseSnapshot?: SelfReviewProposalBaseSnapshot;
};
@@ -263,13 +269,15 @@ const SelfReviewProposalBaseSnapshotSchema = z
.object({
absent: z.boolean().optional(),
agentDocumentId: z.string().optional(),
+ agentId: z.string().optional(),
contentHash: z.string().optional(),
documentId: z.string().optional(),
documentUpdatedAt: z.string().optional(),
managed: z.boolean().optional(),
+ promptHash: z.string().optional(),
skillName: z.string().optional(),
targetTitle: z.string().optional(),
- targetType: z.literal('skill').optional(),
+ targetType: z.enum(['agent_prompt', 'skill']).optional(),
writable: z.boolean().optional(),
})
.passthrough();
@@ -310,13 +318,19 @@ const getMergeableProposalSnapshotError = (action: SelfReviewProposalActionPlan)
`Mergeable proposal action requires a complete base snapshot. actionType=${action.actionType}`;
const isMergeableProposalAction = (actionType: string) =>
- actionType === 'create_skill' || actionType === 'refine_skill';
+ actionType === 'create_skill' || actionType === 'refine_skill' || actionType === 'refine_prompt';
const hasCompleteMergeableSnapshot = (
actionType: string,
snapshot: SelfReviewProposalBaseSnapshot | undefined,
) => {
- if (!snapshot || snapshot.targetType !== 'skill') return false;
+ if (!snapshot) return false;
+
+ if (actionType === 'refine_prompt') {
+ return snapshot.targetType === 'agent_prompt' && !!snapshot.agentId && !!snapshot.promptHash;
+ }
+
+ if (snapshot.targetType !== 'skill') return false;
if (actionType === 'refine_skill') {
return (
@@ -424,6 +438,7 @@ const getProposalTarget = (
if (action.target?.skillDocumentId) {
return { targetId: action.target.skillDocumentId, targetType: 'agent_document' };
}
+ if (action.target?.agentId) return { targetId: action.target.agentId, targetType: 'agent' };
if (action.target?.memoryId) return { targetId: action.target.memoryId, targetType: 'memory' };
if (action.target?.skillName) return { targetId: action.target.skillName, targetType: 'skill' };
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalApply.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalApply.ts
index a59ff391951..1a17a77f9af 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalApply.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalApply.ts
@@ -46,6 +46,8 @@ export interface SelfReviewProposalApplyAdapters {
checkGates: () => Promise<SelfReviewProposalApplyGateResult>;
/** Clock injected for deterministic apply-attempt metadata. */
now?: () => string;
+ /** Replaces an owned agent prompt after snapshot preflight. */
+ replaceAgentPrompt?: (input: { agentId: string; systemRole: string }) => Promise<void>;
/** Safe shared write tools used for approve-time proposal application. */
tools: Pick<ToolSet, 'createSkillIfAbsent' | 'replaceSkillContentCAS'>;
/** Persists updated proposal metadata. */
@@ -144,6 +146,26 @@ const prepareToolAction = (
input: ApplySelfReviewProposalInput,
adapters: SelfReviewProposalApplyAdapters,
): SelfReviewProposalActionApplyResult | PreparedToolAction => {
+ if (action.actionType === 'refine_prompt') {
+ if (
+ action.operation?.domain !== 'agent' ||
+ action.operation.operation !== 'refine_prompt' ||
+ !adapters.replaceAgentPrompt
+ ) {
+ return buildUnsupportedResult(action);
+ }
+ const agentId = pickTrimmedString(action.operation.input.agentId);
+ const systemRole = pickTrimmedString(action.operation.input.systemRole);
+ if (!agentId || !systemRole) return buildUnsupportedResult(action);
+ return {
+ action,
+ apply: async () => {
+ await adapters.replaceAgentPrompt!({ agentId, systemRole });
+ return { resourceId: agentId, status: 'applied', summary: 'Refined agent prompt.' };
+ },
+ };
+ }
+
if (action.actionType === 'consolidate_skill') {
if (
action.operation?.domain !== 'skill' ||
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalPreflight.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalPreflight.ts
index a69143c6154..16e73ccb801 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalPreflight.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalPreflight.ts
@@ -19,6 +19,8 @@ export interface SelfReviewProposalPreflightAdapters {
/** User namespace when the caller can provide it. */
userId?: string;
}) => Promise<boolean>;
+ /** Reads the current prompt hash for an owned agent. */
+ readAgentPromptSnapshot?: (agentId: string) => Promise<{ promptHash: string } | undefined>;
/** Reads current managed skill target state by agent document id. */
readSkillTargetSnapshot: (
skillDocumentId: string,
@@ -40,8 +42,7 @@ export interface SelfReviewProposalPreflightDenied {
}
export type SelfReviewProposalPreflightResult =
- | SelfReviewProposalPreflightAllowed
- | SelfReviewProposalPreflightDenied;
+ SelfReviewProposalPreflightAllowed | SelfReviewProposalPreflightDenied;
/**
* Creates approve-time preflight checks for frozen self-review proposal actions.
@@ -75,6 +76,18 @@ export const createSelfReviewProposalPreflightService = (
return checkConsolidateSkillAction(action, adapters);
}
+ if (action.actionType === 'refine_prompt') {
+ const agentId = getOperationInputString(action, 'agentId') ?? action.target?.agentId;
+ if (!agentId || action.baseSnapshot?.targetType !== 'agent_prompt') {
+ return { allowed: false, reason: 'snapshot_incomplete' };
+ }
+ const current = await adapters.readAgentPromptSnapshot?.(agentId);
+ if (!current) return { allowed: false, reason: 'target_deleted' };
+ return current.promptHash === action.baseSnapshot.promptHash
+ ? { allowed: true }
+ : { allowed: false, reason: 'content_changed' };
+ }
+
return { allowed: false, reason: 'unsupported' };
},
});
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalSnapshot.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalSnapshot.ts
index 7ea170c293f..9dbcc115ab2 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalSnapshot.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalSnapshot.ts
@@ -11,6 +11,8 @@ export interface SelfReviewProposalSnapshotAdapters {
/** User that owns the agent. */
userId: string;
}) => Promise<boolean>;
+ /** Reads the current prompt hash for the reviewed agent. */
+ readAgentPromptSnapshot?: (agentId: string) => Promise<{ promptHash: string } | undefined>;
/** Reads the current managed skill target snapshot by agent document id. */
readSkillTargetSnapshot: (
skillDocumentId: string,
@@ -20,7 +22,7 @@ export interface SelfReviewProposalSnapshotAdapters {
/** Input for capturing a complete proposal base snapshot before merge/apply. */
export interface CaptureSelfReviewProposalSnapshotInput {
/** Mergeable proposal action type to snapshot. */
- actionType: 'create_skill' | 'refine_skill';
+ actionType: 'create_skill' | 'refine_prompt' | 'refine_skill';
/** Agent that owns the target skill namespace. */
agentId: string;
/** Frozen action input from the proposal operation. */
@@ -66,6 +68,22 @@ export const createSelfReviewProposalSnapshotService = (
input,
userId,
}: CaptureSelfReviewProposalSnapshotInput): Promise<SelfReviewProposalBaseSnapshot> => {
+ if (actionType === 'refine_prompt') {
+ const value = input.agentId;
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ throw new Error('agentId is required');
+ }
+ const targetAgentId = value.trim();
+ const snapshot = await adapters.readAgentPromptSnapshot?.(targetAgentId);
+ if (!snapshot?.promptHash) throw new Error('Agent prompt snapshot is required');
+
+ return {
+ agentId: targetAgentId,
+ promptHash: snapshot.promptHash,
+ targetType: 'agent_prompt',
+ };
+ }
+
if (actionType === 'refine_skill') {
const value = input.skillDocumentId;
if (typeof value !== 'string' || value.trim().length === 0) {
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/receiptActivity.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/receiptActivity.ts
new file mode 100644
index 00000000000..59c78d1c638
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/receiptActivity.ts
@@ -0,0 +1,106 @@
+import type { AgentSignalReceiptMetadata } from '../../receiptService';
+
+/** How many nightly runs (one per user-local date) the receipt lookback covers. */
+export const NIGHTLY_RECEIPT_LOOKBACK_DAYS = 7;
+
+/** One nightly run's receipts, keyed by the user-local date that produced them. */
+export interface NightlyReceiptDayPage {
+ /** User-local calendar date of the nightly run. */
+ localDate: string;
+ /** Receipts stored on that run's nightly topic. */
+ receipts: { id: string; metadata?: AgentSignalReceiptMetadata }[];
+}
+
+/**
+ * Resolves the reviewed local date for the nightly receipt lookback.
+ *
+ * Use when:
+ * - A caller did not thread the nightly payload `localDate` into the read adapters
+ *
+ * Expects:
+ * - `reviewWindowEnd` is the exclusive end of the reviewed local day
+ *
+ * Returns:
+ * - The payload `localDate` when present, otherwise the date of the last instant
+ * inside the review window
+ */
+export const resolveReviewedLocalDate = ({
+ localDate,
+ reviewWindowEnd,
+}: {
+ localDate?: string;
+ reviewWindowEnd: string;
+}) => localDate ?? new Date(new Date(reviewWindowEnd).getTime() - 1).toISOString().slice(0, 10);
+
+/**
+ * Lists the user-local dates covered by the nightly receipt lookback.
+ *
+ * Use when:
+ * - Recurring-idea detection needs one nightly topic id per prior run
+ *
+ * Expects:
+ * - `localDate` is the reviewed calendar date, not the review window end. The window
+ * end is the *start* of the current local day, so deriving a date from it would
+ * query a future day that never holds a nightly receipt
+ *
+ * Returns:
+ * - `days` calendar dates ending at `localDate`, newest first
+ */
+export const listNightlyReceiptLocalDates = ({
+ days = NIGHTLY_RECEIPT_LOOKBACK_DAYS,
+ localDate,
+}: {
+ days?: number;
+ localDate: string;
+}) => {
+ const start = new Date(`${localDate}T00:00:00.000Z`);
+
+ return Array.from({ length: days }, (_, offset) => {
+ const day = new Date(start);
+ day.setUTCDate(day.getUTCDate() - offset);
+
+ return day.toISOString().slice(0, 10);
+ });
+};
+
+const getNormalizedIdeaKey = (idempotencyKey: string) =>
+ idempotencyKey
+ .replace(/nightly-review:\d{4}-\d{2}-\d{2}:/, 'nightly-review:')
+ .replace(/nightly-review:[^:]+:[^:]+:\d{4}-\d{2}-\d{2}:/, 'nightly-review:');
+
+/**
+ * Groups recurring self-review ideas across distinct nightly runs.
+ *
+ * Use when:
+ * - Nightly review needs `recurring_review_idea` signals from receipt history
+ *
+ * Expects:
+ * - Each page holds the receipts of exactly one user-local nightly run
+ *
+ * Returns:
+ * - Groups counted by distinct local dates, so several ideas sharing one key inside
+ * a single run never look recurring
+ */
+export const groupRecurringReviewIdeas = (pages: NightlyReceiptDayPage[]) => {
+ const ideaGroups = new Map<string, Map<string, string>>();
+
+ for (const page of pages) {
+ for (const receipt of page.receipts) {
+ for (const idea of receipt.metadata?.selfIteration?.ideas ?? []) {
+ const key = getNormalizedIdeaKey(idea.idempotencyKey);
+ const receiptIdByDate = ideaGroups.get(key) ?? new Map<string, string>();
+
+ if (!receiptIdByDate.has(page.localDate)) receiptIdByDate.set(page.localDate, receipt.id);
+ ideaGroups.set(key, receiptIdByDate);
+ }
+ }
+ }
+
+ return [...ideaGroups.entries()]
+ .filter(([, receiptIdByDate]) => receiptIdByDate.size >= 2)
+ .map(([key, receiptIdByDate]) => ({
+ count: receiptIdByDate.size,
+ key,
+ receiptIds: [...receiptIdByDate.values()],
+ }));
+};
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts
index dacd6b73e14..6214191e255 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts
@@ -1,8 +1,12 @@
+import { createHash } from 'node:crypto';
+
import type { AgentSignalRuntimeService } from '@lobechat/builtin-tool-agent-signal';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
import { pickTrimmedString, toRecord } from '@lobechat/utils';
+import pMap from 'p-map';
+import { AgentModel } from '@/database/models/agent';
import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';
import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
import { BriefModel } from '@/database/models/brief';
@@ -11,6 +15,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';
import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';
+import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';
import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
@@ -28,7 +33,7 @@ import type {
} from '../tools/shared';
import { createMemoryService } from '../tools/shared';
import type { EvidenceRef } from '../types';
-import { Risk, Scope } from '../types';
+import { buildNightlyReviewSourceId, Risk, Scope } from '../types';
import type { createServerSelfReviewBriefWriter } from './brief';
import { createBriefSelfReviewService } from './brief';
import type { SelfReviewBriefTextTranslator } from './briefText';
@@ -50,6 +55,11 @@ import {
} from './proposal';
import { createSelfReviewProposalPreflightService } from './proposalPreflight';
import { createSelfReviewProposalSnapshotService } from './proposalSnapshot';
+import {
+ groupRecurringReviewIdeas,
+ listNightlyReceiptLocalDates,
+ resolveReviewedLocalDate,
+} from './receiptActivity';
interface ProposalBriefReader {
listUnresolvedByAgentAndTrigger: (options: {
@@ -170,6 +180,7 @@ const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {
return {
...operationInput,
+ agentId: pickTrimmedString(operationInput.agentId) ?? pickTrimmedString(target.agentId),
name: pickTrimmedString(operationInput.name) ?? pickTrimmedString(target.skillName),
skillDocumentId:
pickTrimmedString(operationInput.skillDocumentId) ??
@@ -236,7 +247,13 @@ const withCompleteProposalSnapshots = async ({
};
}
- if (actionType !== 'create_skill' && actionType !== 'refine_skill') return rawAction;
+ if (
+ actionType !== 'create_skill' &&
+ actionType !== 'refine_skill' &&
+ actionType !== 'refine_prompt'
+ ) {
+ return rawAction;
+ }
return {
...action,
@@ -457,13 +474,26 @@ export const createReviewRuntimePrimitives = (
};
const readSkillTargetSnapshot = (skillDocumentId: string) =>
skillDocumentService.readSkillTargetSnapshot({ agentDocumentId: skillDocumentId, agentId });
+ const agentModel = new AgentModel(db, userId, workspaceId);
+ const readAgentPromptSnapshot = async (targetAgentId: string) => {
+ if (targetAgentId !== agentId) return;
+ const agent = await agentModel.getAgentConfigById(targetAgentId);
+ if (!agent) return;
+ return {
+ promptHash: createHash('sha256')
+ .update(agent.systemRole ?? '')
+ .digest('hex'),
+ };
+ };
const proposalPreflight = createSelfReviewProposalPreflightService({
isSkillNameAvailable,
+ readAgentPromptSnapshot,
readSkillTargetSnapshot,
});
const proposalSnapshot = createSelfReviewProposalSnapshotService({
isSkillNameAvailable,
+ readAgentPromptSnapshot,
readSkillTargetSnapshot,
});
@@ -855,7 +885,11 @@ export const createServerSelfReviewPolicyOptions = ({
updatedAt: row.updatedAt.toISOString(),
}));
},
- listReceiptActivity: async ({ agentId: targetAgentId }) =>
+ listReceiptActivity: async ({
+ agentId: targetAgentId,
+ localDate: reviewedLocalDate,
+ reviewWindowEnd,
+ }) =>
tracer.startActiveSpan(
'agent_signal.nightly_review.collector.list_receipt_activity',
{
@@ -866,17 +900,55 @@ export const createServerSelfReviewPolicyOptions = ({
},
async (span): Promise<ReceiptActivityDigest> => {
try {
+ const localDates = listNightlyReceiptLocalDates({
+ localDate: resolveReviewedLocalDate({
+ localDate: reviewedLocalDate,
+ reviewWindowEnd,
+ }),
+ });
+ const pages = await pMap(
+ localDates,
+ async (localDate) => ({
+ localDate,
+ receipts: (
+ await listAgentSignalReceipts({
+ agentId: targetAgentId,
+ limit: 50,
+ topicId: buildNightlyReviewSourceId({
+ agentId: targetAgentId,
+ localDate,
+ userId,
+ }),
+ userId,
+ })
+ ).receipts,
+ }),
+ { concurrency: 4 },
+ );
+ const receipts = pages.flatMap((page) => page.receipts);
const digest: ReceiptActivityDigest = {
- appliedCount: 0,
- duplicateGroups: [],
- failedCount: 0,
- pendingProposalCount: 0,
- recentReceipts: [],
- reviewCount: 0,
+ appliedCount: receipts.filter(
+ (item) => item.status === 'applied' || item.status === 'updated',
+ ).length,
+ duplicateGroups: groupRecurringReviewIdeas(pages),
+ failedCount: receipts.filter((item) => item.status === 'failed').length,
+ pendingProposalCount: receipts.filter((item) => item.status === 'proposed').length,
+ recentReceipts: receipts.slice(0, 50).map((item) => ({
+ id: item.id,
+ kind: item.kind,
+ metadata: item.metadata as Record<string, unknown> | undefined,
+ status: item.status,
+ summary: item.detail,
+ targetId: item.target?.id,
+ })),
+ reviewCount: receipts.filter((item) => item.kind === 'review').length,
};
- span.setAttribute('agent.signal.nightly.receipt_pending_proposal_count', 0);
- span.setAttribute('agent.signal.nightly.receipt_recent_count', 0);
+ span.setAttribute(
+ 'agent.signal.nightly.receipt_pending_proposal_count',
+ digest.pendingProposalCount,
+ );
+ span.setAttribute('agent.signal.nightly.receipt_recent_count', receipts.length);
span.setStatus({ code: SpanStatusCode.OK });
return digest;
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/signals.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/signals.ts
index c36c14fd4c7..bc943e69c7a 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/signals.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/signals.ts
@@ -90,6 +90,41 @@ export const deriveSelfReviewSignals = (
}
}
+ const correctionTopics = (input.topics ?? []).filter(
+ (topic) => (topic.correctionCount ?? 0) > 0 || topic.hasCorrection,
+ );
+ if (correctionTopics.length >= 2) {
+ signals.push({
+ evidenceRefs: correctionTopics.slice(0, 5).flatMap((topic) => topic.evidenceRefs.slice(0, 2)),
+ features: correctionTopics.slice(0, 5).map((topic) => ({
+ correctionCount: topic.correctionCount ?? 1,
+ hasCorrection: true,
+ messageCount: topic.messageCount ?? 0,
+ topicId: topic.id,
+ type: 'topic_signal' as const,
+ })),
+ kind: 'repeated_user_correction',
+ strength: correctionTopics.length >= 3 ? 'strong' : 'medium',
+ });
+ }
+
+ for (const group of input.receiptActivity.duplicateGroups.filter((item) => item.count >= 2)) {
+ signals.push({
+ evidenceRefs: group.receiptIds.slice(0, 5).map((id) => ({ id, type: 'receipt' })),
+ features: [
+ {
+ appliedCount: input.receiptActivity.appliedCount,
+ dedupedCount: group.count,
+ failedCount: input.receiptActivity.failedCount,
+ pendingProposalCount: input.receiptActivity.pendingProposalCount,
+ type: 'receipt_history',
+ },
+ ],
+ kind: 'recurring_review_idea',
+ strength: group.count >= 3 ? 'strong' : 'medium',
+ });
+ }
+
if (input.documentActivity.skillBucket.length > 0) {
const evidenceRefs: EvidenceRef[] = [];
for (const item of input.documentActivity.skillBucket) {
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/types.ts b/apps/server/src/services/agentSignal/services/selfIteration/types.ts
index 0ecb073944f..33d38e1e719 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/types.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/types.ts
@@ -141,6 +141,7 @@ export type ActionType =
| 'write_memory'
| 'create_skill'
| 'refine_skill'
+ | 'refine_prompt'
| 'consolidate_skill'
| 'noop'
| 'proposal_only';
@@ -183,13 +184,27 @@ export type SkillConsolidateOperation = DomainOperationCase<
SkillConsolidateInput
>;
+export interface PromptRefineInput {
+ agentId: string;
+ systemRole: string;
+ userId: string;
+}
+
+export type PromptRefineOperation = DomainOperationCase<
+ 'agent',
+ 'refine_prompt',
+ PromptRefineInput
+>;
+
export type DomainOperation =
| MemoryWriteOperation
| SkillConsolidateOperation
| SkillCreateOperation
- | SkillRefineOperation;
+ | SkillRefineOperation
+ | PromptRefineOperation;
export interface ActionTarget {
+ agentId?: string;
memoryId?: string;
skillDocumentId?: string;
skillName?: string;
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap b/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap
index d64c1d1b07d..9cf8c4dcbde 100644
--- a/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap
@@ -18,6 +18,9 @@ exports[`agent signal self-iteration runtime prompt > renders review mode prompt
| \`skill_document_with_tool_failure\` | Approval-gated skill refinement proposal | \`createSelfReviewProposal\` with one \`refine_skill\` action | Use the matching \`managedSkills[].documentId\` or \`documentActivity.skillBucket[].agentDocumentId\` as \`target.skillDocumentId\`; include \`operation: { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }\`; cite topic/message/agent_document evidence refs. |
| \`repeated_tool_failure\` involving \`replaceSkillContentCAS\` | Do not retry the write directly during nightly review | \`createSelfReviewProposal\` when the failed args contain a corrected skill body or a clear skill target | Prefer the failed tool args as the proposed body; call \`getEvidenceDigest\` first if the body or target is not visible in context. |
| \`skill_documents_maybe_overlap\` | Consolidation candidate | \`createSelfReviewProposal\` with \`consolidate_skill\` only when there is a canonical skill and explicit source skills | Otherwise record no proposal for this signal alone. |
+| \`frequent_tool_workflow\` | Reusable workflow candidate | \`createSelfReviewProposal\` with \`create_skill\` when the workflow spans at least 2 topics, appears in cross-day review history, or has strong supporting feedback | Provide a complete skill body and stable name. A single weak same-day occurrence remains an idea. |
+| \`repeated_user_correction\` | Agent prompt improvement candidate | \`createSelfReviewProposal\` with \`refine_prompt\` when corrections show a stable behavioral instruction that belongs in the agent prompt rather than a reusable workflow | Provide the complete replacement systemRole and cite the correction messages. Never directly overwrite the prompt. |
+| \`recurring_review_idea\` | Cross-day evidence has matured | Create the matching \`create_skill\` or \`refine_prompt\` proposal | Two or more matching review ideas across distinct local dates upgrade weak evidence to medium; three or more upgrade it to strong. |
If a rule says \`createSelfReviewProposal\`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.</review_policy_markdown><review_window>Review window: 2026-05-08T16:00:00.000Z to 2026-05-09T16:00:00.000Z</review_window><nightly_review_context_json>{"selfReviewSignals":[{"evidenceRefs":[{"id":"doc-1","type":"agent_document"}],"kind":"skill_document_with_tool_failure"}],"topics":[{"id":"topic-1","summary":"Skill update failed after a tool call."}]}</nightly_review_context_json></self_iteration_review>"
`;
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
index a7d6ef6fefc..2464d3076df 100644
--- a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
@@ -35,7 +35,7 @@ const SELF_ITERATION_SYSTEM_ROLE = [
'Do not use writeMemory for reusable workflows, checklists, templates, skill drafts, agent capabilities, or agent/topic-scoped procedures. Route those to skill actions or recordSelfFeedbackIntent(kind="skill").',
'Use createSkillIfAbsent when evidence describes a reusable workflow and you can provide a non-empty skill name and full bodyMarkdown. Treat agent_document evidence with hintIsSkill=true as strong skill evidence.',
'When review evidence supports an approval-gated change, call createSelfReviewProposal in this run; do not offer to draft it later.',
- 'For createSelfReviewProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, or record_idea. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }. Prefer recordSelfReviewIdea instead of proposal actions when the output is only a thought or question.',
+ 'For createSelfReviewProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, refine_prompt, or record_idea. For create_skill include target.skillName and operation { domain: "skill", operation: "create", input: { name, title, description, bodyMarkdown } }. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }. For refine_prompt include target.agentId and operation { domain: "agent", operation: "refine_prompt", input: { agentId, systemRole } }; agentId must equal the reviewed agent id and systemRole must be a complete replacement prompt, not a patch. Prefer recordSelfReviewIdea instead of proposal actions when the output is only a thought or question.',
'Stop after the useful self-iteration work is complete and summarize the confirmed outcome.',
].join('\n');
@@ -107,6 +107,9 @@ const createNightlyReviewPromptXml = (input: AgentSignalSelfIterationPromptInput
'| `skill_document_with_tool_failure` | Approval-gated skill refinement proposal | `createSelfReviewProposal` with one `refine_skill` action | Use the matching `managedSkills[].documentId` or `documentActivity.skillBucket[].agentDocumentId` as `target.skillDocumentId`; include `operation: { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }`; cite topic/message/agent_document evidence refs. |',
'| `repeated_tool_failure` involving `replaceSkillContentCAS` | Do not retry the write directly during nightly review | `createSelfReviewProposal` when the failed args contain a corrected skill body or a clear skill target | Prefer the failed tool args as the proposed body; call `getEvidenceDigest` first if the body or target is not visible in context. |',
'| `skill_documents_maybe_overlap` | Consolidation candidate | `createSelfReviewProposal` with `consolidate_skill` only when there is a canonical skill and explicit source skills | Otherwise record no proposal for this signal alone. |',
+ '| `frequent_tool_workflow` | Reusable workflow candidate | `createSelfReviewProposal` with `create_skill` when the workflow spans at least 2 topics, appears in cross-day review history, or has strong supporting feedback | Provide a complete skill body and stable name. A single weak same-day occurrence remains an idea. |',
+ '| `repeated_user_correction` | Agent prompt improvement candidate | `createSelfReviewProposal` with `refine_prompt` when corrections show a stable behavioral instruction that belongs in the agent prompt rather than a reusable workflow | Provide the complete replacement systemRole and cite the correction messages. Never directly overwrite the prompt. |',
+ '| `recurring_review_idea` | Cross-day evidence has matured | Create the matching `create_skill` or `refine_prompt` proposal | Two or more matching review ideas across distinct local dates upgrade weak evidence to medium; three or more upgrade it to strong. |',
'',
'If a rule says `createSelfReviewProposal`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.',
].join('\n'),