🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-signal,prompts,database): self-review now proposal actions to briefs, and automatically execute actions (#14583)
Nekob7a50206bf86
diff --git a/packages/database/src/models/__tests__/brief.test.ts b/packages/database/src/models/__tests__/brief.test.tsindex 71ef4954b3c..9b07992ab07 100644--- a/packages/database/src/models/__tests__/brief.test.ts+++ b/packages/database/src/models/__tests__/brief.test.ts@@ -230,6 +230,45 @@ describe('BriefModel', () => {});});+ describe('listUnresolvedByAgentAndTrigger', () => {+ /**+ * @example+ * listUnresolvedByAgentAndTrigger({ agentId, trigger }) returns matching older briefs even when unrelated briefs exceed the cap.+ */+ it('should filter by user, unresolved status, trigger, and agent before applying the limit', async () => {+ const model = new BriefModel(serverDB, userId);++ for (let i = 0; i < 25; i++) {+ await model.create({+ agentId: 'other-agent',+ priority: 'urgent',+ summary: `Unrelated ${i}`,+ title: `Unrelated ${i}`,+ trigger: 'other-trigger',+ type: 'decision',+ });+ }++ await model.create({+ agentId: 'agent-1',+ priority: 'normal',+ summary: 'Matching proposal',+ title: 'Matching',+ trigger: 'agent-signal:nightly-review',+ type: 'decision',+ });++ const rows = await model.listUnresolvedByAgentAndTrigger({+ agentId: 'agent-1',+ limit: 20,+ trigger: 'agent-signal:nightly-review',+ });++ expect(rows).toHaveLength(1);+ expect(rows[0].summary).toBe('Matching proposal');+ });+ });+describe('markRead', () => {it('should mark brief as read', async () => {const model = new BriefModel(serverDB, userId);diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.tsindex d5dc041d330..d5b3d93beb7 100644--- a/packages/database/src/models/agentDocuments/agentDocument.ts+++ b/packages/database/src/models/agentDocuments/agentDocument.ts@@ -310,6 +310,13 @@ export class AgentDocumentModel {content,createdAt,description: this.getMetadataDescription(metadata),+ // NOTICE:+ // Agent documents often carry Markdown `content`, but editor history and restore UI+ // depend on this serialized editor snapshot. Service callers that derive content from+ // Markdown should pass a matching `editorData` snapshot instead of relying on content alone.+ // Root cause: `document_histories` snapshots `editor_data`, so missing editor data makes+ // pre-mutation history capture impossible.+ // Removal condition: only if document history supports Markdown-content snapshots.editorData,fileType,filename,@@ -523,6 +530,14 @@ export class AgentDocumentModel {const documentUpdate: Partial<NewDocument> = {};if (content !== undefined) {+ // NOTICE:+ // Updating Markdown content alone is valid for raw consumers, but it does not refresh+ // the editor snapshot used by document history. Callers that replace full Markdown+ // should also provide `editorData` from the same content when they expect history or+ // editor restore support to keep working.+ // Root cause: `DocumentService.trySaveCurrentDocumentHistory` validates editor data+ // before creating history rows.+ // Removal condition: only if document history supports Markdown-content snapshots.const stats = this.getDocumentStats(content);documentUpdate.content = content;documentUpdate.totalCharCount = stats.totalCharCount;diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.tsindex d6fbbc539fa..6a1b181a0ba 100644--- a/packages/database/src/models/agentSignal/reviewContext.ts+++ b/packages/database/src/models/agentSignal/reviewContext.ts@@ -14,6 +14,11 @@ import type { LobeChatDatabase } from '../../type';const parseAggregateTimestamp = (value: Date | string) =>value instanceof Date ? value : new Date(value);+const explicitPreferenceCue = sql`+ ${messages.role} = 'user'+ AND ${messages.content} ~* '(please remember|for future|next time|stable preference|durable preference|\\bprefer\\b|\\bpreference\\b|以后|以后都|记住|偏好)'+`;+export interface ListAgentSignalTopicActivityOptions {agentId: string;limit: number;@@ -39,6 +44,8 @@ export interface ListAgentSignalActivityWindowOptions {}export interface AgentSignalTopicActivityRow {+ correctionCount: number;+ correctionIds: string[];failedMessages: AgentSignalFailedMessageSummary[];failedToolCalls: AgentSignalFailedToolCallSummary[];failedToolCount: number;@@ -237,6 +244,16 @@ export class AgentSignalReviewContextModel {return this.db.select({+ correctionCount:+ sql<number>`COUNT(${messages.id}) FILTER (WHERE ${explicitPreferenceCue})`.mapWith(+ Number,+ ),+ correctionIds: sql<string[]>`+ COALESCE(+ jsonb_agg(DISTINCT ${messages.id}) FILTER (WHERE ${explicitPreferenceCue}),+ '[]'::jsonb+ )+ `,failedMessages: sql<AgentSignalFailedMessageSummary[]>`COALESCE(jsonb_agg(@@ -299,6 +316,16 @@ export class AgentSignalReviewContextModel {listSelfReflectionTopicActivity = (options: ListAgentSignalSelfReflectionTopicOptions) => {return this.db.select({+ correctionCount:+ sql<number>`COUNT(${messages.id}) FILTER (WHERE ${explicitPreferenceCue})`.mapWith(+ Number,+ ),+ correctionIds: sql<string[]>`+ COALESCE(+ jsonb_agg(DISTINCT ${messages.id}) FILTER (WHERE ${explicitPreferenceCue}),+ '[]'::jsonb+ )+ `,failedMessages: sql<AgentSignalFailedMessageSummary[]>`COALESCE(jsonb_agg(diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.tsindex 9a91b3e7a16..8b2583b075c 100644--- a/packages/database/src/models/brief.ts+++ b/packages/database/src/models/brief.ts@@ -102,6 +102,44 @@ export class BriefModel {.limit(limit);}+ /**+ * Lists unresolved briefs for one agent and trigger before applying the read cap.+ *+ * Use when:+ * - Server-side collectors need a bounded, purpose-specific Daily Brief read+ * - Callers must not let unrelated unresolved briefs consume the limit+ *+ * Expects:+ * - `agentId` and `trigger` identify the proposal or signal boundary+ * - `limit` is a small bounded read budget+ *+ * Returns:+ * - Matching unresolved brief rows ordered newest first+ */+ async listUnresolvedByAgentAndTrigger({+ agentId,+ limit = 20,+ trigger,+ }: {+ agentId: string;+ limit?: number;+ trigger: string;+ }): Promise<BriefItem[]> {+ return this.db+ .select()+ .from(briefs)+ .where(+ and(+ eq(briefs.userId, this.userId),+ eq(briefs.agentId, agentId),+ eq(briefs.trigger, trigger),+ isNull(briefs.resolvedAt),+ ),+ )+ .orderBy(desc(briefs.createdAt))+ .limit(limit);+ }+async findByTaskId(taskId: string): Promise<BriefItem[]> {return this.db.select()@@ -174,6 +212,29 @@ export class BriefModel {return result[0] || null;}+ /**+ * Updates freeform brief metadata without resolving the brief.+ *+ * Use when:+ * - Server workflows need to persist intermediate Daily Brief state+ * - A proposal approve attempt must remain visible after stale or failed preflight+ *+ * Expects:+ * - `metadata` is already validated by the caller-owned feature boundary+ *+ * Returns:+ * - The updated brief row, or `null` when the brief no longer exists+ */+ async updateMetadata(id: string, metadata: BriefItem['metadata']): Promise<BriefItem | null> {+ const result = await this.db+ .update(briefs)+ .set({ metadata })+ .where(and(eq(briefs.id, id), eq(briefs.userId, this.userId)))+ .returning();++ return result[0] || null;+ }+async delete(id: string): Promise<boolean> {const result = await this.db.delete(briefs)diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.tsindex d80a6c774d5..717ae3f8f7e 100644--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts@@ -14,9 +14,13 @@ describe('agent signal nightly review prompt', () => {expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain('Use noop for ordinary successful days',);+ expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain('Noop is silent maintenance state');expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain('Auto-safe memory candidates must be explicit',);+ expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain(+ 'A durable_user_preference signal means',+ );expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain('Consolidation should stay proposal_only',);@@ -30,9 +34,44 @@ describe('agent signal nightly review prompt', () => {const [system] = createAgentSignalNightlyReviewMessages({ maintenanceSignals: [] });expect(system.content).toContain('Start from maintenanceSignals');+ expect(system.content).toContain('proposalActivity');expect(system.content).toContain('Do not re-judge satisfaction');expect(system.content).toContain('Tool activity alone must not trigger skill consolidation');- expect(system.content).toContain('Use receiptActivity to avoid duplicate or stale proposals');+ expect(system.content).toContain(+ 'Use proposalActivity for unresolved proposal refresh, stale proposal, and duplicate proposal checks',+ );+ });++ /**+ * @example+ * The prompt treats existing proposals as lifecycle state and keeps destructive changes reviewable.+ */+ it('documents proposal lifecycle and mutation safety boundaries', () => {+ const [system] = createAgentSignalNightlyReviewMessages({+ maintenanceSignals: [],+ proposalActivity: { active: [] },+ });++ expect(system.content).toContain(+ 'Existing maintenance proposals are state, not fresh evidence',+ );+ expect(system.content).toContain(+ 'Refresh a compatible pending proposal instead of creating a duplicate',+ );+ expect(system.content).toContain('Supersede an incompatible pending proposal');+ expect(system.content).toContain(+ 'Do not use old proposal content as the only evidence for a mutation',+ );+ expect(system.content).toContain(+ 'Broad in-document rewrites can be auto-applied when they preserve resource identity',+ );+ expect(system.content).toContain(+ 'value.bodyMarkdown must contain the complete replacement Markdown body',+ );+ expect(system.content).toContain('Structural or destructive changes must become proposals');+ expect(system.content).toContain(+ 'Use safe write tools for mutations; every write tool performs freshness and idempotency checks',+ );});/**diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.tsindex f50371c88f2..a99fa576450 100644--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts@@ -1,16 +1,27 @@export const AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE = ['Review the bounded daily digest for one assistant. Return only safe maintenance actions.',- 'Start from maintenanceSignals. Inspect toolActivity, documentActivity, feedbackActivity, receiptActivity, topics, managedSkills, and relevantMemories only when a signal cites them or when confirming noop.',+ 'Start from maintenanceSignals. Inspect toolActivity, documentActivity, feedbackActivity, receiptActivity, proposalActivity, topics, managedSkills, and relevantMemories only when a signal cites them or when confirming noop.','Use noop for ordinary successful days, weak evidence, ambiguous evidence, or single-source telemetry. Non-noop actions must cite evidenceRefs from the digest.',+ 'A durable_user_preference signal means the digest found explicit remember/future/preference language; it may produce write_memory when the candidate is stable, normal-sensitivity, and directly grounded in the cited topic or message.',+ 'Noop is silent maintenance state: it must not ask for approval, create a proposal, or describe a user-facing Daily Brief.','Do not re-judge satisfaction, sentiment, or user intent. feedbackActivity is already judged evidence; reuse its result and confidence only as one feature among other evidence.','Tool activity alone must not trigger skill consolidation, skill creation, or skill refinement. Tool activity may support repeated workflow or repeated failure signals only when combined with document, feedback, topic, or receipt evidence.','When maintenanceSignals include skill_document_with_tool_failure, inspect the cited skill documents and tool failures. If the cited evidence is related, return exactly one proposal_only or refine_skill action with the target skillDocumentId; do not return noop for related cited evidence.','Treat documentActivity.skillBucket and hintIsSkill:true as the primary evidence for skill document maintenance, but not as automatic authorization.','Treat documentActivity.generalDocumentBucket as ordinary document activity; it cannot independently trigger skill maintenance.',- 'Use receiptActivity to avoid duplicate or stale proposals. If a related pending proposal exists, prefer noop or explain that the existing proposal should remain pending.',+ 'Use proposalActivity for unresolved proposal refresh, stale proposal, and duplicate proposal checks. Use receiptActivity for already-applied or dismissed maintenance outcomes. If a related pending proposal exists, prefer noop or explain that the existing proposal should remain pending.',+ 'Existing maintenance proposals are state, not fresh evidence. Use proposalActivity only to suppress, refresh, supersede, expire, or explain proposal lifecycle.',+ 'Refresh a compatible pending proposal instead of creating a duplicate when new evidence supports the same target and action.',+ 'Supersede an incompatible pending proposal when the same proposalKey now needs a materially different operation.',+ 'Do not use old proposal content as the only evidence for a mutation; every non-noop action must cite fresh maintenanceSignals or supporting buckets.',+ 'If a related proposal is stale or expired, do not apply it. Either return noop or create a fresh proposal only when current evidence supports it.',+ 'Broad in-document rewrites can be auto-applied when they preserve resource identity, file structure, binding, activation path, and target freshness.',+ 'For auto-applied skill refinement, value.bodyMarkdown must contain the complete replacement Markdown body without YAML frontmatter. Do not put instruction-only text in patch for automatic refinement.',+ 'Structural or destructive changes must become proposals: delete, move, rebind, detach, split, consolidate, merge, activation changes, path changes, namespace changes, or file-structure changes.',+ 'Use safe write tools for mutations; every write tool performs freshness and idempotency checks and emits a receipt.','Attach policyHints for every non-noop action: evidenceStrength, userExplicitness, sensitivity, persistence, and mutationScope when skill-related.','Auto-safe memory candidates must be explicit, stable, normal-sensitivity preferences or durable facts; inferred, temporal, sensitive, third-party, or ambiguous memory candidates should be proposal_only or noop.',- 'Skill creation/refinement should be proposal_only unless the evidence shows explicit maintenance intent and a small targeted change. Consolidation should stay proposal_only.',+ 'Skill creation should be proposal_only unless the evidence shows explicit maintenance intent and a small targeted change. Skill refinement can be auto-applied for explicit small changes or broad in-document rewrites that preserve resource identity. Consolidation should stay proposal_only.',].join(' ');/**diff --git a/src/server/services/agentSignal/__tests__/orchestrator.test.ts b/src/server/services/agentSignal/__tests__/orchestrator.test.tsindex 14169d8d4e7..e7330565df1 100644--- a/src/server/services/agentSignal/__tests__/orchestrator.test.ts+++ b/src/server/services/agentSignal/__tests__/orchestrator.test.ts@@ -7,7 +7,11 @@ import type { AgentSignalEmitOptions } from '../emitter';import { withServerAgentSignalPolicyDefaults } from '../orchestrator';import { createBriefMaintenanceService } from '../services/maintenance/brief';import type { NightlyReviewContext } from '../services/maintenance/nightlyCollector';-import { MaintenanceActionStatus, ReviewRunStatus } from '../services/maintenance/types';+import {+ MaintenanceActionStatus,+ MaintenanceReviewScope,+ ReviewRunStatus,+} from '../services/maintenance/types';const createNightlyReviewContext = (): NightlyReviewContext => ({agentId: 'agent-1',@@ -24,6 +28,13 @@ const createNightlyReviewContext = (): NightlyReviewContext => ({},maintenanceSignals: [],managedSkills: [],+ proposalActivity: {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ },receiptActivity: {appliedCount: 0,duplicateGroups: [],@@ -46,21 +57,17 @@ const createNightlyReviewOptions = (): NonNullable<acquireReviewGuard: vi.fn(async () => true),canRunReview: vi.fn(async () => true),collectContext: vi.fn(async () => createNightlyReviewContext()),- executePlan: vi.fn(async () => ({- actions: [],- status: ReviewRunStatus.Completed,- })),- planReviewOutput: vi.fn((request) => ({- actions: [],- localDate: request.localDate,- plannerVersion: 'test',- reviewScope: request.reviewScope,- summary: request.draft.summary,- })),runMaintenanceReviewAgent: vi.fn(async () => ({- actions: [],- findings: [],- summary: 'Quiet night.',+ execution: {+ actions: [],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: {+ actions: [],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Quiet night.',+ },})),});diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.tsindex 6dd880e56c3..e501d090d22 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts@@ -1575,7 +1575,7 @@ const runMaintainerWorkflow = async (evidenceRefs: [],idempotencyKey: `same-turn-skill:${canonical.bundle.agentDocumentId}`,input: {- patch: workflowResult.bodyMarkdown,+ bodyMarkdown: workflowResult.bodyMarkdown,skillDocumentId: canonical.bundle.agentDocumentId,userId: options.userId,},diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts b/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.tsindex 30d8ad5d52f..39711c40a2b 100644--- a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts+++ b/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts@@ -9,10 +9,10 @@ import type {AgentSignalSignalHandlerDefinition,AgentSignalSourceHandlerDefinition,} from '../../../runtime/middleware';+import type { MaintenanceAgentRunResult } from '../../../services/maintenance/agentRunner';import type { NightlyReviewContext } from '../../../services/maintenance/nightlyCollector';import type {MaintenancePlan,- MaintenancePlanDraft,MaintenanceReviewRunResult,} from '../../../services/maintenance/types';import {@@ -67,6 +67,13 @@ const reviewContext = {},maintenanceSignals: [],managedSkills: [],+ proposalActivity: {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ },receiptActivity: {appliedCount: 0,duplicateGroups: [],@@ -83,30 +90,17 @@ const reviewContext = {userId: 'user-1',} satisfies NightlyReviewContext;-const reviewDraft = {- actions: [- {- actionType: 'noop',- confidence: 0.9,- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],- rationale: 'No maintenance needed.',- },- ],- findings: [],- summary: 'Quiet night.',-} satisfies MaintenancePlanDraft;-const reviewPlan = {actions: [{actionType: 'noop',- applyMode: MaintenanceApplyMode.ProposalOnly,+ applyMode: MaintenanceApplyMode.Skip,confidence: 0.9,dedupeKey: 'noop:quiet',evidenceRefs: [{ id: 'topic-1', type: 'topic' }],idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',rationale: 'No maintenance needed.',- risk: MaintenanceRisk.Medium,+ risk: MaintenanceRisk.Low,},],localDate: reviewPayload.localDate,@@ -119,22 +113,26 @@ const executionResult = {actions: [{idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',- status: MaintenanceActionStatus.Proposed,+ status: MaintenanceActionStatus.Skipped,summary: 'No maintenance needed.',},],status: ReviewRunStatus.Completed,} satisfies MaintenanceReviewRunResult;+const reviewAgentResult = {+ execution: executionResult,+ projectionPlan: reviewPlan,+ stepCount: 1,+} satisfies MaintenanceAgentRunResult;+const createDependencies = (overrides: Partial<CreateNightlyReviewSourceHandlerDependencies> = {},): CreateNightlyReviewSourceHandlerDependencies => ({acquireReviewGuard: vi.fn(async () => true),canRunReview: vi.fn(async () => true),collectContext: vi.fn(async () => reviewContext),- executePlan: vi.fn(async () => executionResult),- planReviewOutput: vi.fn(async () => reviewPlan),- runMaintenanceReviewAgent: vi.fn(async () => reviewDraft),+ runMaintenanceReviewAgent: vi.fn(async () => reviewAgentResult),...overrides,});@@ -143,7 +141,7 @@ describe('nightly review source handler', () => {* @example* expect(result.status).toBe('completed');*/- it('orchestrates collector reviewer planner and executor for a valid nightly source', async () => {+ it('orchestrates collector and bounded agent runner for a valid nightly source', async () => {const deps = createDependencies();const handler = createNightlyReviewSourceHandler(deps);@@ -166,15 +164,12 @@ describe('nightly review source handler', () => {reviewWindowStart: reviewPayload.reviewWindowStart,userId: 'user-1',});- expect(deps.runMaintenanceReviewAgent).toHaveBeenCalledWith(reviewContext);- expect(deps.planReviewOutput).toHaveBeenCalledWith({- draft: reviewDraft,+ expect(deps.runMaintenanceReviewAgent).toHaveBeenCalledWith({+ context: reviewContext,localDate: '2026-05-04',- reviewScope: MaintenanceReviewScope.Nightly,sourceId: 'nightly-review:user-1:agent-1:2026-05-04',userId: 'user-1',});- expect(deps.executePlan).toHaveBeenCalledWith(reviewPlan);expect(result).toEqual(expect.objectContaining({agentId: 'agent-1',@@ -195,27 +190,32 @@ describe('nightly review source handler', () => {it('writes review receipts before creating an eligible nightly brief', async () => {const calls: string[] = [];const deps = createDependencies({- executePlan: vi.fn(async () => ({- actions: [- {- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet',- status: MaintenanceActionStatus.Proposed,- summary: 'No maintenance needed.',- },- ],- status: ReviewRunStatus.Completed,- })),- planReviewOutput: vi.fn(async () => {- return {+ runMaintenanceReviewAgent: vi.fn(async () => ({+ execution: {+ actions: [+ {+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1',+ status: MaintenanceActionStatus.Proposed,+ summary: 'Review the skill consolidation proposal.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: {...reviewPlan,actions: [{...reviewPlan.actions[0],actionType: 'proposal_only',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ dedupeKey: 'proposal_only:skill-doc-1',+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1',+ rationale: 'Review the skill consolidation proposal.',+ risk: MaintenanceRisk.Medium,},],- } satisfies MaintenancePlan;- }),+ } satisfies MaintenancePlan,+ })),writeDailyBrief: vi.fn(async () => {calls.push('brief');@@ -233,7 +233,7 @@ describe('nightly review source handler', () => {expect(deps.writeReceipts).toHaveBeenCalledWith([expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),expect.objectContaining({- id: 'nightly-review:user-1:agent-1:2026-05-04:noop:quiet:action',+ id: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1:action',}),]);expect(deps.writeDailyBrief).toHaveBeenCalledWith(@@ -254,6 +254,171 @@ describe('nightly review source handler', () => {);});+ /**+ * @example+ * expect(deps.writeDailyBrief).toHaveBeenCalledWith(expect.objectContaining({ type: 'insight' }));+ */+ it('creates an insight brief for auto-applied nightly maintenance', async () => {+ const deps = createDependencies({+ runMaintenanceReviewAgent: vi.fn(async () => ({+ execution: {+ actions: [+ {+ idempotencyKey:+ 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',+ resourceId: 'mem-1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Saved concise release summary preference.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: {+ ...reviewPlan,+ actions: [+ {+ ...reviewPlan.actions[0],+ actionType: 'write_memory',+ applyMode: MaintenanceApplyMode.AutoApply,+ dedupeKey: 'memory:concise',+ idempotencyKey:+ 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise',+ operation: {+ domain: 'memory',+ input: {+ content: 'User prefers concise release summaries.',+ userId: 'user-1',+ },+ operation: 'write',+ },+ rationale: 'The user stated a durable release summary preference.',+ risk: MaintenanceRisk.Low,+ target: { topicIds: ['topic-1'] },+ },+ ],+ } satisfies MaintenancePlan,+ })),+ writeDailyBrief: vi.fn(async () => ({ id: 'brief-insight-1' })),+ writeReceipts: vi.fn(async () => {}),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),+ expect.objectContaining({+ id: 'nightly-review:user-1:agent-1:2026-05-04:write_memory:memory:concise:action',+ }),+ ]);+ expect(deps.writeDailyBrief).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: expect.objectContaining({+ actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },+ outcome: 'applied',+ }),+ title: 'Agent self-review updated resources',+ trigger: 'agent-signal:nightly-review',+ type: 'insight',+ }),+ );+ expect(result.execution).toEqual(+ expect.objectContaining({+ briefId: 'brief-insight-1',+ }),+ );+ });++ /**+ * @example+ * expect(deps.writeDailyBrief).not.toHaveBeenCalled();+ */+ it('keeps skipped noop reviews silent after writing the summary receipt', async () => {+ const deps = createDependencies({+ writeDailyBrief: vi.fn(async () => ({ id: 'brief-1' })),+ writeReceipts: vi.fn(async () => {}),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ const result = await handler.handle(createReviewSource());++ expect(deps.writeReceipts).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'nightly-review:user-1:agent-1:2026-05-04:review-summary' }),+ ]);+ expect(deps.writeDailyBrief).not.toHaveBeenCalled();+ expect(result.execution).toEqual(+ expect.not.objectContaining({+ briefId: expect.any(String),+ }),+ );+ });++ /**+ * @example+ * expect(brief.metadata.proposal.actions[0].operation).toBeDefined();+ */+ it('projects frozen proposal action operations from the runner projection plan', async () => {+ const proposedSkillPlan = {+ ...reviewPlan,+ actions: [+ {+ ...reviewPlan.actions[0],+ actionType: 'refine_skill',+ dedupeKey: 'refine_skill:skill-doc-1',+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',+ operation: {+ domain: 'skill',+ input: {+ patch: 'Use the newer workflow summary wording.',+ skillDocumentId: 'skill-doc-1',+ userId: 'user-1',+ },+ operation: 'refine',+ },+ target: { skillDocumentId: 'skill-doc-1' },+ },+ ],+ } satisfies MaintenancePlan;+ const deps = createDependencies({+ runMaintenanceReviewAgent: vi.fn(async () => ({+ execution: {+ actions: [+ {+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',+ status: MaintenanceActionStatus.Proposed,+ summary: 'Refine the workflow summary skill.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: proposedSkillPlan,+ })),+ writeDailyBrief: vi.fn(async () => ({ id: 'brief-1' })),+ writeReceipts: vi.fn(async () => {}),+ });+ const handler = createNightlyReviewSourceHandler(deps);++ await handler.handle(createReviewSource());++ expect(deps.writeDailyBrief).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: expect.objectContaining({+ proposal: expect.objectContaining({+ actions: [+ expect.objectContaining({+ actionType: 'refine_skill',+ operation: expect.objectContaining({+ domain: 'skill',+ operation: 'refine',+ }),+ }),+ ],+ }),+ }),+ }),+ );+ });+/*** @example* expect(result.briefWriteFailed).toBe(true);@@ -262,17 +427,32 @@ describe('nightly review source handler', () => {const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});const briefError = new Error('brief store unavailable');const deps = createDependencies({- planReviewOutput: vi.fn(async () => {- return {+ runMaintenanceReviewAgent: vi.fn(async () => ({+ execution: {+ actions: [+ {+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1',+ status: MaintenanceActionStatus.Proposed,+ summary: 'Review the skill consolidation proposal.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: {...reviewPlan,actions: [{...reviewPlan.actions[0],actionType: 'proposal_only',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ dedupeKey: 'proposal_only:skill-doc-1',+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1',+ rationale: 'Review the skill consolidation proposal.',+ risk: MaintenanceRisk.Medium,},],- } satisfies MaintenancePlan;- }),+ } satisfies MaintenancePlan,+ })),writeDailyBrief: vi.fn(async () => {throw briefError;}),@@ -315,7 +495,6 @@ describe('nightly review source handler', () => {);expect(deps.collectContext).not.toHaveBeenCalled();expect(deps.runMaintenanceReviewAgent).not.toHaveBeenCalled();- expect(deps.executePlan).not.toHaveBeenCalled();});/**diff --git a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.tsindex 90e6236cc07..4d21970ced5 100644--- a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts+++ b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts@@ -4,6 +4,7 @@ import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';import { defineSourceHandler } from '../../runtime/middleware';+import type { MaintenanceAgentRunResult } from '../../services/maintenance/agentRunner';import type { MaintenanceBriefProjection } from '../../services/maintenance/brief';import { createBriefMaintenanceService } from '../../services/maintenance/brief';import type {@@ -13,15 +14,9 @@ import type {import type {EvidenceRef,MaintenancePlan,- MaintenancePlanDraft,- MaintenancePlanRequest,MaintenanceReviewRunResult,} from '../../services/maintenance/types';-import {- buildNightlyReviewSourceId,- MaintenanceReviewScope,- ReviewRunStatus,-} from '../../services/maintenance/types';+import { buildNightlyReviewSourceId, ReviewRunStatus } from '../../services/maintenance/types';import type { AgentSignalReceipt } from '../../services/receiptService';import { createMaintenanceReviewReceipts } from '../../services/receiptService';@@ -97,12 +92,13 @@ export interface CreateNightlyReviewSourceHandlerDependencies {canRunReview: (input: NightlyReviewSourceGuardInput) => Promise<boolean>;/** Collects bounded digest context without mutating maintenance resources. */collectContext: (input: CollectNightlyReviewContextInput) => Promise<NightlyReviewContext>;- /** Applies only the planner-approved maintenance plan mutations. */- executePlan: (plan: MaintenancePlan) => Promise<MaintenanceReviewRunResult>;- /** Converts reviewer output into a deterministic maintenance plan. */- planReviewOutput: (request: MaintenancePlanRequest) => MaintenancePlan | Promise<MaintenancePlan>;- /** Runs the bounded maintenance reviewer against collected digest context. */- runMaintenanceReviewAgent: (context: NightlyReviewContext) => Promise<MaintenancePlanDraft>;+ /** Runs the bounded maintenance agent and returns execution plus the frozen projection plan. */+ runMaintenanceReviewAgent: (input: {+ context: NightlyReviewContext;+ localDate: string;+ sourceId: string;+ userId: string;+ }) => Promise<MaintenanceAgentRunResult>;/** Writes a Daily Brief payload for user-visible nightly outcomes. */writeDailyBrief?: (brief: MaintenanceBriefProjection) => Promise<{ id?: string } | void>;/** Writes durable receipts for the review summary and action outcomes. */@@ -322,7 +318,7 @@ const writeNightlyBrief = async (* - `agent.nightly_review.requested`** Downstream:- * - injected `executePlan`+ * - injected bounded maintenance agent runner** Use when:* - Tests need to run the nightly review orchestration without DB or LLM dependencies@@ -330,7 +326,7 @@ const writeNightlyBrief = async (** Expects:* - `source` is an `agent.nightly_review.requested` source with scheduler-produced payload- * - Dependencies enforce gates, idempotency, reviewer limits, and executor persistence+ * - Dependencies enforce gates, idempotency, runner limits, and persistence** Returns:* - A run result with status and enough plan metadata for future brief builders@@ -433,8 +429,8 @@ export const createNightlyReviewSourceHandler = ();},);- const draft = await runNightlyReviewSpan(- 'agent_signal.nightly_review.run_reviewer',+ const agentResult = await runNightlyReviewSpan(+ 'agent_signal.nightly_review.run_agent',{'agent.signal.agent_id': payload.agentId,'agent.signal.nightly.document_skill_event_count':@@ -448,38 +444,29 @@ export const createNightlyReviewSourceHandler = ('agent.signal.source_id': source.sourceId,'agent.signal.user_id': payload.userId,},- () => deps.runMaintenanceReviewAgent(context),- );- const plan = await runNightlyReviewSpan(- 'agent_signal.nightly_review.plan',- {- 'agent.signal.agent_id': payload.agentId,- 'agent.signal.nightly.draft_action_count': draft.actions.length,- 'agent.signal.nightly.finding_count': draft.findings.length,- 'agent.signal.source_id': source.sourceId,- 'agent.signal.user_id': payload.userId,- },() =>- Promise.resolve(- deps.planReviewOutput({- draft,- localDate: payload.localDate,- reviewScope: MaintenanceReviewScope.Nightly,- sourceId: source.sourceId,- userId: payload.userId,- }),- ),- );- const execution = await runNightlyReviewSpan(- 'agent_signal.nightly_review.execute_plan',- {- 'agent.signal.agent_id': payload.agentId,- 'agent.signal.nightly.plan_action_count': plan.actions.length,- 'agent.signal.source_id': source.sourceId,- 'agent.signal.user_id': payload.userId,+ deps.runMaintenanceReviewAgent({+ context,+ localDate: payload.localDate,+ sourceId: source.sourceId,+ userId: payload.userId,+ }),+ (span, result) => {+ span.setAttribute(+ 'agent.signal.nightly.plan_action_count',+ result.projectionPlan.actions.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.execution_action_count',+ result.execution.actions.length,+ );+ if (typeof result.stepCount === 'number') {+ span.setAttribute('agent.signal.nightly.agent_step_count', result.stepCount);+ }},- () => deps.executePlan(plan),);+ const plan = agentResult.projectionPlan;+ const execution = agentResult.execution;const receipts = createMaintenanceReviewReceipts({agentId: payload.agentId,createdAt: source.timestamp,@@ -508,6 +495,7 @@ export const createNightlyReviewSourceHandler = (agentId: payload.agentId,evidenceRefs: collectPlanEvidenceRefs(plan),localDate: payload.localDate,+ plan,result: executionWithReceipts,reviewWindowEnd: payload.reviewWindowEnd,reviewWindowStart: payload.reviewWindowStart,diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/agentRunner.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/agentRunner.test.tsnew file mode 100644index 00000000000..fc8a03272b4--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/agentRunner.test.ts@@ -0,0 +1,154 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import type { MaintenanceAgentRunResult } from '../agentRunner';+import { createMaintenanceAgentRunner } from '../agentRunner';+import type { NightlyReviewContext } from '../nightlyCollector';+import { createMaintenanceTools } from '../tools';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from '../types';++const reviewContext = {+ agentId: 'agent-1',+ documentActivity: {+ ambiguousBucket: [],+ excludedSummary: { count: 0, reasons: [] },+ generalDocumentBucket: [],+ skillBucket: [],+ },+ feedbackActivity: {+ neutralCount: 0,+ notSatisfied: [],+ satisfied: [],+ },+ maintenanceSignals: [],+ managedSkills: [],+ proposalActivity: {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ },+ receiptActivity: {+ appliedCount: 0,+ duplicateGroups: [],+ failedCount: 0,+ pendingProposalCount: 0,+ recentReceipts: [],+ reviewCount: 0,+ },+ relevantMemories: [],+ reviewWindowEnd: '2026-05-04T14:00:00.000Z',+ reviewWindowStart: '2026-05-03T14:00:00.000Z',+ toolActivity: [],+ topics: [],+ userId: 'user-1',+} satisfies NightlyReviewContext;++const createNoopTools = () =>+ createMaintenanceTools({+ reserveOperation: vi.fn(async () => ({ reserved: true as const })),+ writeReceipt: vi.fn(async () => ({ receiptId: 'receipt-1' })),+ });++describe('createMaintenanceAgentRunner', () => {+ /**+ * @example+ * expect(result.projectionPlan.actions).toHaveLength(1);+ */+ it('passes source metadata, max steps, and tools into the backend runner', async () => {+ const tools = createNoopTools();+ const run = vi.fn<() => Promise<MaintenanceAgentRunResult>>(async () => ({+ execution: {+ actions: [+ {+ idempotencyKey: 'source-1:noop',+ status: MaintenanceActionStatus.Skipped,+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ projectionPlan: {+ actions: [+ {+ actionType: 'noop',+ applyMode: MaintenanceApplyMode.Skip,+ confidence: 1,+ dedupeKey: 'noop',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'source-1:noop',+ rationale: 'No change needed.',+ risk: MaintenanceRisk.Low,+ },+ ],+ localDate: '2026-05-04',+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'No change needed.',+ },+ stepCount: 2,+ }));+ const runner = createMaintenanceAgentRunner({ maxSteps: 10, run, tools });++ const result = await runner.run({+ context: reviewContext,+ localDate: '2026-05-04',+ sourceId: 'source-1',+ userId: 'user-1',+ });++ expect(run).toHaveBeenCalledWith(+ expect.objectContaining({+ context: reviewContext,+ localDate: '2026-05-04',+ maxSteps: 10,+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'source-1',+ tools,+ userId: 'user-1',+ }),+ );+ expect(result.execution.sourceId).toBe('source-1');+ expect(result.projectionPlan.actions).toHaveLength(1);+ });++ /**+ * @example+ * expect(result.execution.status).toBe('failed');+ */+ it('returns a conservative failed envelope when the backend runner throws', async () => {+ const runner = createMaintenanceAgentRunner({+ run: vi.fn(async () => {+ throw new Error('model failed');+ }),+ tools: createNoopTools(),+ });++ const result = await runner.run({+ context: reviewContext,+ localDate: '2026-05-04',+ sourceId: 'source-1',+ userId: 'user-1',+ });++ expect(result.execution).toEqual({+ actions: [],+ sourceId: 'source-1',+ status: ReviewRunStatus.Failed,+ });+ expect(result.projectionPlan).toEqual(+ expect.objectContaining({+ actions: [],+ localDate: '2026-05-04',+ reviewScope: MaintenanceReviewScope.Nightly,+ }),+ );+ expect(result.stepCount).toBe(10);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.tsindex 8d837c28d02..646d6843272 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts+++ b/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts@@ -1,10 +1,20 @@// @vitest-environment node-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { BriefModel } from '@/database/models/brief';import { createBriefMaintenanceService, createServerMaintenanceBriefWriter } from '../brief';-import { MaintenanceActionStatus, ReviewRunStatus } from '../types';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from '../types';++afterEach(() => {+ vi.restoreAllMocks();+});describe('briefMaintenanceService', () => {/**@@ -71,6 +81,53 @@ describe('briefMaintenanceService', () => {).toBeUndefined();});+ /**+ * @example+ * Planned noop actions that execute as proposed remain silent.+ */+ it('does not create proposal briefs for proposed noop actions with receipts', () => {+ const service = createBriefMaintenanceService();++ expect(+ service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions: [+ {+ actionType: 'noop',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.9,+ dedupeKey: 'noop:quiet',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'source:noop:quiet',+ rationale: 'No maintenance change is needed.',+ risk: MaintenanceRisk.Low,+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Review found no actionable maintenance.',+ },+ result: {+ actions: [+ {+ idempotencyKey: 'source:noop:quiet',+ receiptId: 'source:noop:quiet:action',+ status: MaintenanceActionStatus.Proposed,+ summary: 'No maintenance change is needed.',+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-09T20:00:00.000Z',+ reviewWindowStart: '2026-05-09T18:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ }),+ ).toBeUndefined();+ });+/*** @example* Proposal actions produce decision briefs.@@ -108,6 +165,161 @@ describe('briefMaintenanceService', () => {expect(brief?.summary).toContain('- Review skill consolidation proposal.');});+ /**+ * @example+ * Proposal briefs retain the frozen action payload needed for later approval.+ */+ it('stores frozen proposal actions on proposal briefs', () => {+ const service = createBriefMaintenanceService();+ const projected = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions: [+ {+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.91,+ dedupeKey: 'skill:adoc-1',+ evidenceRefs: [{ id: 'adoc-1', type: 'agent_document' }],+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ operation: {+ domain: 'skill',+ input: {+ patch: 'Use the existing skill index.',+ skillDocumentId: 'adoc-1',+ userId: 'user-1',+ },+ operation: 'refine',+ },+ rationale: 'Refine the managed skill instead of creating duplicate skill drafts.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc-1' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Review found a skill refinement proposal.',+ },+ result: {+ actions: [+ {+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ receiptId: 'source:refine_skill:skill:adoc-1:action',+ status: MaintenanceActionStatus.Proposed,+ summary: 'Refine the managed skill instead of creating duplicate skill drafts.',+ },+ ],+ sourceId: 'source',+ status: ReviewRunStatus.Completed,+ summaryReceiptId: 'source:review-summary',+ },+ reviewWindowEnd: '2026-05-09T20:00:00.000Z',+ reviewWindowStart: '2026-05-09T18:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(projected?.actions).toEqual([+ { key: 'approve', label: 'Apply', type: 'resolve' },+ { key: 'dismiss', label: 'Dismiss', type: 'resolve' },+ { key: 'feedback', label: 'Request changes', type: 'comment' },+ ]);+ expect(projected?.metadata.proposal).toMatchObject({+ proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',+ status: 'pending',+ version: 1,+ });+ expect(projected?.metadata.proposal?.actions[0]).toMatchObject({+ actionType: 'refine_skill',+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ operation: {+ domain: 'skill',+ operation: 'refine',+ },+ });+ });++ /**+ * @example+ * Mixed noop and actionable proposed results only freeze the actionable proposal metadata.+ */+ it('stores proposal metadata only for real proposed actions when noop results are mixed in', () => {+ const service = createBriefMaintenanceService();+ const projected = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions: [+ {+ actionType: 'noop',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.9,+ dedupeKey: 'noop:quiet',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'source:noop:quiet',+ rationale: 'No maintenance change is needed.',+ risk: MaintenanceRisk.Low,+ },+ {+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.91,+ dedupeKey: 'skill:adoc-1',+ evidenceRefs: [{ id: 'adoc-1', type: 'agent_document' }],+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ operation: {+ domain: 'skill',+ input: {+ patch: 'Use the existing skill index.',+ skillDocumentId: 'adoc-1',+ userId: 'user-1',+ },+ operation: 'refine',+ },+ rationale: 'Refine the managed skill instead of creating duplicate skill drafts.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc-1' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Review found one actionable proposal.',+ },+ result: {+ actions: [+ {+ idempotencyKey: 'source:noop:quiet',+ receiptId: 'source:noop:quiet:action',+ status: MaintenanceActionStatus.Proposed,+ summary: 'No maintenance change is needed.',+ },+ {+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ receiptId: 'source:refine_skill:skill:adoc-1:action',+ status: MaintenanceActionStatus.Proposed,+ summary: 'Refine the managed skill instead of creating duplicate skill drafts.',+ },+ ],+ sourceId: 'source',+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-09T20:00:00.000Z',+ reviewWindowStart: '2026-05-09T18:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ expect(projected?.metadata.actionCounts.proposed).toBe(1);+ expect(projected?.summary).toContain('1 maintenance proposal need review.');+ expect(projected?.summary).not.toContain('No maintenance change is needed.');+ expect(projected?.metadata.proposal?.actions).toHaveLength(1);+ expect(projected?.metadata.proposal?.actions[0]).toMatchObject({+ actionType: 'refine_skill',+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ });+ });+/*** @example* Failed nightly runs produce an error brief when there is a user-actionable failure.@@ -238,4 +450,281 @@ describe('briefMaintenanceService', () => {await expect(writer.writeDailyBrief(brief)).resolves.toMatchObject({ id: 'brief-1' });expect(create).toHaveBeenCalledWith(brief);});++ /**+ * @example+ * A compatible pending proposal refreshes the old brief instead of creating a duplicate.+ */+ it('refreshes an existing compatible pending proposal brief', async () => {+ const service = createBriefMaintenanceService();+ const incoming = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions: [+ {+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.91,+ dedupeKey: 'skill:adoc-1',+ evidenceRefs: [{ id: 'msg-new', type: 'message' }],+ idempotencyKey: 'source:new',+ operation: {+ domain: 'skill',+ input: { patch: 'new body', skillDocumentId: 'adoc-1', userId: 'user-1' },+ operation: 'refine',+ },+ rationale: 'Refresh the same proposal.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc-1' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Refresh proposal.',+ },+ result: {+ actions: [+ {+ idempotencyKey: 'source:new',+ receiptId: 'receipt-new',+ status: MaintenanceActionStatus.Proposed,+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-10T00:00:00.000Z',+ reviewWindowStart: '2026-05-09T22:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ if (!incoming?.metadata.proposal) throw new Error('Expected projected proposal brief');++ const existingProposal = {+ ...incoming.metadata.proposal,+ actions: [+ {+ ...incoming.metadata.proposal.actions[0],+ idempotencyKey: 'source:old',+ rationale: 'Old rationale.',+ },+ ],+ createdAt: '2026-05-09T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ updatedAt: '2026-05-09T00:00:00.000Z',+ };+ const existingBrief = {+ agentId: 'agent-1',+ id: 'brief-old',+ metadata: { proposal: existingProposal },+ trigger: 'agent-signal:nightly-review',+ } as Awaited<ReturnType<BriefModel['create']>>;+ const updatedBrief = {+ ...existingBrief,+ metadata: { proposal: { ...existingProposal, actions: incoming.metadata.proposal.actions } },+ } as Awaited<ReturnType<BriefModel['create']>>;+ const create = vi.spyOn(BriefModel.prototype, 'create');+ const listUnresolvedByAgentAndTrigger = vi+ .spyOn(BriefModel.prototype, 'listUnresolvedByAgentAndTrigger')+ .mockResolvedValue([existingBrief]);+ const updateMetadata = vi+ .spyOn(BriefModel.prototype, 'updateMetadata')+ .mockResolvedValue(updatedBrief);+ const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');++ await expect(writer.writeDailyBrief(incoming)).resolves.toBe(updatedBrief);++ expect(listUnresolvedByAgentAndTrigger).toHaveBeenCalledWith({+ agentId: 'agent-1',+ limit: 20,+ trigger: 'agent-signal:nightly-review',+ });+ expect(create).not.toHaveBeenCalled();+ expect(updateMetadata).toHaveBeenCalledWith(+ 'brief-old',+ expect.objectContaining({+ proposal: expect.objectContaining({+ actions: incoming.metadata.proposal.actions,+ status: 'pending',+ }),+ }),+ );+ });++ /**+ * @example+ * An incompatible same-key proposal supersedes the old brief and creates a new one.+ */+ it('supersedes an incompatible pending proposal before creating a replacement brief', async () => {+ const service = createBriefMaintenanceService();+ const incoming = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions: [+ {+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.91,+ dedupeKey: 'skill:adoc-1',+ evidenceRefs: [{ id: 'msg-new', type: 'message' }],+ idempotencyKey: 'source:new',+ operation: {+ domain: 'skill',+ input: { patch: 'new body', skillDocumentId: 'adoc-1', userId: 'user-1' },+ operation: 'refine',+ },+ rationale: 'Replace the old proposal.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc-1' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Replacement proposal.',+ },+ result: {+ actions: [+ {+ idempotencyKey: 'source:new',+ receiptId: 'receipt-new',+ status: MaintenanceActionStatus.Proposed,+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-10T00:00:00.000Z',+ reviewWindowStart: '2026-05-09T22:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ if (!incoming?.metadata.proposal) throw new Error('Expected projected proposal brief');++ const existingProposal = incoming.metadata.proposal;+ incoming.metadata.proposal = {+ ...incoming.metadata.proposal,+ actions: [+ {+ ...incoming.metadata.proposal.actions[0],+ operation: {+ domain: 'skill',+ input: { bodyMarkdown: 'new skill', name: 'new-skill', userId: 'user-1' },+ operation: 'create',+ },+ },+ ],+ };+ const existingBrief = {+ agentId: 'agent-1',+ id: 'brief-old',+ metadata: { proposal: existingProposal },+ trigger: 'agent-signal:nightly-review',+ } as Awaited<ReturnType<BriefModel['create']>>;+ const createdBrief = { id: 'brief-new' } as Awaited<ReturnType<BriefModel['create']>>;+ const create = vi.spyOn(BriefModel.prototype, 'create').mockResolvedValue(createdBrief);+ vi.spyOn(BriefModel.prototype, 'listUnresolvedByAgentAndTrigger').mockResolvedValue([+ existingBrief,+ ]);+ const updateMetadata = vi+ .spyOn(BriefModel.prototype, 'updateMetadata')+ .mockResolvedValue(existingBrief);+ const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');++ await expect(writer.writeDailyBrief(incoming)).resolves.toBe(createdBrief);++ expect(updateMetadata).toHaveBeenCalledWith(+ 'brief-old',+ expect.objectContaining({+ proposal: expect.objectContaining({+ status: 'superseded',+ supersededBy: incoming.metadata.proposal.proposalKey,+ }),+ }),+ );+ expect(create).toHaveBeenCalledWith(incoming);+ });++ /**+ * @example+ * An expired pending proposal is marked expired and a fresh proposal brief is created.+ */+ it('marks expired pending proposals before creating a fresh brief', async () => {+ const service = createBriefMaintenanceService();+ const incoming = service.projectNightlyReviewBrief({+ agentId: 'agent-1',+ localDate: '2026-05-09',+ plan: {+ actions: [+ {+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.91,+ dedupeKey: 'skill:adoc-1',+ evidenceRefs: [],+ idempotencyKey: 'source:new',+ operation: {+ domain: 'skill',+ input: { patch: 'new body', skillDocumentId: 'adoc-1', userId: 'user-1' },+ operation: 'refine',+ },+ rationale: 'Create a fresh proposal.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc-1' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Fresh proposal.',+ },+ result: {+ actions: [+ {+ idempotencyKey: 'source:new',+ receiptId: 'receipt-new',+ status: MaintenanceActionStatus.Proposed,+ },+ ],+ status: ReviewRunStatus.Completed,+ },+ reviewWindowEnd: '2026-05-13T00:00:00.000Z',+ reviewWindowStart: '2026-05-12T22:00:00.000Z',+ timezone: 'Asia/Shanghai',+ userId: 'user-1',+ });++ if (!incoming?.metadata.proposal) throw new Error('Expected projected proposal brief');++ const existingProposal = {+ ...incoming.metadata.proposal,+ expiresAt: '2026-05-12T00:00:00.000Z',+ updatedAt: '2026-05-09T00:00:00.000Z',+ };+ const existingBrief = {+ agentId: 'agent-1',+ id: 'brief-old',+ metadata: { proposal: existingProposal },+ trigger: 'agent-signal:nightly-review',+ } as Awaited<ReturnType<BriefModel['create']>>;+ const createdBrief = { id: 'brief-new' } as Awaited<ReturnType<BriefModel['create']>>;+ const create = vi.spyOn(BriefModel.prototype, 'create').mockResolvedValue(createdBrief);+ vi.spyOn(BriefModel.prototype, 'listUnresolvedByAgentAndTrigger').mockResolvedValue([+ existingBrief,+ ]);+ const updateMetadata = vi+ .spyOn(BriefModel.prototype, 'updateMetadata')+ .mockResolvedValue(existingBrief);+ const writer = createServerMaintenanceBriefWriter({} as never, 'user-1');++ await expect(writer.writeDailyBrief(incoming)).resolves.toBe(createdBrief);++ expect(updateMetadata).toHaveBeenCalledWith(+ 'brief-old',+ expect.objectContaining({+ proposal: expect.objectContaining({ status: 'expired' }),+ }),+ );+ expect(create).toHaveBeenCalledWith(incoming);+ });});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.tsindex 96129e6a879..06160e0cb2f 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts@@ -118,6 +118,12 @@ describe('nightlyReviewService', () => {'failed_tool','receipt',]);+ expect(context.maintenanceSignals).toContainEqual(+ expect.objectContaining({+ kind: 'durable_user_preference',+ strength: 'strong',+ }),+ );expect(context.topics[0]).not.toHaveProperty('rawMessages');expect(context.topics[1]).not.toHaveProperty('rawMessages');});@@ -142,6 +148,13 @@ describe('nightlyReviewService', () => {},feedbackActivity: { neutralCount: 0, notSatisfied: [], satisfied: [] },maintenanceSignals: [],+ proposalActivity: {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ },receiptActivity: {appliedCount: 0,duplicateGroups: [],@@ -154,6 +167,45 @@ describe('nightlyReviewService', () => {});});+ it('includes pending proposal activity from the proposal adapter', async () => {+ /**+ * @example+ * expect(context.proposalActivity.active[0].proposalId).toBe('brf_1').+ */+ const service = createNightlyReviewService({+ listManagedSkills: async () => [],+ listProposalActivity: async () => ({+ active: [+ {+ actionType: 'refine_skill',+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceCount: 2,+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalId: 'brf_1',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ status: 'pending',+ summary: 'Existing skill refinement proposal.',+ targetId: 'adoc_1',+ targetTitle: 'Skill Index',+ updatedAt: '2026-05-09T00:00:00.000Z',+ },+ ],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ }),+ listRelevantMemories: async () => [],+ listTopicActivity: async () => [],+ });++ await expect(service.collectNightlyReviewContext(REVIEW_INPUT)).resolves.toMatchObject({+ proposalActivity: {+ active: [{ proposalId: 'brf_1', status: 'pending' }],+ },+ });+ });+it('clips topic activity to the default max topic budget', async () => {/*** @examplediff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyDocumentActivity.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyDocumentActivity.test.tsindex ea104d9b6ba..796a269dbdb 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyDocumentActivity.test.ts+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyDocumentActivity.test.ts@@ -64,6 +64,15 @@ describe('mapNightlyDocumentActivityRows', () => {title: 'Skill index',updatedAt: new Date('2026-05-09T18:10:00.000Z'),},+ {+ agentDocumentId: 'agent-doc-managed-skill',+ documentId: 'doc-managed-skill',+ hintIsSkill: null,+ policyLoadFormat: 'raw',+ templateId: 'agent-skill',+ title: 'Managed skill',+ updatedAt: new Date('2026-05-09T18:11:00.000Z'),+ },]).skillBucket,).toEqual([expect.objectContaining({@@ -71,6 +80,11 @@ describe('mapNightlyDocumentActivityRows', () => {hintIsSkill: false,reason: 'templateId=skills/index',}),+ expect.objectContaining({+ agentDocumentId: 'agent-doc-managed-skill',+ hintIsSkill: false,+ reason: 'templateId=agent-skill',+ }),]);});});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.tsindex 0978f52af0a..77902ec5f5f 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts@@ -153,6 +153,39 @@ describe('deriveNightlyMaintenanceSignals', () => {);});+ /**+ * @example+ * Explicit future preference corrections become durable memory review signals.+ */+ it('creates durable user preference signals from correction-bearing topics', () => {+ expect(+ deriveNightlyMaintenanceSignals({+ documentActivity: createEmptyDocumentActivityForTest(),+ feedbackActivity: createEmptyFeedbackActivityForTest(),+ receiptActivity: createEmptyReceiptActivityForTest(),+ toolActivity: [],+ topics: [+ {+ correctionCount: 1,+ correctionIds: ['msg-preference'],+ evidenceRefs: [{ id: 'msg-preference', type: 'message' }],+ highSignalReasons: ['correction'],+ id: 'topic-preference',+ messageCount: 2,+ reviewScore: 3002,+ summary: 'User explicitly asked future summaries to be concise and conclusion-first.',+ },+ ],+ }),+ ).toContainEqual(+ expect.objectContaining({+ evidenceRefs: [{ id: 'msg-preference', type: 'message' }],+ kind: 'durable_user_preference',+ strength: 'strong',+ }),+ );+ });+/*** @example* Two skill bucket documents produce an overlap review signal.diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.tsindex 53c496b311e..ccd7646504f 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts+++ b/src/server/services/agentSignal/services/maintenance/__tests__/planner.test.ts@@ -250,7 +250,8 @@ describe('maintenancePlannerService', () => {rationale: 'Repeated release-note validation failures reveal a small missing step.',target: { skillDocumentId: 'skill-release-notes' },value: {- patch: 'Add a checklist step to validate changelog sections before publishing.',+ bodyMarkdown:+ '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',skillDocumentId: 'skill-release-notes',},},@@ -268,7 +269,107 @@ describe('maintenancePlannerService', () => {applyMode: MaintenanceApplyMode.AutoApply,operation: {input: {- patch: 'Add a checklist step to validate changelog sections before publishing.',+ bodyMarkdown:+ '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',+ skillDocumentId: 'skill-release-notes',+ },+ },+ risk: MaintenanceRisk.Low,+ });+ });++ /**+ * @example+ * Patch-only skill refinements are not treated as full replacement documents.+ */+ it('keeps patch-only skill refinement drafts out of automatic apply', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'refine_skill',+ confidence: 0.94,+ evidenceRefs: [+ { id: 'tool-fail-1', type: 'tool_call' },+ { id: 'tool-fail-2', type: 'tool_call' },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ mutationScope: 'small',+ userExplicitness: 'implicit',+ },+ rationale: 'The skill needs a small checklist addition.',+ target: { skillDocumentId: 'skill-release-notes' },+ value: {+ patch: 'Add a checklist step to validate changelog sections before publishing.',+ skillDocumentId: 'skill-release-notes',+ },+ },+ ],+ findings: [],+ summary: 'Patch-only skill refinement.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ operation: undefined,+ risk: MaintenanceRisk.Medium,+ });+ });++ /**+ * @example+ * Complete replacement bodies can still be auto-applied for safe skill refinements.+ */+ it('allows skill refinement when the draft contains a complete replacement body', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'refine_skill',+ confidence: 0.94,+ evidenceRefs: [+ { id: 'tool-fail-1', type: 'tool_call' },+ { id: 'tool-fail-2', type: 'tool_call' },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ mutationScope: 'small',+ userExplicitness: 'implicit',+ },+ rationale: 'The replacement body preserves identity and adds the missing step.',+ target: { skillDocumentId: 'skill-release-notes' },+ value: {+ bodyMarkdown:+ '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',+ skillDocumentId: 'skill-release-notes',+ },+ },+ ],+ findings: [],+ summary: 'Complete skill refinement.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.AutoApply,+ operation: {+ input: {+ bodyMarkdown:+ '# Release notes\n\nUse this skill to draft release notes.\n\n- Validate changelog sections before publishing.',skillDocumentId: 'skill-release-notes',},},@@ -276,6 +377,53 @@ describe('maintenancePlannerService', () => {});});+ /**+ * @example+ * A broad rewrite that preserves the same managed skill identity remains auto-applicable.+ */+ it('allows broad in-document skill refinement when identity and evidence are stable', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'refine_skill',+ confidence: 0.93,+ evidenceRefs: [+ { id: 'msg-workflow-correction', type: 'message' },+ { id: 'tool-workflow-fail', type: 'tool_call' },+ ],+ policyHints: {+ evidenceStrength: 'strong',+ mutationScope: 'broad',+ userExplicitness: 'explicit',+ },+ rationale:+ 'The existing skill should be rewritten in place while keeping its file and binding.',+ target: { skillDocumentId: 'skill-release-notes' },+ value: {+ bodyMarkdown:+ '# Release notes\n\nRewrite the checklist in place while preserving the same managed skill identity.',+ skillDocumentId: 'skill-release-notes',+ },+ },+ ],+ findings: [],+ summary: 'Broad in-place refinement.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'refine_skill',+ applyMode: MaintenanceApplyMode.AutoApply,+ risk: MaintenanceRisk.Low,+ });+ });+/*** @example* Weak single-signal memory drafts are downgraded and cannot auto-write.@@ -309,6 +457,38 @@ describe('maintenancePlannerService', () => {});});+ /**+ * @example+ * Noop drafts are skipped maintenance state, not proposal-only review work.+ */+ it('keeps noop drafts silent instead of proposal-only', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'noop',+ confidence: 0.99,+ evidenceRefs: [],+ rationale: 'No durable maintenance is needed.',+ },+ ],+ findings: [],+ summary: 'No maintenance needed.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ expect(plan.actions[0]).toMatchObject({+ actionType: 'noop',+ applyMode: MaintenanceApplyMode.Skip,+ risk: MaintenanceRisk.Low,+ });+ });+/*** @example* Self-reflection never auto-consolidates skills.@@ -347,6 +527,68 @@ describe('maintenancePlannerService', () => {});});+ /**+ * @example+ * One mixed review can produce positive auto-apply, proposal, and skip counts.+ */+ it('separates auto-apply proposal and skip modes for planner metrics', () => {+ const planner = createMaintenancePlannerService();++ const plan = planner.plan({+ draft: {+ actions: [+ {+ actionType: 'write_memory',+ confidence: 0.95,+ evidenceRefs: [{ id: 'msg-memory', type: 'message' }],+ policyHints: {+ evidenceStrength: 'strong',+ persistence: 'stable',+ sensitivity: 'normal',+ userExplicitness: 'explicit',+ },+ rationale: 'Durable preference.',+ value: { content: 'User prefers concise release summaries.' },+ },+ {+ actionType: 'consolidate_skill',+ confidence: 0.96,+ evidenceRefs: [+ { id: 'skill-a', type: 'agent_document' },+ { id: 'skill-b', type: 'agent_document' },+ ],+ rationale: 'Two managed skills overlap and require review.',+ target: { skillDocumentId: 'skill-a' },+ value: { sourceSkillIds: ['skill-a', 'skill-b'] },+ },+ {+ actionType: 'noop',+ confidence: 0.9,+ evidenceRefs: [],+ rationale: 'No extra maintenance is needed.',+ },+ ],+ findings: [],+ summary: 'Mixed maintenance plan.',+ },+ reviewScope: MaintenanceReviewScope.Nightly,+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',+ userId: 'user-1',+ });++ const applyModeCounts = {+ autoApply: plan.actions.filter(+ (action) => action.applyMode === MaintenanceApplyMode.AutoApply,+ ).length,+ proposal: plan.actions.filter(+ (action) => action.applyMode === MaintenanceApplyMode.ProposalOnly,+ ).length,+ skip: plan.actions.filter((action) => action.applyMode === MaintenanceApplyMode.Skip).length,+ };++ expect(applyModeCounts).toEqual({ autoApply: 1, proposal: 1, skip: 1 });+ });+/*** @example* Planner caps auto-apply actions so one review cannot mutate too much.diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.tsnew file mode 100644index 00000000000..fc083fb6669--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts@@ -0,0 +1,395 @@+import { describe, expect, it } from 'vitest';++import type { MaintenanceProposalMetadata } from '../proposal';+import {+ buildMaintenanceProposalFromPlan,+ buildMaintenanceProposalKey,+ getNextProposalExpiry,+ isMaintenanceProposalMetadata,+ refreshMaintenanceProposal,+ shouldRefreshMaintenanceProposal,+ shouldSupersedeMaintenanceProposal,+ supersedeMaintenanceProposal,+} from '../proposal';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+} from '../types';++const validProposalMetadata = (+ overrides: Partial<MaintenanceProposalMetadata> = {},+): MaintenanceProposalMetadata => ({+ actions: [+ {+ actionType: 'refine_skill',+ evidenceRefs: [{ id: 'topic_1', type: 'topic' }],+ idempotencyKey: 'source:refine_skill:skill:adoc_1',+ rationale: 'Refine the skill.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ actionType: 'refine_skill',+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceWindowEnd: '2026-05-09T02:00:00.000Z',+ evidenceWindowStart: '2026-05-09T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ status: 'pending',+ updatedAt: '2026-05-09T00:00:00.000Z',+ version: 1,+ ...overrides,+});++const malformedProposalMetadata = (overrides: Record<string, unknown>) => ({+ ...validProposalMetadata(),+ ...overrides,+});++describe('maintenance proposal metadata', () => {+ /**+ * @example+ * buildMaintenanceProposalKey({ agentId: 'agt_1', actionType: 'refine_skill' })+ * returns a deterministic key scoped to target identity.+ */+ it('builds a stable proposal key from target identity', () => {+ expect(+ buildMaintenanceProposalKey({+ actionType: 'refine_skill',+ agentId: 'agt_1',+ targetId: 'adoc_1',+ targetType: 'agent_document',+ }),+ ).toBe('agt_1:refine_skill:agent_document:adoc_1');+ });++ /**+ * @example+ * getNextProposalExpiry({ createdAt, now }) extends by 72h without exceeding 7d.+ */+ it('extends expiry with a sliding window but keeps a hard cap', () => {+ expect(+ getNextProposalExpiry({+ createdAt: '2026-05-09T00:00:00.000Z',+ now: '2026-05-10T00:00:00.000Z',+ }),+ ).toBe('2026-05-13T00:00:00.000Z');++ expect(+ getNextProposalExpiry({+ createdAt: '2026-05-09T00:00:00.000Z',+ now: '2026-05-15T12:00:00.000Z',+ }),+ ).toBe('2026-05-16T00:00:00.000Z');+ });++ /**+ * @example+ * shouldRefreshMaintenanceProposal({ existing: pendingSameKey }) returns refresh true.+ */+ it('refreshes only compatible pending proposals before expiry', () => {+ expect(+ shouldRefreshMaintenanceProposal({+ existing: {+ actionType: 'refine_skill',+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ status: 'pending',+ },+ incoming: {+ actionType: 'refine_skill',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ },+ now: '2026-05-10T00:00:00.000Z',+ }),+ ).toEqual({ refresh: true });+ });++ /**+ * @example+ * shouldSupersedeMaintenanceProposal({ existing, incoming }) returns supersede true for incompatible operations.+ */+ it('supersedes incompatible pending proposals with the same key', () => {+ expect(+ shouldSupersedeMaintenanceProposal({+ existing: validProposalMetadata({+ actions: [+ {+ actionType: 'refine_skill',+ evidenceRefs: [],+ idempotencyKey: 'old',+ operation: {+ domain: 'skill',+ input: { patch: 'old', skillDocumentId: 'adoc_1', userId: 'user_1' },+ operation: 'refine',+ },+ rationale: 'old rationale',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ }),+ incoming: validProposalMetadata({+ actions: [+ {+ actionType: 'create_skill',+ evidenceRefs: [],+ idempotencyKey: 'new',+ operation: {+ domain: 'skill',+ input: { bodyMarkdown: 'new', name: 'new-skill', userId: 'user_1' },+ operation: 'create',+ },+ rationale: 'new rationale',+ risk: MaintenanceRisk.Medium,+ target: { skillName: 'new-skill' },+ },+ ],+ }),+ now: '2026-05-10T00:00:00.000Z',+ }),+ ).toEqual({ supersede: true });+ });++ /**+ * @example+ * shouldSupersedeMaintenanceProposal({ existing, incoming }) ignores rationale-only changes.+ */+ it('keeps equivalent operations compatible even when rationale changes', () => {+ const existing = validProposalMetadata({+ actions: [+ {+ actionType: 'refine_skill',+ evidenceRefs: [],+ idempotencyKey: 'old',+ operation: {+ domain: 'skill',+ input: { patch: 'old', skillDocumentId: 'adoc_1', userId: 'user_1' },+ operation: 'refine',+ },+ rationale: 'old rationale',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ });+ const incoming = validProposalMetadata({+ actions: [+ {+ actionType: 'refine_skill',+ evidenceRefs: [],+ idempotencyKey: 'new',+ operation: {+ domain: 'skill',+ input: { patch: 'new', skillDocumentId: 'adoc_1', userId: 'user_1' },+ operation: 'refine',+ },+ rationale: 'new rationale',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ });++ expect(+ shouldSupersedeMaintenanceProposal({+ existing,+ incoming,+ now: '2026-05-10T00:00:00.000Z',+ }),+ ).toEqual({ reason: 'compatible', supersede: false });+ });++ /**+ * @example+ * refreshMaintenanceProposal({ existing, incoming }) preserves createdAt and refreshes expiry.+ */+ it('refreshes proposal actions and expiry while preserving proposal identity', () => {+ const existing = validProposalMetadata({+ createdAt: '2026-05-09T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ });+ const incoming = validProposalMetadata({+ actions: [+ {+ actionType: 'refine_skill',+ evidenceRefs: [{ id: 'msg_new', type: 'message' }],+ idempotencyKey: 'new',+ rationale: 'new rationale',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ evidenceWindowEnd: '2026-05-10T01:00:00.000Z',+ evidenceWindowStart: '2026-05-10T00:00:00.000Z',+ });++ expect(+ refreshMaintenanceProposal({+ existing,+ incoming,+ now: '2026-05-10T00:00:00.000Z',+ }),+ ).toMatchObject({+ actions: incoming.actions,+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceWindowEnd: '2026-05-10T01:00:00.000Z',+ expiresAt: '2026-05-13T00:00:00.000Z',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ status: 'pending',+ updatedAt: '2026-05-10T00:00:00.000Z',+ });+ });++ /**+ * @example+ * supersedeMaintenanceProposal({ existing, supersededBy }) marks the old proposal inactive.+ */+ it('marks superseded proposals with replacement identity', () => {+ expect(+ supersedeMaintenanceProposal({+ existing: validProposalMetadata(),+ now: '2026-05-10T00:00:00.000Z',+ supersededBy: 'brief_new',+ }),+ ).toMatchObject({+ status: 'superseded',+ supersededBy: 'brief_new',+ updatedAt: '2026-05-10T00:00:00.000Z',+ });+ });++ /**+ * @example+ * isMaintenanceProposalMetadata({ status: 'pending' }) returns false.+ */+ it('does not accept arbitrary metadata as proposal metadata', () => {+ expect(isMaintenanceProposalMetadata({ status: 'pending' })).toBe(false);+ expect(isMaintenanceProposalMetadata(validProposalMetadata({ actions: [] }))).toBe(true);+ expect(+ isMaintenanceProposalMetadata(malformedProposalMetadata({ actionType: 'delete_everything' })),+ ).toBe(false);+ expect(isMaintenanceProposalMetadata(malformedProposalMetadata({ status: 'archived' }))).toBe(+ false,+ );+ });++ /**+ * @example+ * isMaintenanceProposalMetadata({ actions: [{}] }) returns false.+ */+ it('rejects malformed proposal action metadata entries', () => {+ const validAction = validProposalMetadata().actions[0];+ const malformedProposalAction = (overrides: Record<string, unknown>) =>+ malformedProposalMetadata({ actions: [{ ...validAction, ...overrides }] });++ expect(isMaintenanceProposalMetadata(malformedProposalMetadata({ actions: [{}] }))).toBe(false);+ expect(+ isMaintenanceProposalMetadata(malformedProposalAction({ evidenceRefs: undefined })),+ ).toBe(false);+ expect(+ isMaintenanceProposalMetadata(malformedProposalAction({ idempotencyKey: undefined })),+ ).toBe(false);+ expect(isMaintenanceProposalMetadata(malformedProposalAction({ rationale: undefined }))).toBe(+ false,+ );+ expect(isMaintenanceProposalMetadata(malformedProposalAction({ risk: undefined }))).toBe(false);+ expect(+ isMaintenanceProposalMetadata(malformedProposalAction({ actionType: 'delete_everything' })),+ ).toBe(false);+ expect(isMaintenanceProposalMetadata(malformedProposalAction({ risk: 'critical' }))).toBe(+ false,+ );+ });++ /**+ * @example+ * buildMaintenanceProposalFromPlan({ plan }) stores a target title snapshot for digest mapping.+ */+ it('stores a target title snapshot on frozen proposal actions', () => {+ const proposal = buildMaintenanceProposalFromPlan({+ agentId: 'agt_1',+ evidenceWindowEnd: '2026-05-09T02:00:00.000Z',+ evidenceWindowStart: '2026-05-09T00:00:00.000Z',+ now: '2026-05-09T00:00:00.000Z',+ plan: {+ actions: [+ {+ actionType: 'create_skill',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.92,+ dedupeKey: 'skill:code-review',+ evidenceRefs: [{ id: 'topic_1', type: 'topic' }],+ idempotencyKey: 'source:create_skill:skill:code-review',+ operation: {+ domain: 'skill',+ input: {+ bodyMarkdown: 'Remember review preferences.',+ name: 'code-review',+ title: 'Code Review',+ userId: 'user_1',+ },+ operation: 'create',+ },+ rationale: 'Create a reusable review skill.',+ risk: MaintenanceRisk.Medium,+ target: { skillName: 'code-review' },+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Review found a skill proposal.',+ },+ results: [+ {+ idempotencyKey: 'source:create_skill:skill:code-review',+ status: MaintenanceActionStatus.Proposed,+ },+ ],+ });++ expect(proposal?.actions[0].baseSnapshot).toMatchObject({+ targetTitle: 'Code Review',+ });+ });++ /**+ * @example+ * buildMaintenanceProposalFromPlan({ plan: noopPlan }) returns undefined for proposed noop actions.+ */+ it('does not build proposal metadata from proposed noop actions', () => {+ expect(+ buildMaintenanceProposalFromPlan({+ agentId: 'agt_1',+ evidenceWindowEnd: '2026-05-09T02:00:00.000Z',+ evidenceWindowStart: '2026-05-09T00:00:00.000Z',+ now: '2026-05-09T00:00:00.000Z',+ plan: {+ actions: [+ {+ actionType: 'noop',+ applyMode: MaintenanceApplyMode.ProposalOnly,+ confidence: 0.92,+ dedupeKey: 'noop:quiet',+ evidenceRefs: [{ id: 'topic_1', type: 'topic' }],+ idempotencyKey: 'source:noop:quiet',+ rationale: 'No maintenance change is needed.',+ risk: MaintenanceRisk.Low,+ },+ ],+ plannerVersion: 'test-planner',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Review found no actionable proposal.',+ },+ results: [+ {+ idempotencyKey: 'source:noop:quiet',+ status: MaintenanceActionStatus.Proposed,+ },+ ],+ }),+ ).toBeUndefined();+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.tsnew file mode 100644index 00000000000..2bbd626d540--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts@@ -0,0 +1,248 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { MaintenanceProposalMetadata } from '../proposal';+import { createMaintenanceProposalApplyService } from '../proposalApply';+import {+ MaintenanceActionStatus,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from '../types';++const { spanEnd, spanSetAttribute, spanSetStatus, startActiveSpan } = vi.hoisted(() => {+ interface MockSpan {+ end: ReturnType<typeof vi.fn>;+ recordException: ReturnType<typeof vi.fn>;+ setAttribute: ReturnType<typeof vi.fn>;+ setStatus: ReturnType<typeof vi.fn>;+ }++ const spanSetAttribute = vi.fn();+ const spanSetStatus = vi.fn();+ const spanEnd = vi.fn();+ const startActiveSpan = vi.fn(+ async (_name: string, _options: unknown, callback: (span: MockSpan) => unknown) =>+ callback({+ end: spanEnd,+ recordException: vi.fn(),+ setAttribute: spanSetAttribute,+ setStatus: spanSetStatus,+ }),+ );++ return { spanEnd, spanSetAttribute, spanSetStatus, startActiveSpan };+});++vi.mock('@lobechat/observability-otel/modules/agent-signal', () => ({+ tracer: { startActiveSpan },+}));++const createProposal = (+ overrides: Partial<MaintenanceProposalMetadata> = {},+): MaintenanceProposalMetadata => ({+ actionType: 'refine_skill',+ actions: [+ {+ actionType: 'refine_skill',+ baseSnapshot: {+ agentDocumentId: 'adoc_1',+ contentHash: 'sha256:base',+ documentId: 'doc_1',+ managed: true,+ writable: true,+ },+ evidenceRefs: [{ id: 'msg_1', type: 'message' }],+ idempotencyKey: 'nightly:refine_skill:adoc_1',+ operation: {+ domain: 'skill',+ input: { patch: 'new body', skillDocumentId: 'adoc_1', userId: 'user_1' },+ operation: 'refine',+ },+ rationale: 'Keep the skill up to date.',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceWindowEnd: '2026-05-09T00:00:00.000Z',+ evidenceWindowStart: '2026-05-08T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ status: 'pending',+ updatedAt: '2026-05-09T00:00:00.000Z',+ version: 1,+ ...overrides,+});++describe('maintenance proposal apply service', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ /**+ * @example+ * expect(result.proposal.status).toBe('applied');+ */+ it('applies mergeable fresh proposal actions through the executor', async () => {+ const executePlan = vi.fn().mockResolvedValue({+ actions: [+ {+ idempotencyKey: 'nightly:refine_skill:adoc_1',+ resourceId: 'adoc_1',+ status: MaintenanceActionStatus.Applied,+ summary: 'Refined managed skill.',+ },+ ],+ status: ReviewRunStatus.Completed,+ });+ const updateProposal = vi.fn();+ const writeReceipts = vi.fn();+ const service = createMaintenanceProposalApplyService({+ checkAction: vi.fn().mockResolvedValue({ allowed: true }),+ checkGates: vi.fn().mockResolvedValue({ allowed: true }),+ executePlan,+ now: () => '2026-05-09T01:00:00.000Z',+ updateProposal,+ writeReceipts,+ });++ const result = await service.apply({+ agentId: 'agt_1',+ proposal: createProposal(),+ sourceId: 'nightly-review:user_1:agt_1:2026-05-09',+ sourceType: 'agent.nightly_review.requested',+ userId: 'user_1',+ });++ expect(executePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ actions: [+ expect.objectContaining({+ applyMode: 'auto_apply',+ idempotencyKey: 'nightly:refine_skill:adoc_1',+ }),+ ],+ reviewScope: MaintenanceReviewScope.Nightly,+ }),+ );+ expect(writeReceipts).toHaveBeenCalledWith(+ expect.objectContaining({+ plan: expect.objectContaining({ actions: expect.any(Array) }),+ result: expect.objectContaining({ actions: expect.any(Array) }),+ }),+ );+ expect(result.proposal.status).toBe('applied');+ expect(result.proposal.applyAttempts?.[0].actionResults).toEqual([+ {+ idempotencyKey: 'nightly:refine_skill:adoc_1',+ resourceId: 'adoc_1',+ status: 'applied',+ summary: 'Refined managed skill.',+ },+ ]);+ expect(updateProposal).toHaveBeenCalledWith(result.proposal);+ expect(startActiveSpan).toHaveBeenCalledWith(+ 'agent_signal.maintenance_proposal.apply',+ expect.objectContaining({+ attributes: expect.objectContaining({+ 'agent.signal.agent_id': 'agt_1',+ 'agent.signal.proposal.action_count': 1,+ 'agent.signal.proposal.key': 'agt_1:refine_skill:agent_document:adoc_1',+ 'agent.signal.source_id': 'nightly-review:user_1:agt_1:2026-05-09',+ 'agent.signal.user_id': 'user_1',+ }),+ }),+ expect.any(Function),+ );+ expect(spanSetAttribute).toHaveBeenCalledWith('agent.signal.proposal.apply_status', 'applied');+ expect(spanSetAttribute).toHaveBeenCalledWith(+ 'agent.signal.proposal.executable_action_count',+ 1,+ );+ expect(spanSetStatus).toHaveBeenCalledWith({ code: SpanStatusCode.OK });+ expect(spanEnd).toHaveBeenCalled();+ });++ /**+ * @example+ * expect(result.proposal.conflictReason).toBe('document_changed');+ */+ it('skips stale proposal actions without calling the executor', async () => {+ const executePlan = vi.fn();+ const service = createMaintenanceProposalApplyService({+ checkAction: vi.fn().mockResolvedValue({ allowed: false, reason: 'document_changed' }),+ checkGates: vi.fn().mockResolvedValue({ allowed: true }),+ executePlan,+ now: () => '2026-05-09T01:00:00.000Z',+ updateProposal: vi.fn(),+ });++ const result = await service.apply({+ agentId: 'agt_1',+ proposal: createProposal(),+ sourceId: 'nightly-review:user_1:agt_1:2026-05-09',+ sourceType: 'agent.nightly_review.requested',+ userId: 'user_1',+ });++ expect(executePlan).not.toHaveBeenCalled();+ expect(result.proposal.status).toBe('stale');+ expect(result.proposal.conflictReason).toBe('document_changed');+ expect(result.proposal.applyAttempts?.[0].actionResults[0]).toMatchObject({+ idempotencyKey: 'nightly:refine_skill:adoc_1',+ status: 'skipped_stale',+ });+ expect(spanSetAttribute).toHaveBeenCalledWith('agent.signal.proposal.apply_status', 'stale');+ expect(spanSetAttribute).toHaveBeenCalledWith(+ 'agent.signal.proposal.conflict_reason',+ 'document_changed',+ );+ expect(spanSetStatus).toHaveBeenCalledWith({ code: SpanStatusCode.OK });+ });++ /**+ * @example+ * expect(result.proposal.applyAttempts?.[0].actionResults[0].status).toBe('skipped_unsupported');+ */+ it('records unsupported actions without applying them', async () => {+ const executePlan = vi.fn();+ const service = createMaintenanceProposalApplyService({+ checkAction: vi.fn().mockResolvedValue({ allowed: false, reason: 'unsupported' }),+ checkGates: vi.fn().mockResolvedValue({ allowed: true }),+ executePlan,+ now: () => '2026-05-09T01:00:00.000Z',+ updateProposal: vi.fn(),+ });++ const result = await service.apply({+ agentId: 'agt_1',+ proposal: createProposal({+ actionType: 'consolidate_skill',+ actions: [+ {+ actionType: 'consolidate_skill',+ evidenceRefs: [],+ idempotencyKey: 'nightly:consolidate_skill:adoc_1',+ rationale: 'Merge overlapping skills.',+ risk: MaintenanceRisk.High,+ target: { skillDocumentId: 'adoc_1' },+ },+ ],+ }),+ sourceId: 'nightly-review:user_1:agt_1:2026-05-09',+ sourceType: 'agent.nightly_review.requested',+ userId: 'user_1',+ });++ expect(executePlan).not.toHaveBeenCalled();+ expect(result.proposal.status).toBe('failed');+ expect(result.proposal.applyAttempts?.[0].actionResults).toEqual([+ {+ idempotencyKey: 'nightly:consolidate_skill:adoc_1',+ status: 'skipped_unsupported',+ summary: 'Proposal action is not supported by approve-time apply.',+ },+ ]);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.tsnew file mode 100644index 00000000000..ed1b2533acc--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest';++import { createMaintenanceProposalPreflightService } from '../proposalPreflight';+import { MaintenanceRisk } from '../types';++const createRefineAction = (contentHash = 'sha256:base') => ({+ actionType: 'refine_skill' as const,+ baseSnapshot: {+ agentDocumentId: 'adoc_1',+ contentHash,+ documentId: 'doc_1',+ managed: true,+ targetTitle: 'Skill Index',+ writable: true,+ },+ evidenceRefs: [],+ idempotencyKey: 'key',+ operation: {+ domain: 'skill' as const,+ input: { patch: 'new body', skillDocumentId: 'adoc_1', userId: 'user_1' },+ operation: 'refine' as const,+ },+ rationale: 'Update skill',+ risk: MaintenanceRisk.Medium,+ target: { skillDocumentId: 'adoc_1' },+});++describe('maintenance proposal preflight', () => {+ /**+ * @example+ * expect(result.allowed).toBe(true);+ */+ it('allows unchanged skill document targets', async () => {+ const service = createMaintenanceProposalPreflightService({+ readSkillTarget: async () => ({+ agentDocumentId: 'adoc_1',+ contentHash: 'sha256:base',+ documentId: 'doc_1',+ managed: true,+ targetTitle: 'Skill Index',+ writable: true,+ }),+ });++ await expect(service.checkAction(createRefineAction())).resolves.toEqual({ allowed: true });+ });++ /**+ * @example+ * expect(result.reason).toBe('document_changed');+ */+ it('marks changed content as stale', async () => {+ const service = createMaintenanceProposalPreflightService({+ readSkillTarget: async () => ({+ agentDocumentId: 'adoc_1',+ contentHash: 'sha256:current',+ documentId: 'doc_1',+ managed: true,+ targetTitle: 'Skill Index',+ writable: true,+ }),+ });++ await expect(service.checkAction(createRefineAction())).resolves.toEqual({+ allowed: false,+ reason: 'document_changed',+ });+ });++ /**+ * @example+ * expect(result.reason).toBe('target_not_writable');+ */+ it('rejects unmanaged or readonly targets', async () => {+ const service = createMaintenanceProposalPreflightService({+ readSkillTarget: async () => ({+ agentDocumentId: 'adoc_1',+ contentHash: 'sha256:base',+ documentId: 'doc_1',+ managed: false,+ writable: true,+ }),+ });++ await expect(service.checkAction(createRefineAction())).resolves.toEqual({+ allowed: false,+ reason: 'target_not_writable',+ });+ });++ /**+ * @example+ * expect(result.reason).toBe('target_deleted');+ */+ it('rejects missing targets', async () => {+ const service = createMaintenanceProposalPreflightService({+ readSkillTarget: async () => undefined,+ });++ await expect(service.checkAction(createRefineAction())).resolves.toEqual({+ allowed: false,+ reason: 'target_deleted',+ });+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.tsnew file mode 100644index 00000000000..bc5b1e4fbea--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts@@ -0,0 +1,281 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import type { BriefItem } from '@/database/schemas';++import { listServerProposalActivity } from '../serverRuntime';++const baseBrief = (overrides: Partial<BriefItem>): BriefItem => ({+ actions: null,+ agentId: 'agent-1',+ artifacts: null,+ createdAt: new Date('2026-05-09T00:00:00.000Z'),+ cronJobId: null,+ id: 'brief-1',+ metadata: null,+ priority: 'normal',+ readAt: null,+ resolvedAction: null,+ resolvedAt: null,+ resolvedComment: null,+ summary: 'Proposal summary',+ taskId: null,+ title: 'Proposal',+ topicId: null,+ trigger: 'agent-signal:nightly-review',+ type: 'decision',+ userId: 'user-1',+ ...overrides,+});++const proposalMetadata = (+ overrides: Record<string, unknown> = {},+): NonNullable<BriefItem['metadata']> => ({+ proposal: {+ actionType: 'refine_skill',+ actions: [+ {+ actionType: 'refine_skill',+ baseSnapshot: { targetTitle: 'Skill Index' },+ evidenceRefs: [+ { id: 'topic-1', type: 'topic' },+ { id: 'message-1', type: 'message' },+ ],+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ rationale: 'Refine the skill.',+ risk: 'medium',+ target: { skillDocumentId: 'adoc-1' },+ },+ ],+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ evidenceWindowEnd: '2026-05-09T02:00:00.000Z',+ evidenceWindowStart: '2026-05-09T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',+ status: 'pending',+ updatedAt: '2026-05-09T01:00:00.000Z',+ version: 1,+ ...overrides,+ },+});++describe('listServerProposalActivity', () => {+ /**+ * @example+ * listServerProposalActivity skips malformed metadata and maps active proposal targets.+ */+ it('filters invalid metadata and maps active proposal target digests', async () => {+ const digest = await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async () => [+ baseBrief({ id: 'invalid', metadata: { proposal: { status: 'pending' } } }),+ baseBrief({+ agentId: 'other-agent',+ id: 'other-agent',+ metadata: proposalMetadata(),+ }),+ baseBrief({+ id: 'other-trigger',+ metadata: proposalMetadata(),+ trigger: 'other-trigger',+ }),+ baseBrief({ id: 'active', metadata: proposalMetadata() }),+ ],+ },+ userId: 'user-1',+ });++ expect(digest).toMatchObject({+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ });+ expect(digest.active).toEqual([+ {+ actionType: 'refine_skill',+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceCount: 2,+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalId: 'active',+ proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',+ status: 'pending',+ summary: 'Proposal summary',+ targetId: 'adoc-1',+ targetTitle: 'Skill Index',+ updatedAt: '2026-05-09T01:00:00.000Z',+ },+ ]);+ });++ /**+ * @example+ * listServerProposalActivity passes trigger and agent filters to the brief reader.+ */+ it('queries unresolved proposal briefs by trigger and agent before the read cap', async () => {+ const calls: Array<{ agentId: string; limit?: number; trigger: string }> = [];++ await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async (options) => {+ calls.push(options);++ return [];+ },+ },+ userId: 'user-1',+ });++ expect(calls).toEqual([+ {+ agentId: 'agent-1',+ limit: 20,+ trigger: 'agent-signal:nightly-review',+ },+ ]);+ });++ /**+ * @example+ * listServerProposalActivity excludes expired pending proposals from active activity.+ */+ it('counts expired pending proposals as expired instead of active', async () => {+ const digest = await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async () => [+ baseBrief({+ id: 'expired-pending',+ metadata: proposalMetadata({ expiresAt: '2026-05-10T00:00:00.000Z' }),+ }),+ ],+ },+ now: '2026-05-10T00:00:00.000Z',+ userId: 'user-1',+ });++ expect(digest.active).toEqual([]);+ expect(digest.expiredCount).toBe(1);+ });++ /**+ * @example+ * listServerProposalActivity ignores legacy noop proposal metadata.+ */+ it('skips noop proposal metadata from active activity', async () => {+ const digest = await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async () => [+ baseBrief({+ id: 'noop',+ metadata: proposalMetadata({+ actionType: 'noop',+ actions: [+ {+ actionType: 'noop',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'source:noop:quiet',+ rationale: 'No maintenance needed.',+ risk: 'low',+ },+ ],+ proposalKey: 'agent-1:noop:unknown:noop',+ }),+ }),+ ],+ },+ userId: 'user-1',+ });++ expect(digest.active).toEqual([]);+ });++ /**+ * @example+ * listServerProposalActivity keeps unexpired pending proposals in active activity.+ */+ it('keeps future pending proposals active', async () => {+ const digest = await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async () => [+ baseBrief({+ id: 'future-pending',+ metadata: proposalMetadata({ expiresAt: '2026-05-10T00:00:01.000Z' }),+ }),+ ],+ },+ now: '2026-05-10T00:00:00.000Z',+ userId: 'user-1',+ });++ expect(digest.active.map((proposal) => proposal.proposalId)).toEqual(['future-pending']);+ expect(digest.expiredCount).toBe(0);+ });++ /**+ * @example+ * listServerProposalActivity prefers skillDocumentId when a proposal target has multiple ids.+ */+ it('uses proposal key target priority when mapping active proposal target ids', async () => {+ const digest = await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async () => [+ baseBrief({+ id: 'multi-target',+ metadata: proposalMetadata({+ actions: [+ {+ actionType: 'refine_skill',+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],+ idempotencyKey: 'source:refine_skill:skill:adoc-1',+ rationale: 'Refine the skill.',+ risk: 'medium',+ target: {+ memoryId: 'mem-1',+ skillDocumentId: 'adoc-1',+ skillName: 'skill-name',+ },+ },+ ],+ }),+ }),+ ],+ },+ userId: 'user-1',+ });++ expect(digest.active[0]?.targetId).toBe('adoc-1');+ });++ /**+ * @example+ * listServerProposalActivity counts inactive unresolved proposal statuses without listing them as active.+ */+ it('separates active proposals from inactive unresolved proposal status counts', async () => {+ const digest = await listServerProposalActivity({+ agentId: 'agent-1',+ briefModel: {+ listUnresolvedByAgentAndTrigger: async () => [+ baseBrief({ id: 'accepted', metadata: proposalMetadata({ status: 'accepted' }) }),+ baseBrief({ id: 'dismissed', metadata: proposalMetadata({ status: 'dismissed' }) }),+ baseBrief({ id: 'expired', metadata: proposalMetadata({ status: 'expired' }) }),+ baseBrief({ id: 'stale', metadata: proposalMetadata({ status: 'stale' }) }),+ baseBrief({ id: 'superseded', metadata: proposalMetadata({ status: 'superseded' }) }),+ ],+ },+ userId: 'user-1',+ });++ expect(digest.active.map((proposal) => proposal.proposalId)).toEqual(['accepted']);+ expect(digest.dismissedCount).toBe(1);+ expect(digest.expiredCount).toBe(1);+ expect(digest.staleCount).toBe(1);+ expect(digest.supersededCount).toBe(1);+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.tsindex e495a23b669..2c5cffd5fbe 100644--- a/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.ts+++ b/src/server/services/agentSignal/services/maintenance/__tests__/skill.test.ts@@ -18,7 +18,8 @@ describe('skillManagementService', () => {evidenceRefs: [{ id: 'msg-1', type: 'message' }],idempotencyKey: 'source:refine_skill:skill:doc-1',input: {- patch: 'Add checklist step for failed release note validation.',+ bodyMarkdown:+ '# Release notes\n\n- Add checklist step for failed release note validation.',skillDocumentId: 'doc-1',userId: 'user-1',},@@ -28,6 +29,29 @@ describe('skillManagementService', () => {expect(refineSkill).toHaveBeenCalledOnce();});+ /**+ * @example+ * Patch descriptions are not accepted as complete executable skill replacement bodies.+ */+ it('rejects patch-only skill refinements before persistence', async () => {+ const refineSkill = vi.fn();+ const service = createSkillManagementService({ refineSkill });++ await expect(+ service.refineSkill({+ evidenceRefs: [{ id: 'msg-1', type: 'message' }],+ idempotencyKey: 'source:refine_skill:skill:doc-1',+ input: {+ patch: 'Add a checklist step.',+ skillDocumentId: 'doc-1',+ userId: 'user-1',+ },+ }),+ ).rejects.toThrow('Skill refinement requires a complete replacement bodyMarkdown');++ expect(refineSkill).not.toHaveBeenCalled();+ });+/*** @example* Readonly builtin or marketplace skills are not mutated by this service.@@ -41,7 +65,7 @@ describe('skillManagementService', () => {evidenceRefs: [{ id: 'builtin-skill', type: 'agent_document' }],idempotencyKey: 'source:refine_skill:skill:builtin',input: {- patch: 'Change builtin skill.',+ bodyMarkdown: '# Builtin skill\n\nChange builtin skill.',skillDocumentId: 'builtin-skill',targetReadonly: true,userId: 'user-1',diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.tsnew file mode 100644index 00000000000..8e620d472e9--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts@@ -0,0 +1,419 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { spanEnd, spanRecordException, spanSetAttribute, spanSetStatus, startActiveSpan } =+ vi.hoisted(() => {+ interface MockSpan {+ end: ReturnType<typeof vi.fn>;+ recordException: ReturnType<typeof vi.fn>;+ setAttribute: ReturnType<typeof vi.fn>;+ setStatus: ReturnType<typeof vi.fn>;+ }++ const spanSetAttribute = vi.fn();+ const spanSetStatus = vi.fn();+ const spanRecordException = vi.fn();+ const spanEnd = vi.fn();+ const startActiveSpan = vi.fn(+ async (_name: string, _options: unknown, callback: (span: MockSpan) => unknown) => {+ return callback({+ end: spanEnd,+ recordException: spanRecordException,+ setAttribute: spanSetAttribute,+ setStatus: spanSetStatus,+ });+ },+ );++ return { spanEnd, spanRecordException, spanSetAttribute, spanSetStatus, startActiveSpan };+ });++vi.mock('@lobechat/observability-otel/modules/agent-signal', () => ({+ tracer: { startActiveSpan },+}));++describe('createMaintenanceTools', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ /**+ * @example+ * await tools.replaceSkillContentCAS({ baseRevision: 'old' });+ * expect(result.status).toBe('skipped_stale');+ */+ it('replaceSkillContentCAS returns skipped_stale without writing when preflight fails', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const replaceSkill = vi.fn();+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-stale' });+ const tools = createMaintenanceTools({+ preflight: vi.fn().mockResolvedValue({ allowed: false, reason: 'Document changed.' }),+ replaceSkill,+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt,+ });++ const result = await tools.replaceSkillContentCAS({+ bodyMarkdown: 'Updated body',+ idempotencyKey: 'op-replace-1',+ proposalKey: 'proposal-skill-1',+ skillDocumentId: 'skill-1',+ summary: 'Document changed. '.repeat(30),+ userId: 'user-1',+ });++ expect(replaceSkill).not.toHaveBeenCalled();+ expect(result).toEqual({+ receiptId: 'receipt-stale',+ resourceId: 'skill-1',+ status: 'skipped_stale',+ summary: expect.stringMatching(/^Document changed\./),+ });+ expect(result.summary?.length).toBeLessThanOrEqual(240);+ expect(writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ idempotencyKey: 'op-replace-1',+ proposalKey: 'proposal-skill-1',+ status: 'skipped_stale',+ }),+ );+ });++ /**+ * @example+ * await tools.replaceSkillContentCAS({ idempotencyKey: 'same-key' });+ * returns the existing receipt without calling preflight or replaceSkill.+ */+ it('replaceSkillContentCAS dedupes existing reserved idempotency keys', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const preflight = vi.fn();+ const replaceSkill = vi.fn();+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-deduped' });+ const tools = createMaintenanceTools({+ preflight,+ replaceSkill,+ reserveOperation: vi.fn().mockResolvedValue({+ existing: {+ receiptId: 'receipt-existing',+ resourceId: 'skill-1',+ status: 'applied',+ summary: 'Already replaced.',+ },+ reserved: false,+ }),+ writeReceipt,+ });++ const result = await tools.replaceSkillContentCAS({+ bodyMarkdown: 'Updated body',+ idempotencyKey: 'op-replace-1',+ proposalKey: 'proposal-skill-1',+ skillDocumentId: 'skill-1',+ userId: 'user-1',+ });++ expect(preflight).not.toHaveBeenCalled();+ expect(replaceSkill).not.toHaveBeenCalled();+ expect(result).toEqual({+ receiptId: 'receipt-deduped',+ resourceId: 'skill-1',+ status: 'deduped',+ summary: 'Already replaced.',+ });+ expect(writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ idempotencyKey: 'op-replace-1',+ status: 'deduped',+ }),+ );+ });++ /**+ * @example+ * await tools.createMaintenanceProposal({ proposalKey: 'p1' });+ * expect(result.status).toBe('proposed');+ */+ it('createMaintenanceProposal returns proposed and writes a receipt', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const createProposal = vi.fn().mockResolvedValue({+ proposalId: 'proposal-1',+ summary: 'Proposal created.',+ });+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-proposed' });+ const tools = createMaintenanceTools({+ createProposal,+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt,+ });++ const result = await tools.createMaintenanceProposal({+ idempotencyKey: 'op-proposal-1',+ proposalKey: 'proposal-skill-1',+ summary: 'Create proposal.',+ userId: 'user-1',+ });++ expect(createProposal).toHaveBeenCalledWith(+ expect.objectContaining({+ idempotencyKey: 'op-proposal-1',+ proposalKey: 'proposal-skill-1',+ }),+ );+ expect(result).toEqual({+ receiptId: 'receipt-proposed',+ resourceId: 'proposal-1',+ status: 'proposed',+ summary: 'Proposal created.',+ });+ expect(writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ idempotencyKey: 'op-proposal-1',+ proposalKey: 'proposal-skill-1',+ status: 'proposed',+ }),+ );+ expect(startActiveSpan).toHaveBeenCalledWith(+ 'agent_signal.maintenance_tool.write',+ expect.objectContaining({+ attributes: expect.objectContaining({+ 'agent.signal.maintenance_tool.name': 'createMaintenanceProposal',+ 'agent.signal.proposal.key': 'proposal-skill-1',+ }),+ }),+ expect.any(Function),+ );+ expect(spanSetAttribute).toHaveBeenCalledWith(+ 'agent.signal.maintenance_tool.write_status',+ 'proposed',+ );+ expect(spanEnd).toHaveBeenCalled();+ });++ /**+ * @example+ * await tools.createSkillIfAbsent({ idempotencyKey: 'op-create-skill' });+ * expect(result.status).toBe('failed');+ */+ it('createSkillIfAbsent returns failed and writes a failed receipt when mutation throws', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const error = new Error('Skill write failed.');+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-failed' });+ const tools = createMaintenanceTools({+ createSkill: vi.fn().mockRejectedValue(error),+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt,+ });++ const result = await tools.createSkillIfAbsent({+ bodyMarkdown: 'Skill body',+ idempotencyKey: 'op-create-skill-1',+ name: 'skill-name',+ userId: 'user-1',+ });++ expect(result).toEqual({+ receiptId: 'receipt-failed',+ status: 'failed',+ summary: 'Skill write failed.',+ });+ expect(writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ idempotencyKey: 'op-create-skill-1',+ status: 'failed',+ summary: 'Skill write failed.',+ }),+ );+ expect(spanRecordException).toHaveBeenCalledWith(error);+ expect(spanSetStatus).toHaveBeenCalledWith({ code: SpanStatusCode.ERROR });+ expect(spanEnd).toHaveBeenCalled();+ });++ /**+ * @example+ * await tools.createMaintenanceProposal({ idempotencyKey: 'op-receipt-fails' });+ * rejects when the terminal receipt cannot be written.+ */+ it('createMaintenanceProposal propagates receipt failures and records the write span exception', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const error = new Error('Receipt write failed.');+ const markOperationFailed = vi.fn().mockResolvedValue(undefined);+ const tools = createMaintenanceTools({+ createProposal: vi.fn().mockResolvedValue({+ proposalId: 'proposal-1',+ summary: 'Proposal created.',+ }),+ markOperationFailed,+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt: vi.fn().mockRejectedValue(error),+ });++ await expect(+ tools.createMaintenanceProposal({+ idempotencyKey: 'op-receipt-fails-1',+ proposalKey: 'proposal-skill-1',+ userId: 'user-1',+ }),+ ).rejects.toThrow('Receipt write failed.');++ expect(spanRecordException).toHaveBeenCalledWith(error);+ expect(markOperationFailed).toHaveBeenCalledWith(+ expect.objectContaining({+ error,+ idempotencyKey: 'op-receipt-fails-1',+ proposalKey: 'proposal-skill-1',+ resourceId: 'proposal-1',+ status: 'proposed',+ toolName: 'createMaintenanceProposal',+ userId: 'user-1',+ }),+ );+ expect(spanSetStatus).toHaveBeenCalledWith({+ code: SpanStatusCode.ERROR,+ message: 'Receipt write failed.',+ });+ expect(spanEnd).toHaveBeenCalled();+ });++ /**+ * @example+ * await tools.replaceSkillContentCAS({ skillDocumentId: 'skill-1' });+ * returns the known skill id when the adapter only returns a summary.+ */+ it('replaceSkillContentCAS keeps the known resource id when replacement omits it', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-replace' });+ const tools = createMaintenanceTools({+ preflight: vi.fn().mockResolvedValue({ allowed: true }),+ replaceSkill: vi.fn().mockResolvedValue({ summary: 'Skill replaced.' }),+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt,+ });++ const result = await tools.replaceSkillContentCAS({+ bodyMarkdown: 'Updated body',+ idempotencyKey: 'op-replace-success-1',+ proposalKey: 'proposal-skill-1',+ skillDocumentId: 'skill-1',+ userId: 'user-1',+ });++ expect(result).toEqual({+ receiptId: 'receipt-replace',+ resourceId: 'skill-1',+ status: 'applied',+ summary: 'Skill replaced.',+ });+ expect(writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ resourceId: 'skill-1',+ status: 'applied',+ }),+ );+ });++ /**+ * @example+ * await tools.closeMaintenanceProposal({ proposalId: 'proposal-1' });+ * expect(result.status).toBe('skipped_unsupported');+ */+ it('closeMaintenanceProposal skips unsupported when preflight is missing and does not mutate', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const closeProposal = vi.fn();+ const tools = createMaintenanceTools({+ closeProposal,+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt: vi.fn().mockResolvedValue({ receiptId: 'receipt-unsupported' }),+ });++ const result = await tools.closeMaintenanceProposal({+ idempotencyKey: 'op-close-1',+ proposalId: 'proposal-1',+ userId: 'user-1',+ });++ expect(closeProposal).not.toHaveBeenCalled();+ expect(result).toEqual({+ receiptId: 'receipt-unsupported',+ resourceId: 'proposal-1',+ status: 'skipped_unsupported',+ summary: 'Maintenance preflight is not supported.',+ });+ });++ /**+ * @example+ * await tools.readMaintenanceProposal({ proposalId: 'proposal-1' });+ * rejects and records the read exception on the span.+ */+ it('readMaintenanceProposal propagates errors and ends the span with exception details', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const error = new Error('Read failed.');+ const tools = createMaintenanceTools({+ readProposal: vi.fn().mockRejectedValue(error),+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),+ writeReceipt: vi.fn(),+ });++ await expect(+ tools.readMaintenanceProposal({+ proposalId: 'proposal-1',+ proposalKey: 'proposal-key-1',+ userId: 'user-1',+ }),+ ).rejects.toThrow('Read failed.');++ expect(spanRecordException).toHaveBeenCalledWith(error);+ expect(spanSetStatus).toHaveBeenCalledWith({+ code: SpanStatusCode.ERROR,+ message: 'Read failed.',+ });+ expect(spanEnd).toHaveBeenCalled();+ });++ /**+ * @example+ * await tools.refreshMaintenanceProposal({ proposalId: 'proposal-1' });+ * expect(result.status).toBe('proposed');+ */+ it('refreshMaintenanceProposal returns proposed and writes a receipt', async () => {+ const { createMaintenanceTools } = await import('../tools');+ const preflight = vi.fn().mockResolvedValue({ allowed: true });+ const refreshProposal = vi.fn().mockResolvedValue({+ resourceId: 'proposal-1',+ summary: 'Proposal refreshed.',+ });+ const reserveOperation = vi.fn().mockResolvedValue({ reserved: true });+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-refresh' });+ const tools = createMaintenanceTools({+ preflight,+ refreshProposal,+ reserveOperation,+ writeReceipt,+ });++ const result = await tools.refreshMaintenanceProposal({+ idempotencyKey: 'op-refresh-1',+ proposalId: 'proposal-1',+ userId: 'user-1',+ });++ expect(result).toEqual({+ receiptId: 'receipt-refresh',+ resourceId: 'proposal-1',+ status: 'proposed',+ summary: 'Proposal refreshed.',+ });+ expect(writeReceipt).toHaveBeenCalledWith(+ expect.objectContaining({+ idempotencyKey: 'op-refresh-1',+ status: 'proposed',+ }),+ );+ expect(reserveOperation.mock.invocationCallOrder[0]).toBeLessThan(+ preflight.mock.invocationCallOrder[0],+ );+ expect(reserveOperation.mock.invocationCallOrder[0]).toBeLessThan(+ refreshProposal.mock.invocationCallOrder[0],+ );+ });+});diff --git a/src/server/services/agentSignal/services/maintenance/agentRunner.ts b/src/server/services/agentSignal/services/maintenance/agentRunner.tsnew file mode 100644index 00000000000..9ec4ea89904--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/agentRunner.ts@@ -0,0 +1,175 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';++import type { NightlyReviewContext } from './nightlyCollector';+import type { MaintenanceTools } from './tools';+import type { MaintenancePlan, MaintenanceReviewRunResult } from './types';+import { MaintenanceReviewScope, ReviewRunStatus } from './types';++/** Default step budget for one nightly maintenance agent run. */+const DEFAULT_MAX_MAINTENANCE_AGENT_STEPS = 10;++/**+ * Result envelope returned by the bounded maintenance agent runner.+ */+export interface MaintenanceAgentRunResult {+ /** Executed tool or legacy executor result to persist as receipts. */+ execution: MaintenanceReviewRunResult;+ /** Frozen deterministic plan used for Daily Brief proposal projection. */+ projectionPlan: MaintenancePlan;+ /** Optional number of agent/tool steps consumed by the backend runner. */+ stepCount?: number;+}++/**+ * Input passed to a maintenance runner backend.+ */+export interface MaintenanceAgentRunnerRunInput {+ /** Bounded digest context collected for one nightly review window. */+ context: NightlyReviewContext;+ /** User-local nightly date used in projected maintenance plans. */+ localDate?: string;+ /** Maximum backend agent/tool steps allowed for this run. */+ maxSteps: number;+ /** Review scope attached to projected plans and tracing. */+ reviewScope: MaintenanceReviewScope;+ /** Stable source id used to generate action idempotency keys. */+ sourceId: string;+ /** Safe read/write tools available to the backend runner. */+ tools: MaintenanceTools;+ /** Stable user id owning this run. */+ userId: string;+}++/**+ * Options for creating a bounded maintenance agent runner.+ */+export interface MaintenanceAgentRunnerOptions {+ /**+ * Maximum backend agent/tool steps.+ *+ * @default 10+ */+ maxSteps?: number;+ /** Backend implementation that may call tools and must return a projected plan. */+ run: (input: MaintenanceAgentRunnerRunInput) => Promise<MaintenanceAgentRunResult>;+ /** Safe tools exposed to the backend implementation. */+ tools: MaintenanceTools;+}++/**+ * Input for one bounded nightly maintenance run.+ */+export interface MaintenanceAgentRunnerInput {+ /** Bounded digest context collected for one nightly review window. */+ context: NightlyReviewContext;+ /** User-local nightly date used in projected maintenance plans. */+ localDate?: string;+ /** Stable source id used to generate action idempotency keys. */+ sourceId: string;+ /** Stable user id owning this run. */+ userId: string;+}++const createFailedProjectionPlan = (input: MaintenanceAgentRunnerInput): MaintenancePlan => ({+ actions: [],+ localDate: input.localDate,+ plannerVersion: 'maintenance-agent-runner-fallback-v1',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Maintenance review runner failed before producing a valid plan.',+});++/**+ * Creates a bounded runner for nightly maintenance agent execution.+ *+ * Call stack:+ *+ * createNightlyReviewSourceHandler+ * -> {@link createMaintenanceAgentRunner}+ * -> injected `run`+ * -> safe maintenance tools+ *+ * Use when:+ * - Nightly self-review should execute through one bounded runner boundary+ * - Tests need to verify fallback and source-id normalization without DB or LLMs+ *+ * Expects:+ * - `sourceId` is stable for idempotency+ * - The backend `run` returns both execution output and the frozen projection plan+ *+ * Returns:+ * - A runner that traces the run, injects tools, enforces the configured step budget, and+ * returns a conservative failed result if the backend cannot produce a result+ */+export const createMaintenanceAgentRunner = (options: MaintenanceAgentRunnerOptions) => {+ const maxSteps = Math.max(1, options.maxSteps ?? DEFAULT_MAX_MAINTENANCE_AGENT_STEPS);++ return {+ run: async (input: MaintenanceAgentRunnerInput): Promise<MaintenanceAgentRunResult> =>+ tracer.startActiveSpan(+ 'agent_signal.maintenance_agent.runner.run',+ {+ attributes: {+ 'agent.signal.agent_id': input.context.agentId,+ 'agent.signal.maintenance_agent.max_steps': maxSteps,+ 'agent.signal.review_scope': MaintenanceReviewScope.Nightly,+ 'agent.signal.source_id': input.sourceId,+ 'agent.signal.user_id': input.userId,+ },+ },+ async (span) => {+ try {+ const result = await options.run({+ ...input,+ maxSteps,+ reviewScope: MaintenanceReviewScope.Nightly,+ tools: options.tools,+ });+ const execution = {+ ...result.execution,+ sourceId: result.execution.sourceId ?? input.sourceId,+ };++ span.setAttribute(+ 'agent.signal.maintenance_agent.plan_action_count',+ result.projectionPlan.actions.length,+ );+ span.setAttribute(+ 'agent.signal.maintenance_agent.execution_action_count',+ execution.actions.length,+ );+ if (typeof result.stepCount === 'number') {+ span.setAttribute('agent.signal.maintenance_agent.step_count', result.stepCount);+ }+ span.setStatus({ code: SpanStatusCode.OK });++ return {+ ...result,+ execution,+ };+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal maintenance agent runner failed',+ });+ span.recordException(error as Error);++ return {+ execution: {+ actions: [],+ sourceId: input.sourceId,+ status: ReviewRunStatus.Failed,+ },+ projectionPlan: createFailedProjectionPlan(input),+ stepCount: maxSteps,+ };+ } finally {+ span.end();+ }+ },+ ),+ };+};diff --git a/src/server/services/agentSignal/services/maintenance/brief.ts b/src/server/services/agentSignal/services/maintenance/brief.tsindex 799f87779a7..909a7f0a6f1 100644--- a/src/server/services/agentSignal/services/maintenance/brief.ts+++ b/src/server/services/agentSignal/services/maintenance/brief.ts@@ -1,11 +1,24 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';+import { BriefModel } from '@/database/models/brief';-import type { NewBrief } from '@/database/schemas';+import type { BriefItem, NewBrief } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import type { EvidenceRef, MaintenanceReviewRunResult } from './types';+import type { MaintenanceProposalMetadata } from './proposal';+import {+ AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS,+ buildMaintenanceProposalFromPlan,+ getMaintenanceProposalFromBriefMetadata,+ refreshMaintenanceProposal,+ shouldRefreshMaintenanceProposal,+ shouldSupersedeMaintenanceProposal,+ supersedeMaintenanceProposal,+} from './proposal';+import type { EvidenceRef, MaintenancePlan, MaintenanceReviewRunResult } from './types';import { MaintenanceActionStatus, ReviewRunStatus } from './types';-const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';+export const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';interface MaintenanceBriefActionCounts {/** Number of actions applied to durable resources. */@@ -28,6 +41,8 @@ export interface MaintenanceBriefMetadata {localDate: string;/** Coarse user-visible outcome selected by the projection service. */outcome: 'applied' | 'error' | 'proposal';+ /** Frozen maintenance proposal state for approve/dismiss flows. */+ proposal?: MaintenanceProposalMetadata;/** Durable receipt ids linked to this brief. */receiptIds: string[];/** Review source id that produced this brief. */@@ -46,6 +61,19 @@ export type MaintenanceBriefProjection = Omit<NewBrief, 'id' | 'userId'> & {trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;};+const isProposalExpired = (proposal: Pick<MaintenanceProposalMetadata, 'expiresAt'>, now: string) =>+ new Date(proposal.expiresAt).getTime() <= new Date(now).getTime();++const updateBriefProposalMetadata = (+ brief: BriefItem,+ proposal: MaintenanceProposalMetadata,+): BriefItem['metadata'] => ({+ ...(brief.metadata && typeof brief.metadata === 'object' && !Array.isArray(brief.metadata)+ ? (brief.metadata as Record<string, unknown>)+ : {}),+ proposal,+});+/** Input used to project one nightly maintenance result to a Daily Brief payload. */export interface ProjectNightlyReviewBriefInput {/** Agent reviewed by the nightly maintenance run. */@@ -54,6 +82,8 @@ export interface ProjectNightlyReviewBriefInput {evidenceRefs?: EvidenceRef[];/** User-local date reviewed by the nightly run. */localDate: string;+ /** Frozen maintenance plan used to preserve proposal actions. */+ plan?: MaintenancePlan;/** Executor result for the nightly maintenance run. */result: MaintenanceReviewRunResult;/** Review window end ISO timestamp. */@@ -94,20 +124,39 @@ export interface MaintenanceProposalVisibilityInput {trigger?: string | null;}-const countActions = (result: MaintenanceReviewRunResult): MaintenanceBriefActionCounts => {+const getPlanActionByIdempotencyKey = (plan?: MaintenancePlan) =>+ new Map(plan?.actions.map((action) => [action.idempotencyKey, action]));++const isVisibleProposalResult = (+ action: MaintenanceReviewRunResult['actions'][number],+ planActionByIdempotencyKey: Map<+ string,+ MaintenancePlan['actions'][number]+ > = getPlanActionByIdempotencyKey(),+) => {+ if (action.status !== MaintenanceActionStatus.Proposed || !action.receiptId) return false;++ const plannedAction = planActionByIdempotencyKey.get(action.idempotencyKey);++ return plannedAction?.actionType !== 'noop';+};++const countActions = (+ result: MaintenanceReviewRunResult,+ plan?: MaintenancePlan,+): MaintenanceBriefActionCounts => {const counts: MaintenanceBriefActionCounts = {applied: 0,failed: 0,proposed: 0,skipped: 0,};+ const planActionByIdempotencyKey = getPlanActionByIdempotencyKey(plan);for (const action of result.actions) {if (action.status === MaintenanceActionStatus.Applied) counts.applied += 1;if (action.status === MaintenanceActionStatus.Failed) counts.failed += 1;- if (action.status === MaintenanceActionStatus.Proposed && action.receiptId) {- counts.proposed += 1;- }+ if (isVisibleProposalResult(action, planActionByIdempotencyKey)) counts.proposed += 1;if (action.status === MaintenanceActionStatus.Skipped ||action.status === MaintenanceActionStatus.Deduped@@ -139,9 +188,15 @@ const formatActionSummaries = (result: MaintenanceReviewRunResult,status: MaintenanceActionStatus,heading: string,+ plan?: MaintenancePlan,) => {+ const planActionByIdempotencyKey = getPlanActionByIdempotencyKey(plan);const summaries = result.actions- .filter((action) => action.status === status)+ .filter((action) => {+ if (status !== MaintenanceActionStatus.Proposed) return action.status === status;++ return isVisibleProposalResult(action, planActionByIdempotencyKey);+ }).map((action) => action.summary?.trim() ?? '').filter(Boolean);@@ -155,8 +210,9 @@ const createDetailedSummary = (result: MaintenanceReviewRunResult,status: MaintenanceActionStatus,heading: string,+ plan?: MaintenancePlan,) => {- const details = formatActionSummaries(result, status, heading);+ const details = formatActionSummaries(result, status, heading, plan);return details ? `${summary}\n\n${details}` : summary;};@@ -165,13 +221,20 @@ const createBriefCopy = (outcome: MaintenanceBriefMetadata['outcome'],counts: MaintenanceBriefActionCounts,result: MaintenanceReviewRunResult,+ plan?: MaintenancePlan,) => {if (outcome === 'proposal') {const summary = `${counts.proposed} maintenance proposal${counts.proposed === 1 ? '' : 's'} need review.`;return {priority: 'normal' as const,- summary: createDetailedSummary(summary, result, MaintenanceActionStatus.Proposed, 'Proposal'),+ summary: createDetailedSummary(+ summary,+ result,+ MaintenanceActionStatus.Proposed,+ 'Proposal',+ plan,+ ),title: 'Agent self-review proposal',type: 'decision' as const,};@@ -269,20 +332,33 @@ export const createBriefMaintenanceService = () => ({projectNightlyReviewBrief: (input: ProjectNightlyReviewBriefInput,): MaintenanceBriefProjection | undefined => {- const actionCounts = countActions(input.result);+ const actionCounts = countActions(input.result, input.plan);const outcome = getOutcome(input.result, actionCounts);if (!outcome) return;- const copy = createBriefCopy(outcome, actionCounts, input.result);+ const copy = createBriefCopy(outcome, actionCounts, input.result, input.plan);+ const proposal =+ outcome === 'proposal' && input.plan+ ? buildMaintenanceProposalFromPlan({+ agentId: input.agentId,+ evidenceWindowEnd: input.reviewWindowEnd,+ evidenceWindowStart: input.reviewWindowStart,+ now: input.reviewWindowEnd,+ plan: input.plan,+ results: input.result.actions,+ })+ : undefined;return {+ ...(proposal ? { actions: AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS } : {}),agentId: input.agentId,metadata: {actionCounts,evidenceRefs: input.evidenceRefs ?? [],localDate: input.localDate,outcome,+ ...(proposal ? { proposal } : {}),receiptIds: getReceiptIds(input.result),...(input.result.sourceId ? { sourceId: input.result.sourceId } : {}),timezone: input.timezone,@@ -309,12 +385,162 @@ export const createBriefMaintenanceService = () => ({* - `db` and `userId` belong to the source-event owner** Returns:- * - A writer whose `writeDailyBrief` method calls `BriefModel.create`+ * - A writer whose `writeDailyBrief` method creates or refreshes proposal briefs*/export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId: string) => {const model = new BriefModel(db, userId);return {- writeDailyBrief: (brief: MaintenanceBriefProjection) => model.create(brief),+ writeDailyBrief: (brief: MaintenanceBriefProjection) =>+ tracer.startActiveSpan(+ 'agent_signal.maintenance_brief.write',+ {+ attributes: {+ 'agent.signal.agent_id': brief.agentId ?? '',+ 'agent.signal.brief.trigger': brief.trigger,+ 'agent.signal.user_id': userId,+ ...(brief.metadata.proposal+ ? {+ 'agent.signal.proposal.action_count': brief.metadata.proposal.actions.length,+ 'agent.signal.proposal.key': brief.metadata.proposal.proposalKey,+ }+ : {}),+ },+ },+ async (span) => {+ try {+ const incomingProposal = brief.metadata.proposal;+ if (!incomingProposal || !brief.agentId) return model.create(brief);++ const now = incomingProposal.updatedAt;+ const rows = await model.listUnresolvedByAgentAndTrigger({+ agentId: brief.agentId,+ limit: 20,+ trigger: brief.trigger,+ });+ const existingBrief = rows.find((row) => {+ const proposal = getMaintenanceProposalFromBriefMetadata(row.metadata);++ return (+ proposal?.proposalKey === incomingProposal.proposalKey &&+ (proposal.status === 'pending' ||+ proposal.status === 'expired' ||+ proposal.status === 'stale')+ );+ });++ if (!existingBrief) return model.create(brief);++ const existingProposal = getMaintenanceProposalFromBriefMetadata(+ existingBrief.metadata,+ );+ if (!existingProposal) return model.create(brief);++ if (existingProposal.status === 'pending' && isProposalExpired(existingProposal, now)) {+ const expiredProposal: MaintenanceProposalMetadata = {+ ...existingProposal,+ status: 'expired',+ updatedAt: now,+ };+ await model.updateMetadata(+ existingBrief.id,+ updateBriefProposalMetadata(existingBrief, expiredProposal),+ );+ span.setAttribute('agent.signal.proposal.status', 'expired');++ return model.create(brief);+ }++ const refresh = shouldRefreshMaintenanceProposal({+ existing: existingProposal,+ incoming: incomingProposal,+ now,+ });+ if (+ refresh.refresh &&+ shouldSupersedeMaintenanceProposal({+ existing: existingProposal,+ incoming: incomingProposal,+ now,+ }).supersede === false+ ) {+ const refreshedProposal = refreshMaintenanceProposal({+ existing: existingProposal,+ incoming: incomingProposal,+ now,+ });+ span.setAttribute('agent.signal.proposal.status', 'refreshed');++ return tracer.startActiveSpan(+ 'agent_signal.maintenance_proposal.refresh',+ {+ attributes: {+ 'agent.signal.proposal.key': refreshedProposal.proposalKey,+ 'agent.signal.proposal.status': refreshedProposal.status,+ },+ },+ async (refreshSpan) => {+ try {+ const updatedBrief = await model.updateMetadata(+ existingBrief.id,+ updateBriefProposalMetadata(existingBrief, refreshedProposal),+ );++ return updatedBrief ?? model.create(brief);+ } finally {+ refreshSpan.end();+ }+ },+ );+ }++ const supersede = shouldSupersedeMaintenanceProposal({+ existing: existingProposal,+ incoming: incomingProposal,+ now,+ });+ if (supersede.supersede) {+ const supersededProposal = supersedeMaintenanceProposal({+ existing: existingProposal,+ now,+ supersededBy: incomingProposal.proposalKey,+ });+ await tracer.startActiveSpan(+ 'agent_signal.maintenance_proposal.supersede',+ {+ attributes: {+ 'agent.signal.proposal.key': supersededProposal.proposalKey,+ 'agent.signal.proposal.status': supersededProposal.status,+ },+ },+ async (supersedeSpan) => {+ try {+ await model.updateMetadata(+ existingBrief.id,+ updateBriefProposalMetadata(existingBrief, supersededProposal),+ );+ } finally {+ supersedeSpan.end();+ }+ },+ );+ span.setAttribute('agent.signal.proposal.status', 'superseded');++ return model.create(brief);+ }++ return model.create(brief);+ } catch (error) {+ span.recordException(error as Error);+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ throw error;+ } finally {+ span.end();+ }+ },+ ),};};diff --git a/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts b/src/server/services/agentSignal/services/maintenance/nightlyCollector.tsindex 43488c779f2..2c649baa11e 100644--- a/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts+++ b/src/server/services/agentSignal/services/maintenance/nightlyCollector.ts@@ -2,7 +2,8 @@ import { SpanStatusCode } from '@lobechat/observability-otel/api';import { tracer } from '@lobechat/observability-otel/modules/agent-signal';import { deriveNightlyMaintenanceSignals } from './nightlySignals';-import type { EvidenceRef } from './types';+import type { MaintenanceProposalStatus } from './proposal';+import type { EvidenceRef, MaintenanceActionType } from './types';const DEFAULT_MAX_TOPICS = 30;const DEFAULT_MAX_MANAGED_SKILLS = 20;@@ -311,6 +312,48 @@ export interface ReceiptActivityDigest {reviewCount: number;}+/** Bounded unresolved proposal visible to nightly review. */+export interface MaintenanceProposalDigest {+ /** Dominant action type represented by this proposal. */+ actionType: MaintenanceActionType;+ /** Last known conflict reason when the proposal became stale or blocked. */+ conflictReason?: string;+ /** Proposal creation ISO timestamp. */+ createdAt: string;+ /** Number of bounded evidence refs attached to the proposal. */+ evidenceCount: number;+ /** Proposal expiry ISO timestamp. */+ expiresAt: string;+ /** Daily Brief id or durable proposal id. */+ proposalId: string;+ /** Stable one-pending-proposal key for this action target. */+ proposalKey: string;+ /** Current lifecycle status. */+ status: MaintenanceProposalStatus;+ /** Short proposal summary safe to inject into reviewer context. */+ summary: string;+ /** Target id when available. */+ targetId?: string;+ /** Human-readable target title when available. */+ targetTitle?: string;+ /** Last proposal update ISO timestamp. */+ updatedAt: string;+}++/** Existing unresolved proposal row activity summarized for nightly review. */+export interface ProposalActivityDigest {+ /** Active proposals that may be refreshed, superseded, or kept pending. */+ active: MaintenanceProposalDigest[];+ /** Count of unresolved proposal rows whose metadata is already dismissed. */+ dismissedCount: number;+ /** Count of unresolved proposal rows whose metadata is expired or whose pending expiry passed. */+ expiredCount: number;+ /** Count of unresolved proposal rows whose metadata is stale. */+ staleCount: number;+ /** Count of unresolved proposal rows whose metadata is superseded. */+ supersededCount: number;+}+/** Nightly maintenance signal shown to the reviewer before raw buckets. */export interface MaintenanceSignal {/** Evidence refs that justify the signal. */@@ -325,6 +368,7 @@ export interface MaintenanceSignal {/** Initial nightly maintenance signal categories. */export type MaintenanceSignalKind =+ | 'durable_user_preference'| 'frequent_tool_workflow'| 'hinted_skill_document_changed'| 'pending_related_proposal_exists'@@ -360,6 +404,13 @@ export type MaintenanceSignalFeature =topicCount: number;totalCount: number;type: 'tool_usage';+ }+ | {+ correctionCount: number;+ hasCorrection: boolean;+ messageCount: number;+ topicId?: string;+ type: 'topic_signal';};/** Normalized topic digest emitted in nightly review context. */@@ -383,6 +434,8 @@ export interface NightlyReviewReadAdapters {listFeedbackActivity?: (input: NightlyReviewReadInput) => Promise<FeedbackActivityDigest>;/** Lists managed skill summaries for this agent and review window. */listManagedSkills: (input: ListManagedSkillsInput) => Promise<NightlyReviewManagedSkillSummary[]>;+ /** Lists existing maintenance proposal activity for this agent. */+ listProposalActivity?: (input: NightlyReviewReadInput) => Promise<ProposalActivityDigest>;/** Lists recent receipt activity relevant to this review window. */listReceiptActivity?: (input: NightlyReviewReadInput) => Promise<ReceiptActivityDigest>;/** Lists relevant memory summaries for this agent and review window. */@@ -443,6 +496,8 @@ export interface NightlyReviewContext {maintenanceSignals: MaintenanceSignal[];/** Managed skills relevant to the agent. */managedSkills: NightlyReviewManagedSkillSummary[];+ /** Existing maintenance proposals used to refresh or supersede pending decisions. */+ proposalActivity: ProposalActivityDigest;/** Recent receipt history used to avoid duplicate proposals. */receiptActivity: ReceiptActivityDigest;/** Memories relevant to the review window and agent. */@@ -651,6 +706,14 @@ const createEmptyReceiptActivity = (): ReceiptActivityDigest => ({reviewCount: 0,});+const createEmptyProposalActivity = (): ProposalActivityDigest => ({+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+});+/*** Creates a pure nightly review collector service from digest read adapters.*@@ -703,6 +766,7 @@ export const createNightlyReviewService = (documentActivity,feedbackActivity,receiptActivity,+ proposalActivity,] = await Promise.all([readAdapters.listTopicActivity({...readInput,@@ -723,6 +787,8 @@ export const createNightlyReviewService = (Promise.resolve(createEmptyFeedbackActivity()),readAdapters.listReceiptActivity?.(readInput) ??Promise.resolve(createEmptyReceiptActivity()),+ readAdapters.listProposalActivity?.(readInput) ??+ Promise.resolve(createEmptyProposalActivity()),]);const topics = topicRows.map(normalizeTopic).sort(compareTopics).slice(0, maxTopics);const maintenanceSignals = deriveNightlyMaintenanceSignals({@@ -730,6 +796,7 @@ export const createNightlyReviewService = (feedbackActivity,receiptActivity,toolActivity,+ topics,});span.setAttribute('agent.signal.nightly.raw_topic_count', topicRows.length);@@ -761,6 +828,26 @@ export const createNightlyReviewService = ('agent.signal.nightly.receipt_pending_proposal_count',receiptActivity.pendingProposalCount,);+ span.setAttribute(+ 'agent.signal.nightly.proposal_active_count',+ proposalActivity.active.length,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_expired_count',+ proposalActivity.expiredCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_dismissed_count',+ proposalActivity.dismissedCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_stale_count',+ proposalActivity.staleCount,+ );+ span.setAttribute(+ 'agent.signal.nightly.proposal_superseded_count',+ proposalActivity.supersededCount,+ );span.setAttribute('agent.signal.nightly.maintenance_signal_count',maintenanceSignals.length,@@ -779,6 +866,7 @@ export const createNightlyReviewService = (feedbackActivity,maintenanceSignals,managedSkills: managedSkills.slice(0, maxManagedSkills),+ proposalActivity,receiptActivity,relevantMemories: relevantMemories.slice(0, maxRelevantMemories),toolActivity,diff --git a/src/server/services/agentSignal/services/maintenance/nightlyDocumentActivity.ts b/src/server/services/agentSignal/services/maintenance/nightlyDocumentActivity.tsindex a1249aeb1d7..ef831a3f5cc 100644--- a/src/server/services/agentSignal/services/maintenance/nightlyDocumentActivity.ts+++ b/src/server/services/agentSignal/services/maintenance/nightlyDocumentActivity.ts@@ -43,7 +43,11 @@ export const mapNightlyDocumentActivityRows = (continue;}- if (row.templateId === 'skills/index' || row.templateId === 'skills/bundle') {+ if (+ row.templateId === 'agent-skill' ||+ row.templateId === 'skills/index' ||+ row.templateId === 'skills/bundle'+ ) {digest.skillBucket.push({...base,hintIsSkill: false,diff --git a/src/server/services/agentSignal/services/maintenance/nightlySignals.ts b/src/server/services/agentSignal/services/maintenance/nightlySignals.tsindex 0bec88b89ba..d6fb8099efe 100644--- a/src/server/services/agentSignal/services/maintenance/nightlySignals.ts+++ b/src/server/services/agentSignal/services/maintenance/nightlySignals.ts@@ -2,6 +2,7 @@ import type {DocumentActivityDigest,FeedbackActivityDigest,MaintenanceSignal,+ NightlyReviewTopicDigest,ReceiptActivityDigest,ToolActivityDigest,} from './nightlyCollector';@@ -12,6 +13,7 @@ interface DeriveNightlyMaintenanceSignalsInput {feedbackActivity: FeedbackActivityDigest;receiptActivity: ReceiptActivityDigest;toolActivity: ToolActivityDigest[];+ topics?: NightlyReviewTopicDigest[];}const pushUniqueRef = (refs: EvidenceRef[], ref: EvidenceRef) => {@@ -47,6 +49,26 @@ export const deriveNightlyMaintenanceSignals = (const signals: MaintenanceSignal[] = [];const feedbackFeatures = createFeedbackFeatures(input.feedbackActivity);+ for (const topic of input.topics ?? []) {+ if (!topic.highSignalReasons.includes('correction')) continue;++ signals.push({+ evidenceRefs: topic.evidenceRefs.slice(0, 5),+ features: [+ {+ correctionCount: topic.correctionCount ?? (topic.hasCorrection ? 1 : 0),+ hasCorrection: Boolean(topic.hasCorrection),+ messageCount: topic.messageCount ?? 0,+ ...((topic.topicId ?? topic.id) ? { topicId: topic.topicId ?? topic.id } : {}),+ type: 'topic_signal',+ },+ ...feedbackFeatures,+ ],+ kind: 'durable_user_preference',+ strength: 'strong',+ });+ }+for (const tool of input.toolActivity) {const topicCount = new Set(tool.topicIds).size;const toolFeature = {diff --git a/src/server/services/agentSignal/services/maintenance/planner.ts b/src/server/services/agentSignal/services/maintenance/planner.tsindex b98b3ecd650..0855b89da90 100644--- a/src/server/services/agentSignal/services/maintenance/planner.ts+++ b/src/server/services/agentSignal/services/maintenance/planner.ts@@ -122,16 +122,14 @@ const createOperation = (if (draft.actionType === 'refine_skill') {const skillDocumentId =getStringField(draft.value, 'skillDocumentId') ?? draft.target?.skillDocumentId;+ const bodyMarkdown = getStringField(draft.value, 'bodyMarkdown');- if (!skillDocumentId) return undefined;+ if (!skillDocumentId || !bodyMarkdown) return undefined;return {domain: 'skill',input: {- patch:- getStringField(draft.value, 'patch') ??- getStringField(draft.value, 'bodyMarkdown') ??- getStringField(draft.value, 'content'),+ bodyMarkdown,targetReadonly: getTargetReadonly(draft),skillDocumentId,userId: request.userId,@@ -185,10 +183,15 @@ const classifyMemoryPlan = (return { applyMode: MaintenanceApplyMode.AutoApply, risk: MaintenanceRisk.Low };};-const isStrongSmallSkillDraft = (draft: MaintenanceActionDraft) =>+const isBroadInPlaceRefineDraft = (draft: MaintenanceActionDraft) =>+ draft.actionType === 'refine_skill' &&+ draft.policyHints?.mutationScope === 'broad' &&+ Boolean(draft.target?.skillDocumentId);++const isStrongAutoApplySkillDraft = (draft: MaintenanceActionDraft) =>draft.confidence >= SKILL_AUTO_APPLY_CONFIDENCE_THRESHOLD &&draft.policyHints?.evidenceStrength === 'strong' &&- draft.policyHints?.mutationScope === 'small';+ (draft.policyHints?.mutationScope === 'small' || isBroadInPlaceRefineDraft(draft));const hasAutoApplySkillIntent = (draft: MaintenanceActionDraft) =>draft.policyHints?.userExplicitness === 'explicit' ||@@ -208,7 +211,7 @@ const classifySkillPlan = (return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.High };}- if (!isStrongSmallSkillDraft(draft) || !hasAutoApplySkillIntent(draft)) {+ if (!isStrongAutoApplySkillDraft(draft) || !hasAutoApplySkillIntent(draft)) {return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };}@@ -230,14 +233,18 @@ const classifyInitialPlan = (draft: MaintenanceActionDraft,reviewScope: MaintenanceReviewScope,): Pick<MaintenanceActionPlan, 'applyMode' | 'risk'> => {- if (draft.evidenceRefs.length === 0 || draft.confidence < LOW_RISK_CONFIDENCE_THRESHOLD) {- return { applyMode: MaintenanceApplyMode.Skip, risk: MaintenanceRisk.High };+ if (draft.actionType === 'noop') {+ return { applyMode: MaintenanceApplyMode.Skip, risk: MaintenanceRisk.Low };}- if (draft.actionType === 'noop' || draft.actionType === 'proposal_only') {+ if (draft.actionType === 'proposal_only') {return { applyMode: MaintenanceApplyMode.ProposalOnly, risk: MaintenanceRisk.Medium };}+ if (draft.evidenceRefs.length === 0 || draft.confidence < LOW_RISK_CONFIDENCE_THRESHOLD) {+ return { applyMode: MaintenanceApplyMode.Skip, risk: MaintenanceRisk.High };+ }+if (draft.actionType === 'write_memory') {return classifyMemoryPlan(draft);}diff --git a/src/server/services/agentSignal/services/maintenance/proposal.ts b/src/server/services/agentSignal/services/maintenance/proposal.tsnew file mode 100644index 00000000000..c91adc0cd3a--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/proposal.ts@@ -0,0 +1,610 @@+import type { BriefAction } from '@lobechat/types';++import type {+ EvidenceRef,+ MaintenanceActionPlan,+ MaintenanceActionResult,+ MaintenanceActionTarget,+ MaintenanceActionType,+ MaintenancePlan,+} from './types';+import { MaintenanceActionStatus, MaintenanceRisk } from './types';++export const MAINTENANCE_PROPOSAL_VERSION = 1;++export type MaintenanceProposalStatus =+ | 'pending'+ | 'accepted'+ | 'applying'+ | 'applied'+ | 'partially_failed'+ | 'failed'+ | 'dismissed'+ | 'expired'+ | 'stale'+ | 'superseded';++const MAINTENANCE_ACTION_TYPES = [+ 'write_memory',+ 'create_skill',+ 'refine_skill',+ 'consolidate_skill',+ 'noop',+ 'proposal_only',+] as const satisfies MaintenanceActionType[];++const MAINTENANCE_PROPOSAL_STATUSES = [+ 'pending',+ 'accepted',+ 'applying',+ 'applied',+ 'partially_failed',+ 'failed',+ 'dismissed',+ 'expired',+ 'stale',+ 'superseded',+] as const satisfies MaintenanceProposalStatus[];++const MAINTENANCE_RISKS = [+ MaintenanceRisk.High,+ MaintenanceRisk.Low,+ MaintenanceRisk.Medium,+] as const satisfies MaintenanceRisk[];++export type MaintenanceProposalConflictReason =+ | 'agent_gate_disabled'+ | 'document_changed'+ | 'target_deleted'+ | 'target_not_writable'+ | 'target_type_changed'+ | 'user_gate_disabled'+ | 'server_gate_disabled';++export interface BuildMaintenanceProposalKeyInput {+ /** Action category represented by the proposal. */+ actionType: MaintenanceActionType;+ /** Agent whose self-review produced the proposal. */+ agentId: string;+ /** 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';+}++export interface MaintenanceProposalBaseSnapshot {+ /** Agent document id when the proposal targets managed skill/document state. */+ agentDocumentId?: string;+ /** Content hash observed when the proposal was created. */+ contentHash?: string;+ /** Canonical document id observed when the proposal was created. */+ documentId?: string;+ /** Last document update timestamp observed when the proposal was created. */+ documentUpdatedAt?: string;+ /** Whether the target was managed by Agent Signal. */+ managed?: boolean;+ /** Human-readable target title observed at proposal time. */+ targetTitle?: string;+ /** Whether the target was writable at proposal time. */+ writable?: boolean;+}++export interface MaintenanceProposalAction {+ /** Planned action type frozen into the proposal. */+ actionType: MaintenanceActionType;+ /** Optional target freshness snapshot used by approve-time preflight. */+ baseSnapshot?: MaintenanceProposalBaseSnapshot;+ /** Bounded evidence references retained for audit and prompt context. */+ evidenceRefs: EvidenceRef[];+ /** Stable operation idempotency key from the original maintenance plan. */+ idempotencyKey: string;+ /** Frozen domain operation to apply after user approval when still fresh. */+ operation?: MaintenanceActionPlan['operation'];+ /** Reviewer rationale shown to users and future maintenance runs. */+ rationale: string;+ /** Risk assigned by the maintenance planner. */+ risk: MaintenanceRisk;+ /** Bounded target identity from the original plan. */+ target?: MaintenanceActionTarget;+}++export interface MaintenanceProposalActionApplyResult {+ /** Frozen action idempotency key this apply result belongs to. */+ idempotencyKey: string;+ /** Resource id touched by the action when one exists. */+ resourceId?: string;+ /** Apply status emitted by the approve-time merge path. */+ status: 'applied' | 'deduped' | 'failed' | 'skipped_stale' | 'skipped_unsupported';+ /** Short user-visible result summary. */+ summary?: string;+}++export interface MaintenanceProposalApplyAttempt {+ /** Per-action results in proposal action order. */+ actionResults: MaintenanceProposalActionApplyResult[];+ /** ISO timestamp for this apply attempt. */+ appliedAt: string;+ /** Aggregate apply attempt status. */+ status: 'applied' | 'failed' | 'partially_failed' | 'stale';+}++export interface MaintenanceProposalMetadata {+ /** Frozen proposal actions. */+ actions: MaintenanceProposalAction[];+ /** Dominant action type used for digest grouping and refresh checks. */+ actionType: MaintenanceActionType;+ /** Historical approve/apply attempts for this proposal. */+ applyAttempts?: MaintenanceProposalApplyAttempt[];+ /** Conflict reason when the proposal cannot be applied as-is. */+ conflictReason?: MaintenanceProposalConflictReason;+ /** ISO timestamp when the proposal was first created. */+ createdAt: string;+ /** Bounded evidence retained at proposal level. */+ evidenceRefs?: EvidenceRef[];+ /** Review evidence window end ISO timestamp. */+ evidenceWindowEnd: string;+ /** Review evidence window start ISO timestamp. */+ evidenceWindowStart: string;+ /** ISO timestamp after which the pending proposal should be ignored or expired. */+ expiresAt: string;+ /** Stable one-pending-proposal key for this target/action pair. */+ proposalKey: string;+ /** Current proposal lifecycle state. */+ status: MaintenanceProposalStatus;+ /** Proposal key or brief id that superseded this proposal. */+ supersededBy?: string;+ /** ISO timestamp for the last proposal lifecycle update. */+ updatedAt: string;+ /** Metadata schema version. */+ version: typeof MAINTENANCE_PROPOSAL_VERSION;+}++export interface MaintenanceProposalBriefMetadata {+ /** Agent Signal maintenance proposal metadata stored inside Daily Brief metadata. */+ proposal?: MaintenanceProposalMetadata;+}++export const AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS = [+ { key: 'approve', label: 'Apply', type: 'resolve' },+ { key: 'dismiss', label: 'Dismiss', type: 'resolve' },+ { key: 'feedback', label: 'Request changes', type: 'comment' },+] satisfies BriefAction[];++const isEvidenceRefArray = (value: unknown): value is EvidenceRef[] =>+ Array.isArray(value) &&+ value.every((item) => {+ if (!item || typeof item !== 'object') return false;++ const evidenceRef = item as Record<string, unknown>;++ return typeof evidenceRef.id === 'string' && typeof evidenceRef.type === 'string';+ });++const isKnownStringValue = <TValue extends string>(+ value: unknown,+ allowedValues: readonly TValue[],+): value is TValue => typeof value === 'string' && allowedValues.includes(value as TValue);++const isMaintenanceProposalAction = (value: unknown): value is MaintenanceProposalAction => {+ if (!value || typeof value !== 'object') return false;++ const action = value as Record<string, unknown>;++ return (+ isKnownStringValue(action.actionType, MAINTENANCE_ACTION_TYPES) &&+ isEvidenceRefArray(action.evidenceRefs) &&+ typeof action.idempotencyKey === 'string' &&+ typeof action.rationale === 'string' &&+ isKnownStringValue(action.risk, MAINTENANCE_RISKS)+ );+};++/**+ * Builds the stable proposal key for one target/action pair.+ *+ * Use when:+ * - A nightly review creates or refreshes a pending proposal+ * - Proposal digest logic needs to group compatible incoming changes+ *+ * Expects:+ * - `targetId` is stable inside `targetType`+ * - Callers choose the most specific target type available+ *+ * Returns:+ * - A colon-delimited key stable across retries for the same proposal target+ */+export const buildMaintenanceProposalKey = ({+ actionType,+ agentId,+ targetId,+ targetType,+}: BuildMaintenanceProposalKeyInput) => [agentId, actionType, targetType, targetId].join(':');++/**+ * Calculates the next expiry for a pending proposal.+ *+ * Use when:+ * - A nightly review creates a proposal+ * - A compatible pending proposal is refreshed by new evidence+ *+ * Expects:+ * - `createdAt` and `now` are valid ISO timestamps+ *+ * Returns:+ * - `now + 72h`, capped at `createdAt + 7d`+ */+export const getNextProposalExpiry = ({ createdAt, now }: { createdAt: string; now: string }) => {+ const nowMs = new Date(now).getTime();+ const createdMs = new Date(createdAt).getTime();+ const slidingMs = nowMs + 72 * 60 * 60 * 1000;+ const hardCapMs = createdMs + 7 * 24 * 60 * 60 * 1000;++ return new Date(Math.min(slidingMs, hardCapMs)).toISOString();+};++/**+ * Checks whether unknown Daily Brief metadata contains proposal metadata.+ *+ * Use when:+ * - Brief feeds need to distinguish Agent Signal proposal briefs+ * - Apply/dismiss paths load serialized metadata from storage+ *+ * Expects:+ * - The value may be arbitrary JSON-like data+ *+ * Returns:+ * - `true` only when required proposal metadata fields are present+ */+export const isMaintenanceProposalMetadata = (+ value: unknown,+): value is MaintenanceProposalMetadata => {+ if (!value || typeof value !== 'object') return false;++ const payload = value as Record<string, unknown>;++ return (+ payload.version === MAINTENANCE_PROPOSAL_VERSION &&+ isKnownStringValue(payload.actionType, MAINTENANCE_ACTION_TYPES) &&+ typeof payload.proposalKey === 'string' &&+ isKnownStringValue(payload.status, MAINTENANCE_PROPOSAL_STATUSES) &&+ typeof payload.createdAt === 'string' &&+ typeof payload.updatedAt === 'string' &&+ typeof payload.expiresAt === 'string' &&+ typeof payload.evidenceWindowStart === 'string' &&+ typeof payload.evidenceWindowEnd === 'string' &&+ (payload.evidenceRefs === undefined || isEvidenceRefArray(payload.evidenceRefs)) &&+ Array.isArray(payload.actions) &&+ payload.actions.every(isMaintenanceProposalAction)+ );+};++/**+ * Reads proposal metadata from a Daily Brief metadata object.+ *+ * Use when:+ * - Brief approve/dismiss paths need the stored maintenance proposal+ * - Proposal digest collectors inspect unresolved Agent Signal briefs+ *+ * Expects:+ * - `metadata` may be arbitrary persisted JSON+ *+ * Returns:+ * - Parsed proposal metadata when present, otherwise `undefined`+ */+export const getMaintenanceProposalFromBriefMetadata = (+ metadata: unknown,+): MaintenanceProposalMetadata | undefined => {+ if (!metadata || typeof metadata !== 'object') return;++ const proposal = (metadata as MaintenanceProposalBriefMetadata).proposal;++ return isMaintenanceProposalMetadata(proposal) ? proposal : undefined;+};++const getProposalTarget = (+ action: MaintenanceActionPlan,+): Pick<BuildMaintenanceProposalKeyInput, 'targetId' | 'targetType'> => {+ if (action.target?.skillDocumentId) {+ return { targetId: action.target.skillDocumentId, targetType: 'agent_document' };+ }+ if (action.target?.memoryId) return { targetId: action.target.memoryId, targetType: 'memory' };+ if (action.target?.skillName) return { targetId: action.target.skillName, targetType: 'skill' };++ return { targetId: action.dedupeKey, targetType: 'unknown' };+};++const getOperationTargetTitle = (action: MaintenanceActionPlan) => {+ if (action.operation?.domain !== 'skill') return;++ const { input } = action.operation;++ if ('title' in input && input.title) return input.title;+ if ('name' in input && input.name) return input.name;+};++const getProposalBaseSnapshot = (+ action: MaintenanceActionPlan,+): MaintenanceProposalBaseSnapshot | undefined => {+ const targetTitle = getOperationTargetTitle(action) ?? action.target?.skillName;++ return targetTitle ? { targetTitle } : undefined;+};++export interface BuildMaintenanceProposalFromPlanInput {+ /** Agent whose nightly review produced the proposal. */+ agentId: string;+ /** Evidence window end ISO timestamp. */+ evidenceWindowEnd: string;+ /** Evidence window start ISO timestamp. */+ evidenceWindowStart: string;+ /** Stable timestamp to use for created/updated proposal metadata. */+ now: string;+ /** Frozen maintenance plan generated before execution. */+ plan: MaintenancePlan;+ /** Execution results that identify which actions stayed proposed. */+ results: MaintenanceActionResult[];+}++/**+ * Builds proposal metadata from a maintenance plan and execution results.+ *+ * Use when:+ * - A nightly review projected a user-visible proposal Daily Brief+ * - Approve-time application needs frozen actions instead of rerunning review+ *+ * Expects:+ * - `results` uses the same idempotency keys as `plan.actions`+ * - Only `proposed` execution results should become frozen proposal actions+ *+ * Returns:+ * - Proposal metadata for the first proposed target/action group, or `undefined`+ */+export const buildMaintenanceProposalFromPlan = ({+ agentId,+ evidenceWindowEnd,+ evidenceWindowStart,+ now,+ plan,+ results,+}: BuildMaintenanceProposalFromPlanInput): MaintenanceProposalMetadata | undefined => {+ const proposedResultKeys = new Set(+ results+ .filter((result) => result.status === MaintenanceActionStatus.Proposed)+ .map((result) => result.idempotencyKey),+ );+ const proposedActions = plan.actions.filter(+ (action) => action.actionType !== 'noop' && proposedResultKeys.has(action.idempotencyKey),+ );++ if (proposedActions.length === 0) return;++ const [firstAction] = proposedActions;+ const target = getProposalTarget(firstAction);+ const proposalKey = buildMaintenanceProposalKey({+ actionType: firstAction.actionType,+ agentId,+ targetId: target.targetId,+ targetType: target.targetType,+ });+ const evidenceRefs = new Map<string, EvidenceRef>();++ for (const action of proposedActions) {+ for (const evidenceRef of action.evidenceRefs) {+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);+ }+ }++ return {+ actionType: firstAction.actionType,+ actions: proposedActions.map((action) => {+ const baseSnapshot = getProposalBaseSnapshot(action);++ return {+ actionType: action.actionType,+ ...(baseSnapshot ? { baseSnapshot } : {}),+ evidenceRefs: action.evidenceRefs,+ idempotencyKey: action.idempotencyKey,+ ...(action.operation ? { operation: action.operation } : {}),+ rationale: action.rationale,+ risk: action.risk,+ ...(action.target ? { target: action.target } : {}),+ };+ }),+ createdAt: now,+ evidenceRefs: [...evidenceRefs.values()],+ evidenceWindowEnd,+ evidenceWindowStart,+ expiresAt: getNextProposalExpiry({ createdAt: now, now }),+ proposalKey,+ status: 'pending',+ updatedAt: now,+ version: MAINTENANCE_PROPOSAL_VERSION,+ };+};++/**+ * Decides whether a compatible incoming proposal should refresh an existing one.+ *+ * Use when:+ * - A nightly review sees evidence for a target with an existing pending proposal+ * - Proposal creation needs to avoid duplicate unresolved briefs+ *+ * Expects:+ * - `now` is the comparison timestamp for expiry checks+ *+ * Returns:+ * - `{ refresh: true }` only for same-key, same-action, unexpired pending proposals+ */+export const shouldRefreshMaintenanceProposal = ({+ existing,+ incoming,+ now,+}: {+ existing: Pick<+ MaintenanceProposalMetadata,+ 'actionType' | 'expiresAt' | 'proposalKey' | 'status'+ > &+ Partial<MaintenanceProposalMetadata>;+ incoming: { actionType: MaintenanceActionType; proposalKey: string };+ now: string;+}) => {+ if (existing.status !== 'pending') return { refresh: false, reason: 'not_pending' as const };+ if (new Date(existing.expiresAt).getTime() <= new Date(now).getTime()) {+ return { refresh: false, reason: 'expired' as const };+ }+ if (existing.proposalKey !== incoming.proposalKey) {+ return { refresh: false, reason: 'different_key' as const };+ }+ if (existing.actionType && existing.actionType !== incoming.actionType) {+ return { refresh: false, reason: 'different_action' as const };+ }++ return { refresh: true };+};++const getActionTargetSignature = (+ action: Pick<MaintenanceProposalAction, 'operation' | 'target'>,+) => {+ if (action.target?.skillDocumentId) return `skillDocumentId:${action.target.skillDocumentId}`;+ if (action.target?.memoryId) return `memoryId:${action.target.memoryId}`;+ if (action.target?.skillName) return `skillName:${action.target.skillName}`;+ if (action.operation?.domain === 'skill' && 'skillDocumentId' in action.operation.input) {+ return `skillDocumentId:${action.operation.input.skillDocumentId}`;+ }+ if (action.operation?.domain === 'memory' && 'content' in action.operation.input) {+ return 'memory:content';+ }++ return 'unknown';+};++const getActionOperationSignature = (action: MaintenanceProposalAction) =>+ [+ action.actionType,+ action.operation?.domain ?? 'none',+ action.operation?.operation ?? 'none',+ getActionTargetSignature(action),+ ].join(':');++/**+ * Checks whether two frozen proposal action lists can refresh the same pending proposal.+ *+ * Use when:+ * - A nightly review proposes a change for a target that already has a pending proposal+ * - Free-form rationale or summaries changed but the underlying operation identity did not+ *+ * Expects:+ * - Caller has already matched proposals by `proposalKey`+ *+ * Returns:+ * - `true` when action type, operation domain/name, and target identity are equivalent+ */+export const areProposalActionsCompatible = (+ existing: MaintenanceProposalAction[],+ incoming: MaintenanceProposalAction[],+) => {+ if (existing.length !== incoming.length) return false;++ return existing.every(+ (action, index) =>+ getActionOperationSignature(action) === getActionOperationSignature(incoming[index]),+ );+};++/**+ * Decides whether an incoming proposal should replace a pending proposal with the same key.+ *+ * Use when:+ * - A nightly review found a same-target proposal whose operation is no longer compatible+ * - The old proposal should become superseded instead of accumulating duplicate pending briefs+ *+ * Expects:+ * - `now` is the comparison timestamp for expiry checks+ *+ * Returns:+ * - `{ supersede: true }` only for same-key, unexpired pending proposals with incompatible actions+ */+export const shouldSupersedeMaintenanceProposal = ({+ existing,+ incoming,+ now,+}: {+ existing: Pick<MaintenanceProposalMetadata, 'actions' | 'expiresAt' | 'proposalKey' | 'status'> &+ Partial<MaintenanceProposalMetadata>;+ incoming: Pick<MaintenanceProposalMetadata, 'actions' | 'proposalKey'>;+ now: string;+}) => {+ if (existing.status !== 'pending') return { supersede: false, reason: 'not_pending' as const };+ if (new Date(existing.expiresAt).getTime() <= new Date(now).getTime()) {+ return { supersede: false, reason: 'expired' as const };+ }+ if (existing.proposalKey !== incoming.proposalKey) {+ return { supersede: false, reason: 'different_key' as const };+ }+ if (areProposalActionsCompatible(existing.actions, incoming.actions)) {+ return { supersede: false, reason: 'compatible' as const };+ }++ return { supersede: true };+};++/**+ * Refreshes a pending proposal with newer evidence while preserving its identity.+ *+ * Use when:+ * - A compatible nightly proposal repeats before the pending proposal expires+ * - The existing Daily Brief should remain the single user-visible proposal+ *+ * Expects:+ * - Existing and incoming proposals have already been checked for compatibility+ *+ * Returns:+ * - Proposal metadata with refreshed actions, evidence window, and sliding expiry+ */+export const refreshMaintenanceProposal = ({+ existing,+ incoming,+ now,+}: {+ existing: MaintenanceProposalMetadata;+ incoming: MaintenanceProposalMetadata;+ now: string;+}): MaintenanceProposalMetadata => ({+ ...existing,+ actions: incoming.actions,+ actionType: incoming.actionType,+ evidenceRefs: incoming.evidenceRefs,+ evidenceWindowEnd: incoming.evidenceWindowEnd,+ evidenceWindowStart: incoming.evidenceWindowStart,+ expiresAt: getNextProposalExpiry({ createdAt: existing.createdAt, now }),+ status: 'pending',+ updatedAt: now,+});++/**+ * Marks a pending proposal as superseded by a newer incompatible proposal.+ *+ * Use when:+ * - The same target receives a new proposal whose operation identity changed+ * - Future nightly reviews need to know why the old proposal stopped being active+ *+ * Expects:+ * - `supersededBy` is a proposal key or brief id for the replacement+ *+ * Returns:+ * - Proposal metadata with terminal `superseded` state+ */+export const supersedeMaintenanceProposal = ({+ existing,+ now,+ supersededBy,+}: {+ existing: MaintenanceProposalMetadata;+ now: string;+ supersededBy: string;+}): MaintenanceProposalMetadata => ({+ ...existing,+ status: 'superseded',+ supersededBy,+ updatedAt: now,+});diff --git a/src/server/services/agentSignal/services/maintenance/proposalApply.ts b/src/server/services/agentSignal/services/maintenance/proposalApply.tsnew file mode 100644index 00000000000..7c59060ab17--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/proposalApply.ts@@ -0,0 +1,325 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';++import type { CreateMaintenanceReviewReceiptsInput } from '../receiptService';+import type { MaintenanceProposalApplyGateResult } from './brief';+import type {+ MaintenanceProposalAction,+ MaintenanceProposalActionApplyResult,+ MaintenanceProposalApplyAttempt,+ MaintenanceProposalConflictReason,+ MaintenanceProposalMetadata,+} from './proposal';+import type { MaintenanceProposalPreflightResult } from './proposalPreflight';+import type { MaintenanceActionResult, MaintenancePlan, MaintenanceReviewRunResult } from './types';+import {+ MaintenanceActionStatus,+ MaintenanceApplyMode,+ MaintenanceReviewScope,+ MaintenanceRisk,+ ReviewRunStatus,+} from './types';++export interface ApplyMaintenanceProposalInput {+ /** Agent that owns the proposal target. */+ agentId: string;+ /** User-local date when the proposal is tied to a nightly run. */+ localDate?: string;+ /** Frozen proposal metadata read from Daily Brief metadata. */+ proposal: MaintenanceProposalMetadata;+ /** Source id used for approve-time receipts and idempotency context. */+ sourceId: string;+ /** Source type used for approve-time receipts. */+ sourceType: string;+ /** IANA timezone used for nightly receipt metadata. */+ timezone?: string;+ /** User that owns the proposal. */+ userId: string;+}++export interface ApplyMaintenanceProposalResult {+ /** Proposal metadata after the apply attempt has been recorded. */+ proposal: MaintenanceProposalMetadata;+ /** Executor result for mergeable actions, or a synthetic result for skipped-only attempts. */+ result: MaintenanceReviewRunResult;+}++export interface MaintenanceProposalApplyAdapters {+ /** Re-checks one frozen action against current target state. */+ checkAction: (action: MaintenanceProposalAction) => Promise<MaintenanceProposalPreflightResult>;+ /** Re-checks feature/user/agent gates immediately before mutation. */+ checkGates: () => Promise<MaintenanceProposalApplyGateResult>;+ /** Executes the fresh subset through the normal maintenance executor. */+ executePlan: (plan: MaintenancePlan) => Promise<MaintenanceReviewRunResult>;+ /** Clock injected for deterministic apply-attempt metadata. */+ now?: () => string;+ /** Persists updated proposal metadata. */+ updateProposal: (proposal: MaintenanceProposalMetadata) => Promise<void>;+ /** Persists approve-time receipts for the executed subset. */+ writeReceipts?: (input: CreateMaintenanceReviewReceiptsInput) => Promise<void>;+}++interface PreparedAction {+ action: MaintenanceProposalAction;+ planAction: MaintenancePlan['actions'][number];+}++const toPlanAction = (+ action: MaintenanceProposalAction,+): MaintenancePlan['actions'][number] | undefined => {+ if (!action.operation) return;++ return {+ actionType: action.actionType,+ applyMode: MaintenanceApplyMode.AutoApply,+ confidence: 1,+ dedupeKey: action.idempotencyKey,+ evidenceRefs: action.evidenceRefs,+ idempotencyKey: action.idempotencyKey,+ operation: action.operation,+ rationale: action.rationale,+ risk: action.risk ?? MaintenanceRisk.Medium,+ ...(action.target ? { target: action.target } : {}),+ };+};++const toApplyResult = (+ action: MaintenanceProposalAction,+ status: MaintenanceProposalActionApplyResult['status'],+ summary: string,+): MaintenanceProposalActionApplyResult => ({+ idempotencyKey: action.idempotencyKey,+ status,+ summary,+});++const mapExecutionStatus = (+ result: MaintenanceActionResult,+): MaintenanceProposalActionApplyResult['status'] => {+ if (result.status === MaintenanceActionStatus.Applied) return 'applied';+ if (result.status === MaintenanceActionStatus.Deduped) return 'deduped';+ if (result.status === MaintenanceActionStatus.Failed) return 'failed';++ return 'skipped_unsupported';+};++const getAttemptStatus = (+ actionResults: MaintenanceProposalActionApplyResult[],+): MaintenanceProposalApplyAttempt['status'] => {+ const hasApplied = actionResults.some(+ (result) => result.status === 'applied' || result.status === 'deduped',+ );+ const hasFailed = actionResults.some(+ (result) => result.status === 'failed' || result.status === 'skipped_unsupported',+ );+ const hasStale = actionResults.some((result) => result.status === 'skipped_stale');++ if (hasApplied && (hasFailed || hasStale)) return 'partially_failed';+ if (hasApplied) return 'applied';+ if (hasStale && !hasFailed) return 'stale';++ return 'failed';+};++const getProposalStatus = (status: MaintenanceProposalApplyAttempt['status']) => {+ if (status === 'applied') return 'applied';+ if (status === 'partially_failed') return 'partially_failed';+ if (status === 'stale') return 'stale';++ return 'failed';+};++const getFirstConflictReason = (+ result: MaintenanceProposalPreflightResult,+): MaintenanceProposalConflictReason | undefined => {+ if (result.allowed || result.reason === 'unsupported') return;++ return result.reason;+};++const buildSyntheticResult = (+ actionResults: MaintenanceProposalActionApplyResult[],+): MaintenanceReviewRunResult => ({+ actions: actionResults.map((result) => ({+ idempotencyKey: result.idempotencyKey,+ ...(result.resourceId ? { resourceId: result.resourceId } : {}),+ status:+ result.status === 'failed'+ ? MaintenanceActionStatus.Failed+ : result.status === 'deduped'+ ? MaintenanceActionStatus.Deduped+ : result.status === 'applied'+ ? MaintenanceActionStatus.Applied+ : MaintenanceActionStatus.Skipped,+ ...(result.summary ? { summary: result.summary } : {}),+ })),+ status: actionResults.some((result) => result.status === 'failed')+ ? ReviewRunStatus.Failed+ : ReviewRunStatus.Skipped,+});++/**+ * Creates the approve-time merge path for Agent Signal maintenance proposals.+ *+ * Use when:+ * - A user approves an Agent Signal Daily Brief proposal+ * - Frozen proposal actions must be rechecked before mutation+ *+ * Expects:+ * - Callers persist proposal metadata through `updateProposal`+ * - `executePlan` is the same executor family used by nightly maintenance+ *+ * Returns:+ * - A service that records one apply attempt and never reruns reviewer/planner+ */+export const createMaintenanceProposalApplyService = (+ adapters: MaintenanceProposalApplyAdapters,+) => ({+ apply: async (input: ApplyMaintenanceProposalInput): Promise<ApplyMaintenanceProposalResult> =>+ tracer.startActiveSpan(+ 'agent_signal.maintenance_proposal.apply',+ {+ attributes: {+ 'agent.signal.agent_id': input.agentId,+ 'agent.signal.proposal.action_count': input.proposal.actions.length,+ 'agent.signal.proposal.key': input.proposal.proposalKey,+ 'agent.signal.source_id': input.sourceId,+ 'agent.signal.user_id': input.userId,+ },+ },+ async (span) => {+ try {+ const now = adapters.now?.() ?? new Date().toISOString();+ const gateResult = await adapters.checkGates();+ const skippedResults: MaintenanceProposalActionApplyResult[] = [];+ const executableActions: PreparedAction[] = [];+ let conflictReason: MaintenanceProposalConflictReason | undefined;++ if (!gateResult.allowed) {+ conflictReason = gateResult.reason;+ skippedResults.push(+ ...input.proposal.actions.map((action) =>+ toApplyResult(action, 'skipped_stale', `Proposal blocked: ${gateResult.reason}.`),+ ),+ );+ } else {+ for (const action of input.proposal.actions) {+ const preflight = await adapters.checkAction(action);+ if (!preflight.allowed) {+ conflictReason ??= getFirstConflictReason(preflight);+ skippedResults.push(+ toApplyResult(+ action,+ preflight.reason === 'unsupported' ? 'skipped_unsupported' : 'skipped_stale',+ preflight.reason === 'unsupported'+ ? 'Proposal action is not supported by approve-time apply.'+ : `Proposal target changed: ${preflight.reason}.`,+ ),+ );+ continue;+ }++ const planAction = toPlanAction(action);+ if (!planAction) {+ skippedResults.push(+ toApplyResult(+ action,+ 'skipped_unsupported',+ 'Proposal action is missing an executable operation.',+ ),+ );+ continue;+ }++ executableActions.push({ action, planAction });+ }+ }++ const plan: MaintenancePlan = {+ actions: executableActions.map(({ planAction }) => planAction),+ plannerVersion: 'maintenance-proposal-apply-v1',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: `Apply maintenance proposal ${input.proposal.proposalKey}.`,+ ...(input.localDate ? { localDate: input.localDate } : {}),+ };+ const execution =+ plan.actions.length > 0+ ? await adapters.executePlan(plan)+ : buildSyntheticResult(skippedResults);+ const executionByKey = new Map(+ execution.actions.map((result) => [result.idempotencyKey, result]),+ );+ const executedResults = executableActions.map(({ action }) => {+ const result = executionByKey.get(action.idempotencyKey);+ if (!result) {+ return toApplyResult(action, 'failed', 'Executor did not return an action result.');+ }++ return {+ idempotencyKey: action.idempotencyKey,+ ...(result.resourceId ? { resourceId: result.resourceId } : {}),+ status: mapExecutionStatus(result),+ ...(result.summary ? { summary: result.summary } : {}),+ };+ });+ const applyResultByKey = new Map(+ [...executedResults, ...skippedResults].map((result) => [+ result.idempotencyKey,+ result,+ ]),+ );+ const actionResults = input.proposal.actions.map(+ (action) =>+ applyResultByKey.get(action.idempotencyKey) ??+ toApplyResult(action, 'failed', 'Proposal action was not evaluated.'),+ );+ const attemptStatus = getAttemptStatus(actionResults);+ const applyAttempt: MaintenanceProposalApplyAttempt = {+ actionResults,+ appliedAt: now,+ status: attemptStatus,+ };+ const proposal: MaintenanceProposalMetadata = {+ ...input.proposal,+ applyAttempts: [...(input.proposal.applyAttempts ?? []), applyAttempt],+ ...(conflictReason ? { conflictReason } : {}),+ status: getProposalStatus(attemptStatus),+ updatedAt: now,+ };++ if (plan.actions.length > 0 && adapters.writeReceipts) {+ await adapters.writeReceipts({+ agentId: input.agentId,+ createdAt: Date.parse(now),+ ...(input.localDate ? { localDate: input.localDate } : {}),+ plan,+ result: execution,+ sourceId: input.sourceId,+ sourceType: input.sourceType,+ ...(input.timezone ? { timezone: input.timezone } : {}),+ userId: input.userId,+ });+ }++ await adapters.updateProposal(proposal);+ span.setAttribute('agent.signal.proposal.apply_status', proposal.status);+ span.setAttribute('agent.signal.proposal.executable_action_count', plan.actions.length);+ if (conflictReason) {+ span.setAttribute('agent.signal.proposal.conflict_reason', conflictReason);+ }+ span.setStatus({ code: SpanStatusCode.OK });++ return { proposal, result: execution };+ } catch (error) {+ span.recordException(error as Error);+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message: error instanceof Error ? error.message : String(error),+ });+ throw error;+ } finally {+ span.end();+ }+ },+ ),+});diff --git a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts b/src/server/services/agentSignal/services/maintenance/proposalPreflight.tsnew file mode 100644index 00000000000..9e8a4cf07c2--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts@@ -0,0 +1,98 @@+import type { MaintenanceProposalAction, MaintenanceProposalConflictReason } from './proposal';++export type MaintenanceProposalPreflightReason = MaintenanceProposalConflictReason | 'unsupported';++/** Snapshot of a managed skill target used for approve-time freshness checks. */+export interface MaintenanceProposalSkillTargetSnapshot {+ /** Current agent document binding id. */+ agentDocumentId: string;+ /** Current hash of the skill body or normalized content. */+ contentHash?: string;+ /** Current backing document id. */+ documentId?: string;+ /** Whether the target is still managed by Agent Signal. */+ managed: boolean;+ /** Current human-readable title. */+ targetTitle?: string;+ /** Whether the target may still be mutated. */+ writable: boolean;+}++/** Adapters required by proposal apply preflight. */+export interface MaintenanceProposalPreflightAdapters {+ /** Reads current managed skill target state by agent document id. */+ readSkillTarget: (+ agentDocumentId: string,+ ) => Promise<MaintenanceProposalSkillTargetSnapshot | undefined>;+}++/** Successful proposal preflight result. */+export interface MaintenanceProposalPreflightAllowed {+ /** Whether the action may still be applied. */+ allowed: true;+}++/** Failed proposal preflight result with conflict reason. */+export interface MaintenanceProposalPreflightDenied {+ /** Whether the action may still be applied. */+ allowed: false;+ /** Conflict reason recorded on stale or unsupported proposal actions. */+ reason: MaintenanceProposalPreflightReason;+}++export type MaintenanceProposalPreflightResult =+ | MaintenanceProposalPreflightAllowed+ | MaintenanceProposalPreflightDenied;++/**+ * Creates approve-time preflight checks for frozen maintenance proposal actions.+ *+ * Use when:+ * - A user approves a Daily Brief maintenance proposal+ * - The merge path must detect stale, deleted, readonly, or retargeted skill documents first+ *+ * Expects:+ * - Proposal actions include the base snapshot captured when the proposal was created+ * - `readSkillTarget` returns current truth for the same user/agent boundary+ *+ * Returns:+ * - A service that accepts unchanged `refine_skill` targets and rejects drifted targets+ */+export const createMaintenanceProposalPreflightService = (+ adapters: MaintenanceProposalPreflightAdapters,+) => ({+ checkAction: async (+ action: MaintenanceProposalAction,+ ): Promise<MaintenanceProposalPreflightResult> => {+ if (action.actionType !== 'refine_skill') {+ return { allowed: false, reason: 'unsupported' };+ }++ const targetId = action.target?.skillDocumentId;+ if (!targetId || !action.baseSnapshot) {+ return { allowed: false, reason: 'target_deleted' };+ }++ const current = await adapters.readSkillTarget(targetId);+ if (!current) {+ return { allowed: false, reason: 'target_deleted' };+ }++ if (!current.writable || !current.managed) {+ return { allowed: false, reason: 'target_not_writable' };+ }++ if (action.baseSnapshot.documentId && current.documentId !== action.baseSnapshot.documentId) {+ return { allowed: false, reason: 'target_type_changed' };+ }++ if (+ action.baseSnapshot.contentHash &&+ current.contentHash !== action.baseSnapshot.contentHash+ ) {+ return { allowed: false, reason: 'document_changed' };+ }++ return { allowed: true };+ },+});diff --git a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts b/src/server/services/agentSignal/services/maintenance/serverRuntime.tsindex 790ab1b7cf9..6c98100a554 100644--- a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts+++ b/src/server/services/agentSignal/services/maintenance/serverRuntime.ts@@ -8,6 +8,7 @@ import { z } from 'zod';import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';+import { BriefModel } from '@/database/models/brief';import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';@@ -30,6 +31,7 @@ import { redisPolicyStateStore } from '../../store/adapters/redis/policyStateStoimport { redisSourceEventStore } from '../../store/adapters/redis/sourceEventStore';import { persistAgentSignalReceipts } from '../receiptService';import { createSelfReflectionService } from '../selfReflection';+import { createMaintenanceAgentRunner } from './agentRunner';import { createServerMaintenanceBriefWriter } from './brief';import { createMaintenanceExecutorService } from './executor';import { createMemoryMaintenanceService } from './memory';@@ -39,13 +41,16 @@ import type {NightlyReviewManagedSkillSummary,NightlyReviewRelevantMemorySummary,NightlyReviewTopicActivityRow,+ ProposalActivityDigest,ReceiptActivityDigest,ToolActivityDigest,} from './nightlyCollector';import { createNightlyReviewService } from './nightlyCollector';import { mapNightlyDocumentActivityRows } from './nightlyDocumentActivity';import { createMaintenancePlannerService } from './planner';+import { getMaintenanceProposalFromBriefMetadata } from './proposal';import { createSkillManagementService } from './skill';+import { createMaintenanceTools } from './tools';import type {EvidenceRef,MaintenanceActionDraft,@@ -237,6 +242,22 @@ const NIGHTLY_REVIEW_AGENT_SCHEMA = {strict: true,} satisfies GenerateObjectSchema;+/** Bounded unresolved Daily Brief read budget for proposal activity digesting. */+const NIGHTLY_PROPOSAL_ACTIVITY_LIMIT = 20;++/** Daily Brief trigger used by Agent Signal nightly maintenance proposals. */+const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';++const ACTIVE_PROPOSAL_STATUSES = new Set(['accepted', 'applying', 'pending']);++interface ProposalBriefReader {+ listUnresolvedByAgentAndTrigger: (options: {+ agentId: string;+ limit?: number;+ trigger: string;+ }) => Promise<Awaited<ReturnType<BriefModel['listUnresolvedByAgentAndTrigger']>>>;+}+// Runtime parser for model output after structured generation. This mirrors the// model-facing schema above, but the two schemas serve different boundaries.const EvidenceRefSchema = z@@ -423,11 +444,7 @@ const createServerMaintenanceExecutor = (input: {};},refineSkill: async ({ input: skillInput }) => {- const bodyMarkdown =- getStringField(skillInput, 'bodyMarkdown') ??- getStringField(skillInput, 'patch') ??- getStringField(skillInput, 'content') ??- '';+ const bodyMarkdown = getStringField(skillInput, 'bodyMarkdown') ?? '';const result = await input.skillDocumentService.replaceSkillIndex({agentId: input.agentId ?? '',agentDocumentId: skillInput.skillDocumentId,@@ -549,6 +566,172 @@ const collectSelfReflectionContext = async (};};+const getProposalTargetDigest = (+ proposal: NonNullable<ReturnType<typeof getMaintenanceProposalFromBriefMetadata>>,+): Pick<ProposalActivityDigest['active'][number], 'targetId' | 'targetTitle'> => {+ const action = proposal.actions[0];+ const target = action?.target;++ return {+ ...(target?.skillDocumentId+ ? { targetId: target.skillDocumentId }+ : target?.memoryId+ ? { targetId: target.memoryId }+ : target?.skillName+ ? { targetId: target.skillName }+ : {}),+ ...(action?.baseSnapshot?.targetTitle ? { targetTitle: action.baseSnapshot.targetTitle } : {}),+ };+};++const getProposalEvidenceCount = (+ proposal: NonNullable<ReturnType<typeof getMaintenanceProposalFromBriefMetadata>>,+) => {+ const evidenceRefs = new Map<string, EvidenceRef>();++ for (const evidenceRef of proposal.evidenceRefs ?? []) {+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);+ }++ for (const action of proposal.actions) {+ for (const evidenceRef of action.evidenceRefs) {+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);+ }+ }++ return evidenceRefs.size;+};++const hasPendingProposalExpired = ({ expiresAt, now }: { expiresAt: string; now: string }) => {+ const expiresAtMs = new Date(expiresAt).getTime();+ const nowMs = new Date(now).getTime();++ return Number.isFinite(expiresAtMs) && Number.isFinite(nowMs) && expiresAtMs <= nowMs;+};++const isNoopProposal = (+ proposal: NonNullable<ReturnType<typeof getMaintenanceProposalFromBriefMetadata>>,+) =>+ proposal.actionType === 'noop' ||+ proposal.actions.every((action) => action.actionType === 'noop');++/**+ * Lists existing server-side maintenance proposal activity for one agent.+ *+ * Use when:+ * - Nightly review context needs unresolved proposal state+ * - Tests need the server adapter behavior without booting the full runtime+ *+ * Expects:+ * - `briefModel` applies user, agent, trigger, and unresolved filters before the limit+ * - `now` is an ISO timestamp used to treat expired pending proposals as inactive+ * - Stored metadata may be malformed and must be treated as absent+ *+ * Returns:+ * - Active unresolved proposal digests plus unresolved status counts+ */+export const listServerProposalActivity = async ({+ agentId,+ briefModel,+ now = new Date().toISOString(),+ userId,+}: {+ agentId: string;+ briefModel: ProposalBriefReader;+ now?: string;+ userId: string;+}): Promise<ProposalActivityDigest> =>+ tracer.startActiveSpan(+ 'agent_signal.nightly_review.collector.list_proposal_activity',+ {+ attributes: {+ 'agent.signal.agent_id': agentId,+ 'agent.signal.nightly.proposal_read_limit': NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,+ 'agent.signal.user_id': userId,+ },+ },+ async (span) => {+ try {+ const rows = await briefModel.listUnresolvedByAgentAndTrigger({+ agentId,+ limit: NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,+ });+ const digest: ProposalActivityDigest = {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ };+ let validProposalCount = 0;++ for (const brief of rows) {+ if (brief.agentId !== agentId) continue;+ if (brief.trigger !== NIGHTLY_REVIEW_BRIEF_TRIGGER) continue;++ const proposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);+ if (!proposal) continue;+ if (isNoopProposal(proposal)) continue;++ validProposalCount += 1;++ if (proposal.status === 'dismissed') digest.dismissedCount += 1;+ if (proposal.status === 'expired') digest.expiredCount += 1;+ if (proposal.status === 'stale') digest.staleCount += 1;+ if (proposal.status === 'superseded') digest.supersededCount += 1;++ if (+ proposal.status === 'pending' &&+ hasPendingProposalExpired({ expiresAt: proposal.expiresAt, now })+ ) {+ digest.expiredCount += 1;+ continue;+ }++ if (!ACTIVE_PROPOSAL_STATUSES.has(proposal.status)) continue;++ digest.active.push({+ actionType: proposal.actionType,+ createdAt: proposal.createdAt,+ evidenceCount: getProposalEvidenceCount(proposal),+ expiresAt: proposal.expiresAt,+ proposalId: brief.id,+ proposalKey: proposal.proposalKey,+ status: proposal.status,+ summary: brief.summary,+ ...getProposalTargetDigest(proposal),+ updatedAt: proposal.updatedAt,+ });+ }++ span.setAttribute('agent.signal.nightly.proposal_unresolved_row_count', rows.length);+ span.setAttribute('agent.signal.nightly.proposal_valid_count', validProposalCount);+ span.setAttribute('agent.signal.nightly.proposal_active_count', digest.active.length);+ span.setAttribute('agent.signal.nightly.proposal_dismissed_count', digest.dismissedCount);+ span.setAttribute('agent.signal.nightly.proposal_expired_count', digest.expiredCount);+ span.setAttribute('agent.signal.nightly.proposal_stale_count', digest.staleCount);+ span.setAttribute('agent.signal.nightly.proposal_superseded_count', digest.supersededCount);+ span.setStatus({ code: SpanStatusCode.OK });++ return digest;+ } catch (error) {+ span.setStatus({+ code: SpanStatusCode.ERROR,+ message:+ error instanceof Error+ ? error.message+ : 'AgentSignal nightly proposal activity read failed',+ });+ span.recordException(error as Error);++ throw error;+ } finally {+ span.end();+ }+ },+ );+/*** Creates server runtime handlers for the self-reflection source handler.*@@ -745,6 +928,7 @@ export const createServerNightlyReviewPolicyOptions = ({const planner = createMaintenancePlannerService();const nightlyReviewModel = new AgentSignalNightlyReviewModel(db);const reviewContextModel = new AgentSignalReviewContextModel(db, userId);+ const briefModel = new BriefModel(db, userId);const skillDocumentService = new SkillManagementDocumentService(db, userId);const collector = createNightlyReviewService({listDocumentActivity: async ({ agentId: targetAgentId, reviewWindowEnd, reviewWindowStart }) =>@@ -826,6 +1010,12 @@ export const createServerNightlyReviewPolicyOptions = ({readonly: false,}));},+ listProposalActivity: ({ agentId: targetAgentId }) =>+ listServerProposalActivity({+ agentId: targetAgentId,+ briefModel,+ userId,+ }),listRelevantMemories: async ({ limit = 20 }) => {const rows = await reviewContextModel.listRelevantMemories({ limit });@@ -928,6 +1118,8 @@ export const createServerNightlyReviewPolicyOptions = ({});return rows.map<NightlyReviewTopicActivityRow>((row) => ({+ correctionCount: row.correctionCount,+ correctionIds: row.correctionIds,evidenceRefs: row.topicId ? [{ id: row.topicId, type: 'topic' }] : [],failedMessages: row.failedMessages,failedToolCount: row.failedToolCount,@@ -947,6 +1139,31 @@ export const createServerNightlyReviewPolicyOptions = ({skillDocumentService,userId,});+ const maintenanceTools = createMaintenanceTools({+ reserveOperation: async () => ({ reserved: true }),+ writeReceipt: async () => ({}),+ });+ const maintenanceAgentRunner = createMaintenanceAgentRunner({+ maxSteps: 10,+ run: async ({ context, localDate, reviewScope, sourceId }) => {+ const draft = await runServerMaintenanceReviewAgent(db, userId, context);+ const projectionPlan = planner.plan({+ draft,+ localDate,+ reviewScope,+ sourceId,+ userId,+ });+ const execution = await executor.execute(projectionPlan);++ return {+ execution,+ projectionPlan,+ stepCount: 1,+ };+ },+ tools: maintenanceTools,+ });const briefWriter = createServerMaintenanceBriefWriter(db, userId);return {@@ -972,9 +1189,13 @@ export const createServerNightlyReviewPolicyOptions = ({return targets.length > 0;},collectContext: (input) => collector.collectNightlyReviewContext(input),- executePlan: (plan) => executor.execute(plan),- planReviewOutput: (request) => planner.plan(request),- runMaintenanceReviewAgent: (context) => runServerMaintenanceReviewAgent(db, userId, context),+ runMaintenanceReviewAgent: ({ context, localDate, sourceId, userId: runnerUserId }) =>+ maintenanceAgentRunner.run({+ context,+ localDate,+ sourceId,+ userId: runnerUserId,+ }),writeDailyBrief: (brief) => briefWriter.writeDailyBrief(brief),writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),};diff --git a/src/server/services/agentSignal/services/maintenance/skill.ts b/src/server/services/agentSignal/services/maintenance/skill.tsindex b7f14b77b8a..2f32314594f 100644--- a/src/server/services/agentSignal/services/maintenance/skill.ts+++ b/src/server/services/agentSignal/services/maintenance/skill.ts@@ -22,7 +22,9 @@ export interface CreateMaintenanceSkillInput extends SkillMaintenanceBaseInput {/** Input for refining an existing managed skill. */export interface RefineMaintenanceSkillInput extends SkillMaintenanceBaseInput {- /** Patch, replacement body, or maintainer payload. */+ /** Full replacement Markdown body without YAML frontmatter. */+ bodyMarkdown?: string;+ /** Human-readable proposal patch text, not executable replacement content. */patch?: string;/** Writable managed skill agent document id. */skillDocumentId: string;@@ -103,6 +105,12 @@ const assertApprovedConsolidation = (input: ConsolidateMaintenanceSkillInput) =>}};+const assertCompleteRefineBody = (input: RefineMaintenanceSkillInput) => {+ if (!input.bodyMarkdown?.trim()) {+ throw new Error('Skill refinement requires a complete replacement bodyMarkdown');+ }+};+/*** Creates a skill management maintenance service.*@@ -141,6 +149,7 @@ export const createSkillManagementService = (adapters: SkillMaintenanceAdapters},refineSkill: async (request: SkillMaintenanceRefineRequest): Promise<SkillMaintenanceResult> => {assertWritableSkill(request.input.targetReadonly);+ assertCompleteRefineBody(request.input);if (!adapters.refineSkill) {throw new Error('Skill refine adapter is required');diff --git a/src/server/services/agentSignal/services/maintenance/tools.ts b/src/server/services/agentSignal/services/maintenance/tools.tsnew file mode 100644index 00000000000..ec4c645ff4e--- /dev/null+++ b/src/server/services/agentSignal/services/maintenance/tools.ts@@ -0,0 +1,555 @@+import { SpanStatusCode } from '@lobechat/observability-otel/api';+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';++/** Terminal status emitted by safe maintenance write tools. */+export type MaintenanceToolWriteStatus =+ | 'applied'+ | 'deduped'+ | 'failed'+ | 'proposed'+ | 'skipped_stale'+ | 'skipped_unsupported';++/** Public result returned by safe maintenance write tools. */+export interface MaintenanceToolWriteResult {+ /** Receipt written for the terminal tool outcome. */+ receiptId?: string;+ /** Resource touched or considered by the maintenance tool. */+ resourceId?: string;+ /** Terminal write safety status. */+ status: MaintenanceToolWriteStatus;+ /** Bounded human-readable tool result. */+ summary?: string;+}++/** Successful preflight result for a maintenance write targeting an existing resource. */+export interface MaintenanceToolPreflightAllowed {+ /** Whether the target is still safe to mutate. */+ allowed: true;+}++/** Failed preflight result for a maintenance write targeting an existing resource. */+export interface MaintenanceToolPreflightDenied {+ /** Whether the target is still safe to mutate. */+ allowed: false;+ /** Short stale/conflict reason to store in the receipt. */+ reason: string;+}++/** Preflight result emitted before existing-resource writes. */+export type MaintenanceToolPreflightResult =+ | MaintenanceToolPreflightAllowed+ | MaintenanceToolPreflightDenied;++/** Shared write envelope accepted by all maintenance tools. */+export interface MaintenanceToolWriteInput {+ /** Stable operation key used to dedupe repeated tool calls. */+ idempotencyKey: string;+ /** Stable proposal key used for proposal-scoped tracing and receipts. */+ proposalKey?: string;+ /** Optional caller-provided summary, bounded before persistence. */+ summary?: string;+ /** User that owns the maintenance operation. */+ userId: string;+}++/** Input for replacing one managed skill using compare-and-swap safety checks. */+export interface ReplaceSkillContentCASInput extends MaintenanceToolWriteInput {+ /** Replacement skill body. */+ bodyMarkdown: string;+ /** Optional replacement description. */+ description?: string;+ /** Existing managed skill document id. */+ skillDocumentId: string;+}++/** Input for creating one skill when no existing skill has been selected. */+export interface CreateSkillIfAbsentInput extends MaintenanceToolWriteInput {+ /** Skill body or authoring payload. */+ bodyMarkdown?: string;+ /** Optional skill description. */+ description?: string;+ /** Stable skill name. */+ name?: string;+ /** Optional skill title. */+ title?: string;+}++/** Input for creating one user-visible maintenance proposal. */+export interface CreateMaintenanceProposalInput extends MaintenanceToolWriteInput {+ /** Proposal action payload retained by the injected proposal adapter. */+ actions?: unknown[];+ /** Proposal metadata retained by the injected proposal adapter. */+ metadata?: Record<string, unknown>;+}++/** Input for refreshing an existing maintenance proposal. */+export interface RefreshMaintenanceProposalInput extends MaintenanceToolWriteInput {+ /** Existing proposal id to refresh. */+ proposalId: string;+}++/** Input for superseding an existing maintenance proposal. */+export interface SupersedeMaintenanceProposalInput extends MaintenanceToolWriteInput {+ /** Existing proposal id to supersede. */+ proposalId: string;+ /** Replacement proposal key or id. */+ supersededBy: string;+}++/** Input for closing an existing maintenance proposal. */+export interface CloseMaintenanceProposalInput extends MaintenanceToolWriteInput {+ /** Existing proposal id to close. */+ proposalId: string;+ /** Lifecycle reason recorded by the injected adapter. */+ reason?: string;+}++/** Result returned by mutation adapters before receipt persistence. */+export interface MaintenanceToolMutationResult {+ /** Resource created or updated by the adapter. */+ resourceId?: string;+ /** Short adapter summary. */+ summary?: string;+}++/** Receipt write request emitted after every terminal write outcome. */+export interface MaintenanceToolReceiptInput extends MaintenanceToolWriteResult {+ /** Stable operation key used to dedupe repeated tool calls. */+ idempotencyKey: string;+ /** Stable proposal key used for proposal-scoped tracing and receipts. */+ proposalKey?: string;+ /** Tool that produced this receipt. */+ toolName: string;+ /** User that owns the maintenance operation. */+ userId: string;+}++/** Receipt adapter result. */+export interface MaintenanceToolReceiptResult {+ /** Persisted receipt id. */+ receiptId?: string;+}++/** Lifecycle request emitted after a reserved maintenance operation reaches a terminal state. */+export interface MaintenanceToolOperationLifecycleInput extends MaintenanceToolReceiptInput {+ /** Persisted terminal receipt id, when the receipt adapter returns one. */+ receiptId?: string;+}++/** Lifecycle request emitted when a reserved operation cannot write its terminal receipt. */+export interface MaintenanceToolOperationFailureInput extends MaintenanceToolReceiptInput {+ /** Error thrown while writing the terminal receipt. */+ error: unknown;+}++/** Atomic reservation result for a newly claimed maintenance operation. */+export interface MaintenanceToolReservedOperation {+ /** True when the adapter atomically claimed this idempotency key for mutation. */+ reserved: true;+}++/** Atomic reservation result for a previously completed maintenance operation. */+export interface MaintenanceToolExistingOperation {+ /** Prior terminal operation result returned without running mutation. */+ existing: MaintenanceToolWriteResult;+ /** False when the adapter found an existing terminal operation for this key. */+ reserved: false;+}++/** Atomic idempotency reservation emitted before any write preflight or mutation. */+export type MaintenanceToolOperationReservation =+ | MaintenanceToolExistingOperation+ | MaintenanceToolReservedOperation;++/** Adapters used by safe maintenance read/write tools. */+export interface MaintenanceToolsAdapters {+ /** Closes an existing maintenance proposal. */+ closeProposal?: (input: CloseMaintenanceProposalInput) => Promise<MaintenanceToolMutationResult>;+ /**+ * Marks a reserved idempotency operation as terminal after its receipt is persisted.+ *+ * Adapters that store in-progress reservations should use this hook to make the terminal+ * receipt/result the dedupe source of truth. Without it, repeated calls may either rerun+ * mutation or leave reservations stuck in an in-progress state.+ */+ completeOperation?: (input: MaintenanceToolOperationLifecycleInput) => Promise<void>;+ /** Creates one user-visible maintenance proposal. */+ createProposal?: (+ input: CreateMaintenanceProposalInput,+ ) => Promise<MaintenanceToolMutationResult & { proposalId?: string }>;+ /** Creates one managed skill. */+ createSkill?: (input: CreateSkillIfAbsentInput) => Promise<MaintenanceToolMutationResult>;+ /**+ * Marks or releases a reserved operation when its terminal receipt cannot be persisted.+ *+ * Adapters should make this hook prevent duplicate mutation while avoiding permanently stuck+ * reservations. A common implementation records the failure against the idempotency key and+ * releases retryable reservation state only when the mutation contract is safe to retry.+ */+ markOperationFailed?: (input: MaintenanceToolOperationFailureInput) => Promise<void>;+ /** Checks freshness and writability before mutating existing resources. */+ preflight?: (+ input:+ | CloseMaintenanceProposalInput+ | RefreshMaintenanceProposalInput+ | ReplaceSkillContentCASInput+ | SupersedeMaintenanceProposalInput,+ ) => Promise<MaintenanceToolPreflightResult>;+ /** Reads an existing maintenance proposal. */+ readProposal?: (input: {+ proposalId?: string;+ proposalKey?: string;+ userId: string;+ }) => Promise<unknown>;+ /** Refreshes an existing maintenance proposal. */+ refreshProposal?: (+ input: RefreshMaintenanceProposalInput,+ ) => Promise<MaintenanceToolMutationResult>;+ /** Replaces existing managed skill content after CAS preflight. */+ replaceSkill?: (input: ReplaceSkillContentCASInput) => Promise<MaintenanceToolMutationResult>;+ /** Atomically reserves an idempotency key before any preflight or mutation runs. */+ reserveOperation: (idempotencyKey: string) => Promise<MaintenanceToolOperationReservation>;+ /** Supersedes an existing maintenance proposal. */+ supersedeProposal?: (+ input: SupersedeMaintenanceProposalInput,+ ) => Promise<MaintenanceToolMutationResult>;+ /** Writes the audit receipt for a terminal maintenance tool status. */+ writeReceipt: (input: MaintenanceToolReceiptInput) => Promise<MaintenanceToolReceiptResult>;+}++const MAX_SUMMARY_LENGTH = 240;++/**+ * Normalizes maintenance tool summaries.+ *+ * Before:+ * - `" A very long summary ... "`+ *+ * After:+ * - `"A very long summary ..."`+ */+const boundSummary = (summary: string | undefined) => {+ if (!summary) return undefined;++ const normalized = summary.trim().replaceAll(/\s+/g, ' ');++ return normalized.length > MAX_SUMMARY_LENGTH+ ? `${normalized.slice(0, MAX_SUMMARY_LENGTH - 3)}...`+ : normalized;+};++const errorSummary = (error: unknown) =>+ boundSummary(error instanceof Error ? error.message : String(error));++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++const getResultWithReceipt = async (+ adapters: MaintenanceToolsAdapters,+ input: MaintenanceToolWriteInput,+ toolName: string,+ result: MaintenanceToolWriteResult,+): Promise<MaintenanceToolWriteResult> => {+ const boundedResult = { ...result, summary: boundSummary(result.summary) };+ const receipt = await adapters.writeReceipt({+ ...boundedResult,+ idempotencyKey: input.idempotencyKey,+ proposalKey: input.proposalKey,+ toolName,+ userId: input.userId,+ });++ return { ...boundedResult, receiptId: receipt.receiptId ?? boundedResult.receiptId };+};++const withWriteSpan = async <TInput extends MaintenanceToolWriteInput>(+ toolName: string,+ input: TInput,+ operation: (+ recordConvertedException: (error: unknown) => void,+ ) => Promise<MaintenanceToolWriteResult>,+) => {+ return tracer.startActiveSpan(+ 'agent_signal.maintenance_tool.write',+ {+ attributes: {+ 'agent.signal.maintenance_tool.name': toolName,+ ...(input.proposalKey ? { 'agent.signal.proposal.key': input.proposalKey } : {}),+ },+ },+ async (span) => {+ try {+ const result = await operation((error) => span.recordException(error as Error));++ span.setAttribute('agent.signal.maintenance_tool.write_status', result.status);+ span.setStatus({+ code: result.status === 'failed' ? SpanStatusCode.ERROR : SpanStatusCode.OK,+ });++ return result;+ } catch (error) {+ span.recordException(error as Error);+ span.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });++ throw error;+ } finally {+ span.end();+ }+ },+ );+};++const withReadSpan = async <TResult>(+ toolName: string,+ proposalKey: string | undefined,+ operation: () => Promise<TResult>,+) => {+ return tracer.startActiveSpan(+ 'agent_signal.maintenance_tool.read',+ {+ attributes: {+ 'agent.signal.maintenance_tool.name': toolName,+ ...(proposalKey ? { 'agent.signal.proposal.key': proposalKey } : {}),+ },+ },+ async (span) => {+ try {+ const result = await operation();++ span.setStatus({ code: SpanStatusCode.OK });++ return result;+ } catch (error) {+ span.recordException(error as Error);+ span.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });++ throw error;+ } finally {+ span.end();+ }+ },+ );+};++const runWriteTool = async <TInput extends MaintenanceToolWriteInput>({+ adapters,+ input,+ mutate,+ preflight,+ preflightRequired,+ resourceId,+ successStatus,+ toolName,+ unsupportedSummary,+}: {+ adapters: MaintenanceToolsAdapters;+ input: TInput;+ mutate?: () => Promise<MaintenanceToolMutationResult>;+ preflight?: () => Promise<MaintenanceToolPreflightResult>;+ preflightRequired?: boolean;+ resourceId?: string;+ successStatus: Exclude<+ MaintenanceToolWriteStatus,+ 'deduped' | 'failed' | 'skipped_stale' | 'skipped_unsupported'+ >;+ toolName: string;+ unsupportedSummary: string;+}) => {+ return withWriteSpan(toolName, input, async (recordConvertedException) => {+ let operationReserved = false;+ const result = await (async (): Promise<MaintenanceToolWriteResult> => {+ try {+ const reservation = await adapters.reserveOperation(input.idempotencyKey);++ if (!reservation.reserved) {+ return {+ resourceId: reservation.existing.resourceId,+ status: 'deduped',+ summary: reservation.existing.summary,+ };+ }++ operationReserved = true;++ if (!mutate) {+ return {+ resourceId,+ status: 'skipped_unsupported',+ summary: unsupportedSummary,+ };+ }++ if (preflightRequired && !preflight) {+ return {+ resourceId,+ status: 'skipped_unsupported',+ summary: 'Maintenance preflight is not supported.',+ };+ }++ if (preflight) {+ const preflightResult = await preflight();++ if (!preflightResult.allowed) {+ return {+ resourceId,+ status: 'skipped_stale',+ summary: preflightResult.reason || input.summary,+ };+ }+ }++ const mutationResult = await mutate();++ return {+ resourceId: mutationResult.resourceId ?? resourceId,+ status: successStatus,+ summary: mutationResult.summary ?? input.summary,+ };+ } catch (error) {+ recordConvertedException(error);++ return {+ resourceId,+ status: 'failed',+ summary: errorSummary(error),+ };+ }+ })();++ try {+ const resultWithReceipt = await getResultWithReceipt(adapters, input, toolName, result);++ if (operationReserved) {+ await adapters.completeOperation?.({+ ...resultWithReceipt,+ idempotencyKey: input.idempotencyKey,+ proposalKey: input.proposalKey,+ toolName,+ userId: input.userId,+ });+ }++ return resultWithReceipt;+ } catch (error) {+ if (operationReserved) {+ await adapters.markOperationFailed?.({+ ...result,+ error,+ idempotencyKey: input.idempotencyKey,+ proposalKey: input.proposalKey,+ toolName,+ userId: input.userId,+ });+ }++ throw error;+ }+ });+};++/**+ * Creates safe read/write maintenance tools with injected domain adapters.+ *+ * Use when:+ * - Agent Signal needs callable maintenance tools before runner wiring+ * - Tests need to verify write safety contracts without database services+ *+ * Expects:+ * - `idempotencyKey` is stable per intended write+ * - Existing-resource writes inject `preflight` before mutation+ *+ * Returns:+ * - Tool functions that dedupe, preflight, mutate, receipt, and trace consistently+ */+export const createMaintenanceTools = (adapters: MaintenanceToolsAdapters) => ({+ closeMaintenanceProposal: async (input: CloseMaintenanceProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.closeProposal ? () => adapters.closeProposal!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.proposalId,+ successStatus: 'applied',+ toolName: 'closeMaintenanceProposal',+ unsupportedSummary: 'Maintenance proposal close is not supported.',+ }),+ createMaintenanceProposal: async (input: CreateMaintenanceProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.createProposal+ ? async () => {+ const result = await adapters.createProposal!(input);++ return {+ resourceId: result.resourceId ?? result.proposalId,+ summary: result.summary,+ };+ }+ : undefined,+ successStatus: 'proposed',+ toolName: 'createMaintenanceProposal',+ unsupportedSummary: 'Maintenance proposal creation is not supported.',+ }),+ createSkillIfAbsent: async (input: CreateSkillIfAbsentInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.createSkill ? () => adapters.createSkill!(input) : undefined,+ successStatus: 'applied',+ toolName: 'createSkillIfAbsent',+ unsupportedSummary: 'Skill creation is not supported.',+ }),+ readMaintenanceProposal: async (input: {+ proposalId?: string;+ proposalKey?: string;+ userId: string;+ }) =>+ withReadSpan('readMaintenanceProposal', input.proposalKey, async () => {+ if (!adapters.readProposal) return undefined;++ return adapters.readProposal(input);+ }),+ refreshMaintenanceProposal: async (input: RefreshMaintenanceProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.refreshProposal ? () => adapters.refreshProposal!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.proposalId,+ successStatus: 'proposed',+ toolName: 'refreshMaintenanceProposal',+ unsupportedSummary: 'Maintenance proposal refresh is not supported.',+ }),+ replaceSkillContentCAS: async (input: ReplaceSkillContentCASInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.replaceSkill ? () => adapters.replaceSkill!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.skillDocumentId,+ successStatus: 'applied',+ toolName: 'replaceSkillContentCAS',+ unsupportedSummary: 'Skill replacement is not supported.',+ }),+ supersedeMaintenanceProposal: async (input: SupersedeMaintenanceProposalInput) =>+ runWriteTool({+ adapters,+ input,+ mutate: adapters.supersedeProposal ? () => adapters.supersedeProposal!(input) : undefined,+ preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,+ preflightRequired: true,+ resourceId: input.proposalId,+ successStatus: 'applied',+ toolName: 'supersedeMaintenanceProposal',+ unsupportedSummary: 'Maintenance proposal supersede is not supported.',+ }),+});++/** Callable safe maintenance tools exposed to bounded maintenance agent runners. */+export type MaintenanceTools = ReturnType<typeof createMaintenanceTools>;diff --git a/src/server/services/brief/index.test.ts b/src/server/services/brief/index.test.tsindex 5e77749752e..aad73e47903 100644--- a/src/server/services/brief/index.test.ts+++ b/src/server/services/brief/index.test.ts@@ -5,6 +5,7 @@ import { AgentModel } from '@/database/models/agent';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';import type { LobeChatDatabase } from '@/database/type';+import { MaintenanceRisk } from '@/server/services/agentSignal/services/maintenance/types';import { BriefService } from './index';@@ -36,10 +37,12 @@ describe('BriefService', () => {};const mockBriefModel = {+ findById: vi.fn(),list: vi.fn(),listUnresolved: vi.fn(),listUnresolvedEnriched: vi.fn(),resolve: vi.fn(),+ updateMetadata: vi.fn(),};const mockTaskModel = {@@ -57,6 +60,7 @@ describe('BriefService', () => {(TaskModel as any).mockImplementation(() => mockTaskModel);// Default: no downstream tasks unlocked. Specific tests can override.mockTaskModel.getUnlockedTasks.mockResolvedValue([]);+ mockBriefModel.findById.mockResolvedValue(null);});describe('enrichBriefsWithAgents', () => {@@ -391,6 +395,107 @@ describe('BriefService', () => {});describe('resolve', () => {+ const proposalMetadata = {+ actionType: 'refine_skill' as const,+ actions: [+ {+ actionType: 'refine_skill' as const,+ evidenceRefs: [],+ idempotencyKey: 'nightly:refine:adoc_1',+ rationale: 'Refine a managed skill.',+ risk: MaintenanceRisk.Medium,+ },+ ],+ createdAt: '2026-05-09T00:00:00.000Z',+ evidenceWindowEnd: '2026-05-09T00:00:00.000Z',+ evidenceWindowStart: '2026-05-08T00:00:00.000Z',+ expiresAt: '2026-05-12T00:00:00.000Z',+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',+ status: 'pending' as const,+ updatedAt: '2026-05-09T00:00:00.000Z',+ version: 1 as const,+ };++ /**+ * @example+ * expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-1', { action: 'approve' });+ */+ it('applies a pending maintenance proposal before resolving an approved brief', async () => {+ const maintenanceProposalResolver = vi.fn().mockResolvedValue({+ brief: { id: 'proposal-1' },+ shouldResolve: true,+ });+ const service = new BriefService(db, userId, { maintenanceProposalResolver });+ mockBriefModel.findById.mockResolvedValue({+ id: 'proposal-1',+ metadata: { proposal: proposalMetadata },+ trigger: 'agent-signal:nightly-review',+ });+ mockBriefModel.resolve.mockResolvedValue({ id: 'proposal-1', resolvedAction: 'approve' });++ const result = await service.resolve('proposal-1', { action: 'approve' });++ expect(maintenanceProposalResolver).toHaveBeenCalledWith({+ action: 'approve',+ brief: expect.objectContaining({ id: 'proposal-1' }),+ proposal: proposalMetadata,+ });+ expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-1', { action: 'approve' });+ expect(result).toEqual({ id: 'proposal-1', resolvedAction: 'approve' });+ });++ /**+ * @example+ * expect(mockBriefModel.resolve).not.toHaveBeenCalled();+ */+ it('keeps stale maintenance proposal briefs unresolved after approve preflight fails', async () => {+ const unresolvedBrief = {+ id: 'proposal-2',+ metadata: { proposal: { ...proposalMetadata, status: 'stale' } },+ trigger: 'agent-signal:nightly-review',+ };+ const maintenanceProposalResolver = vi.fn().mockResolvedValue({+ brief: unresolvedBrief,+ shouldResolve: false,+ });+ const service = new BriefService(db, userId, { maintenanceProposalResolver });+ mockBriefModel.findById.mockResolvedValue({+ id: 'proposal-2',+ metadata: { proposal: proposalMetadata },+ trigger: 'agent-signal:nightly-review',+ });++ const result = await service.resolve('proposal-2', { action: 'approve' });++ expect(result).toBe(unresolvedBrief);+ expect(mockBriefModel.resolve).not.toHaveBeenCalled();+ });++ /**+ * @example+ * expect(maintenanceProposalResolver).toHaveBeenCalledWith(expect.objectContaining({ action: 'dismiss' }));+ */+ it('dismisses pending maintenance proposals through the proposal resolver', async () => {+ const maintenanceProposalResolver = vi.fn().mockResolvedValue({+ brief: { id: 'proposal-3' },+ shouldResolve: true,+ });+ const service = new BriefService(db, userId, { maintenanceProposalResolver });+ mockBriefModel.findById.mockResolvedValue({+ id: 'proposal-3',+ metadata: { proposal: proposalMetadata },+ trigger: 'agent-signal:nightly-review',+ });+ mockBriefModel.resolve.mockResolvedValue({ id: 'proposal-3', resolvedAction: 'dismiss' });++ await service.resolve('proposal-3', { action: 'dismiss' });++ expect(maintenanceProposalResolver).toHaveBeenCalledWith(+ expect.objectContaining({ action: 'dismiss' }),+ );+ expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-3', { action: 'dismiss' });+ });+it('should complete the task when approving a result brief on a non-scheduled task', async () => {const service = new BriefService(db, userId);mockBriefModel.resolve.mockResolvedValue({diff --git a/src/server/services/brief/index.ts b/src/server/services/brief/index.tsindex 0e3a9ea35b9..a73445d0438 100644--- a/src/server/services/brief/index.ts+++ b/src/server/services/brief/index.ts@@ -5,6 +5,9 @@ import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';import type { BriefItem } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/maintenance/brief';+import type { MaintenanceProposalMetadata } from '@/server/services/agentSignal/services/maintenance/proposal';+import { getMaintenanceProposalFromBriefMetadata } from '@/server/services/agentSignal/services/maintenance/proposal';export interface AgentAvatarInfo {avatar: string | null;@@ -22,21 +25,198 @@ export type BriefWithAgent = BriefItem & {taskStatus: TaskStatus | null;};+export interface MaintenanceProposalBriefResolutionInput {+ /** User action requested by the Daily Brief card. */+ action: 'approve' | 'dismiss';+ /** Brief row that stores the pending proposal metadata. */+ brief: BriefItem;+ /** Frozen proposal metadata extracted from the brief. */+ proposal: MaintenanceProposalMetadata;+}++export interface MaintenanceProposalBriefResolutionResult {+ /** Latest brief row after proposal metadata updates. */+ brief: BriefItem | null;+ /** Resolution action to store when it differs from the requested action. */+ resolveAction?: string;+ /** Resolve the brief after proposal handling succeeds. */+ shouldResolve: boolean;+}++export interface BriefServiceOptions {+ /** Optional override used by tests or alternate runtimes for Agent Signal proposal approval. */+ maintenanceProposalResolver?: (+ input: MaintenanceProposalBriefResolutionInput,+ ) => Promise<MaintenanceProposalBriefResolutionResult>;+}++const asMetadataRecord = (metadata: BriefItem['metadata']): Record<string, unknown> =>+ metadata && typeof metadata === 'object' && !Array.isArray(metadata)+ ? (metadata as Record<string, unknown>)+ : {};++const getOptionalString = (value: unknown): string | undefined =>+ typeof value === 'string' ? value : undefined;+export class BriefService {private agentModel: AgentModel;private briefModel: BriefModel;private db: LobeChatDatabase;+ private maintenanceProposalResolver?: BriefServiceOptions['maintenanceProposalResolver'];private taskModel: TaskModel;private userId: string;- constructor(db: LobeChatDatabase, userId: string) {+ constructor(db: LobeChatDatabase, userId: string, options: BriefServiceOptions = {}) {this.db = db;this.userId = userId;this.agentModel = new AgentModel(db, userId);this.briefModel = new BriefModel(db, userId);+ this.maintenanceProposalResolver = options.maintenanceProposalResolver;this.taskModel = new TaskModel(db, userId);}+ private async resolveMaintenanceProposalBrief(+ input: MaintenanceProposalBriefResolutionInput,+ ): Promise<MaintenanceProposalBriefResolutionResult> {+ if (this.maintenanceProposalResolver) return this.maintenanceProposalResolver(input);++ const { createBriefMaintenanceService } =+ await import('@/server/services/agentSignal/services/maintenance/brief');+ const { createMaintenanceExecutorService } =+ await import('@/server/services/agentSignal/services/maintenance/executor');+ const { createMaintenanceProposalApplyService } =+ await import('@/server/services/agentSignal/services/maintenance/proposalApply');+ const { createMaintenanceProposalPreflightService } =+ await import('@/server/services/agentSignal/services/maintenance/proposalPreflight');+ const { createSkillManagementService } =+ await import('@/server/services/agentSignal/services/maintenance/skill');+ const { createMaintenanceReviewReceipts, persistAgentSignalReceipts } =+ await import('@/server/services/agentSignal/services/receiptService');+ const { AgentSignalReviewContextModel } =+ await import('@/database/models/agentSignal/reviewContext');+ const { isAgentSignalEnabledForUser } =+ await import('@/server/services/agentSignal/featureGate');+ const { SkillManagementDocumentService } =+ await import('@/server/services/skillManagement/SkillManagementDocumentService');++ const { action, brief, proposal } = input;+ const metadata = asMetadataRecord(brief.metadata);+ const updateProposal = async (nextProposal: MaintenanceProposalMetadata) =>+ this.briefModel.updateMetadata(brief.id, { ...metadata, proposal: nextProposal });++ if (action === 'dismiss') {+ const now = new Date().toISOString();+ const updatedBrief = await updateProposal({+ ...proposal,+ status: 'dismissed',+ updatedAt: now,+ });++ return { brief: updatedBrief, shouldResolve: true };+ }++ if (!brief.agentId) return { brief, shouldResolve: false };++ const skillDocumentService = new SkillManagementDocumentService(this.db, this.userId);+ const preflight = createMaintenanceProposalPreflightService({+ readSkillTarget: (agentDocumentId) =>+ skillDocumentService.readSkillTargetSnapshot({+ agentDocumentId,+ agentId: brief.agentId ?? '',+ }),+ });+ const executor = createMaintenanceExecutorService({+ memory: {+ writeMemory: async () => {+ throw new Error('Memory proposal apply is not supported yet');+ },+ },+ skill: createSkillManagementService({+ refineSkill: async ({ input: skillInput }) => {+ const skillPayload = skillInput as unknown as Record<string, unknown>;+ const bodyMarkdown =+ getOptionalString(skillPayload.bodyMarkdown) ??+ skillInput.patch ??+ getOptionalString(skillPayload.content) ??+ '';+ const result = await skillDocumentService.replaceSkillIndex({+ agentId: brief.agentId ?? '',+ agentDocumentId: skillInput.skillDocumentId,+ bodyMarkdown,+ description: getOptionalString(skillPayload.description),+ });++ if (!result) throw new Error('Skill target not found');++ return {+ skillDocumentId: result.bundle.agentDocumentId,+ summary: `Refined managed skill ${result.name}.`,+ };+ },+ }),+ });+ const briefMaintenance = createBriefMaintenanceService();+ const applyService = createMaintenanceProposalApplyService({+ checkAction: preflight.checkAction,+ checkGates: () =>+ briefMaintenance.canApplyMaintenanceProposal({+ checkAgentGate: () =>+ new AgentSignalReviewContextModel(this.db, this.userId).canAgentRunSelfIteration(+ brief.agentId ?? '',+ ),+ checkServerGate: () => true,+ checkUserGate: () => isAgentSignalEnabledForUser(this.db, this.userId),+ }),+ executePlan: executor.execute,+ updateProposal: async (nextProposal) => {+ await updateProposal(nextProposal);+ },+ writeReceipts: async (receiptInput) => {+ await persistAgentSignalReceipts(createMaintenanceReviewReceipts(receiptInput));+ },+ });+ const sourceId =+ typeof metadata.sourceId === 'string'+ ? metadata.sourceId+ : `maintenance-proposal-approve:${brief.id}`;+ const applyInput = {+ agentId: brief.agentId,+ proposal,+ sourceId,+ sourceType: 'agent.maintenance_proposal.approved',+ userId: this.userId,+ ...(typeof metadata.localDate === 'string' ? { localDate: metadata.localDate } : {}),+ ...(typeof metadata.timezone === 'string' ? { timezone: metadata.timezone } : {}),+ };+ const result = await applyService.apply(applyInput);+ const updatedBrief = await this.briefModel.findById(brief.id);++ if (result.proposal.status === 'applied') {+ return { brief: updatedBrief, shouldResolve: true };+ }++ if (result.proposal.status === 'partially_failed') {+ return { brief: updatedBrief, resolveAction: 'approve_partial', shouldResolve: true };+ }++ return { brief: updatedBrief, shouldResolve: false };+ }++ private async maybeResolveMaintenanceProposalBrief(+ id: string,+ action: string | undefined,+ ): Promise<MaintenanceProposalBriefResolutionResult | undefined> {+ if (action !== 'approve' && action !== 'dismiss') return;++ const brief = await this.briefModel.findById(id);+ if (!brief || brief.trigger !== NIGHTLY_REVIEW_BRIEF_TRIGGER) return;++ const proposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);+ if (!proposal || proposal.status !== 'pending') return;++ return this.resolveMaintenanceProposalBrief({ action, brief, proposal });+ }+/*** Lightweight enrich for callers that only need the direct producing agent* (e.g. task detail, where the surrounding payload already covers task tree@@ -191,6 +371,16 @@ export class BriefService {id: string,options?: { action?: string; comment?: string },): Promise<BriefItem | null> {+ const proposalResult = await this.maybeResolveMaintenanceProposalBrief(id, options?.action);+ if (proposalResult) {+ if (!proposalResult.shouldResolve) return proposalResult.brief;++ return this.briefModel.resolve(id, {+ ...options,+ action: proposalResult.resolveAction ?? options?.action,+ });+ }+const brief = await this.briefModel.resolve(id, options);if (!brief) return null;diff --git a/src/server/services/skillManagement/SkillManagementDocumentService.test.ts b/src/server/services/skillManagement/SkillManagementDocumentService.test.tsindex 8524c613cef..835b9f55fb3 100644--- a/src/server/services/skillManagement/SkillManagementDocumentService.test.ts+++ b/src/server/services/skillManagement/SkillManagementDocumentService.test.ts@@ -24,9 +24,16 @@ import type { SkillAgentDocument } from './types';const now = new Date('2026-05-02T00:00:00.000Z');-const createSnapshot = async (content: string): Promise<AgentDocumentEditorSnapshot> => ({- content,- editorData: { markdown: content },+const createSnapshot = vi.fn(+ async (content: string): Promise<AgentDocumentEditorSnapshot> => ({+ content,+ editorData: { markdown: content, root: { children: [{ type: 'paragraph' }], type: 'root' } },+ }),+);++const expectedEditorData = (content: string) => ({+ markdown: content,+ root: { children: [{ type: 'paragraph' }], type: 'root' },});class InMemoryAgentDocumentModel implements SkillManagementAgentDocumentModel {@@ -319,6 +326,18 @@ describe('SkillManagementDocumentService', () => {}),}),);+ expect(agentDocumentModel.createCalls[1]).toEqual(+ expect.objectContaining({+ content: skillContent('release-writer', 'Writes release notes'),+ filename: SKILL_INDEX_FILENAME,+ params: expect.objectContaining({+ editorData: expectedEditorData(skillContent('release-writer', 'Writes release notes')),+ fileType: SKILL_INDEX_FILE_TYPE,+ parentId: 'document-1',+ policyLoad: PolicyLoad.DISABLED,+ }),+ }),+ );const detail = await service.getSkill({agentId: 'agent-1',@@ -361,6 +380,7 @@ describe('SkillManagementDocumentService', () => {expect(agentDocumentModel.documents).toHaveLength(2);expect(agentDocumentModel.documents.find((doc) => doc.id === source.id)).toEqual(expect.objectContaining({+ editorData: expectedEditorData(skillContent('draft-skill', 'Draft helper', '# Draft')),fileType: SKILL_INDEX_FILE_TYPE,filename: SKILL_INDEX_FILENAME,parentId: detail.bundle.documentId,@@ -465,6 +485,9 @@ describe('SkillManagementDocumentService', () => {expect.objectContaining({agentDocumentId: created.index.agentDocumentId,params: expect.objectContaining({+ editorData: expectedEditorData(+ skillContent('researcher', 'Researches docs better', '# Better'),+ ),metadata: {skill: { frontmatter: { description: 'Researches docs better', name: 'researcher' } },},@@ -553,6 +576,14 @@ describe('SkillManagementDocumentService', () => {created.index.documentId,'llm_call',);+ expect(agentDocumentModel.updateCalls.at(-1)).toEqual(+ expect.objectContaining({+ agentDocumentId: created.index.agentDocumentId,+ params: expect.objectContaining({+ editorData: expectedEditorData(skillContent('new-skill', 'Old description')),+ }),+ }),+ );});it('throws loudly when a bundle has no matching index document', async () => {diff --git a/src/server/services/skillManagement/SkillManagementDocumentService.ts b/src/server/services/skillManagement/SkillManagementDocumentService.tsindex 7c2bf4f7121..bdede2a2193 100644--- a/src/server/services/skillManagement/SkillManagementDocumentService.ts+++ b/src/server/services/skillManagement/SkillManagementDocumentService.ts@@ -1,8 +1,10 @@import type { LobeChatDatabase } from '@lobechat/database';+import { sha256 } from 'js-sha256';import { AgentDocumentModel, PolicyLoad } from '@/database/models/agentDocuments';import type { AgentDocumentEditorSnapshot } from '../agentDocuments/headlessEditor';+import { createMarkdownEditorSnapshot as createDefaultMarkdownEditorSnapshot } from '../agentDocuments/headlessEditor';import { DocumentService } from '../document';import {AGENT_SKILL_TEMPLATE_ID,@@ -29,6 +31,7 @@ import type {SkillDocumentRef,SkillSummary,SkillTargetInput,+ SkillTargetSnapshot,} from './types';type SkillManagementAgentDocumentModel = Pick<@@ -90,6 +93,7 @@ const buildSkillMetadata = (*/export class SkillManagementDocumentService {private agentDocumentModel: SkillManagementAgentDocumentModel;+ private createMarkdownEditorSnapshot: (content: string) => Promise<AgentDocumentEditorSnapshot>;private documentService: Pick<DocumentService, 'trySaveCurrentDocumentHistory'>;constructor(@@ -98,6 +102,8 @@ export class SkillManagementDocumentService {deps?: SkillManagementDocumentServiceDeps,) {this.agentDocumentModel = deps?.agentDocumentModel ?? new AgentDocumentModel(db, userId);+ this.createMarkdownEditorSnapshot =+ deps?.createMarkdownEditorSnapshot ?? createDefaultMarkdownEditorSnapshot;this.documentService = deps?.documentService ?? new DocumentService(db, userId);}@@ -124,6 +130,14 @@ export class SkillManagementDocumentService {});const frontmatter = parseSkillFrontmatter(normalizedContent);const metadata = buildSkillMetadata(frontmatter);+ // NOTICE:+ // Managed skill indexes are Markdown-backed, but document history snapshots are+ // editor-data-backed. Always keep `content` and `editorData` in sync so the next+ // automated skill refinement can save a pre-mutation `document_histories` row.+ // Root cause: older managed-skill writes only persisted Markdown content, which made+ // `DocumentService.trySaveCurrentDocumentHistory` no-op for `editorData = NULL`.+ // Removal condition: only if document history can snapshot Markdown content directly.+ const indexEditorSnapshot = await this.createMarkdownEditorSnapshot(normalizedContent);const duplicateBundles = (await this.agentDocumentModel.listByParentAndFilename(input.agentId, null, name)).filter((doc) => doc.fileType === SKILL_BUNDLE_FILE_TYPE);@@ -166,6 +180,7 @@ export class SkillManagementDocumentService {const index = await this.agentDocumentModel.convertAgentDocumentToSkillIndexWithTx(trx, {agentDocumentId: input.sourceAgentDocumentId,content: normalizedContent,+ editorData: indexEditorSnapshot.editorData,filename: SKILL_INDEX_FILENAME,metadata,parentId: bundle.documentId,@@ -187,6 +202,7 @@ export class SkillManagementDocumentService {SKILL_INDEX_FILENAME,normalizedContent,{+ editorData: indexEditorSnapshot.editorData,fileType: SKILL_INDEX_FILE_TYPE,metadata,parentId: bundle.documentId,@@ -266,6 +282,46 @@ export class SkillManagementDocumentService {return this.toSkillDetail(resolved, index, { includeContent: input.includeContent });}+ /**+ * Reads current managed skill state for proposal merge preflight.+ *+ * Use when:+ * - Agent Signal applies a previously-created maintenance proposal+ * - The apply path needs a compare-and-set guard before replacing skill content+ *+ * Expects:+ * - `agentDocumentId` may be either the skill bundle id or SKILL.md index id+ *+ * Returns:+ * - Current target snapshot, or `undefined` when the skill no longer exists+ */+ async readSkillTargetSnapshot(input: {+ agentDocumentId: string;+ agentId: string;+ }): Promise<SkillTargetSnapshot | undefined> {+ const detail = await this.getSkill({+ agentDocumentId: input.agentDocumentId,+ agentId: input.agentId,+ includeContent: true,+ });++ if (!detail) return undefined;++ // NOTICE:+ // The content hash is a compare-and-set guard for applying old maintenance proposals.+ // It intentionally hashes the current normalized SKILL.md content from the skill-management+ // service so approve/apply can reject proposals when the user or another agent changed the+ // target after the proposal was created.+ return {+ agentDocumentId: detail.bundle.agentDocumentId,+ contentHash: `sha256:${sha256(detail.content ?? '')}`,+ documentId: detail.bundle.documentId,+ managed: true,+ targetTitle: detail.title,+ writable: true,+ };+ }+/*** Replaces a managed skill index while preserving document ids.*@@ -293,6 +349,13 @@ export class SkillManagementDocumentService {});const frontmatter = parseSkillFrontmatter(normalizedContent);const metadata = buildSkillMetadata(frontmatter);+ // NOTICE:+ // The replacement body must be projected into editor data before updating the backing+ // document. Without this, history capture works for ordinary agent documents but silently+ // skips managed skills because there is no valid editor state to snapshot.+ // Root cause: `document_histories.editor_data` stores editor snapshots, not Markdown.+ // Removal condition: only if document history can snapshot Markdown content directly.+ const editorSnapshot = await this.createMarkdownEditorSnapshot(normalizedContent);await this.documentService.trySaveCurrentDocumentHistory(index.documentId, 'llm_call');const updatedBundle =@@ -301,6 +364,7 @@ export class SkillManagementDocumentService {})) ?? resolved;await this.agentDocumentModel.update(index.id, {content: normalizedContent,+ editorData: editorSnapshot.editorData,metadata,policyLoad: PolicyLoad.DISABLED,});@@ -338,6 +402,7 @@ export class SkillManagementDocumentService {});const frontmatter = parseSkillFrontmatter(normalizedContent);const metadata = buildSkillMetadata(frontmatter);+ const editorSnapshot = await this.createMarkdownEditorSnapshot(normalizedContent);if (normalizedContent !== index.content) {await this.documentService.trySaveCurrentDocumentHistory(index.documentId, 'llm_call');@@ -357,6 +422,7 @@ export class SkillManagementDocumentService {});await this.agentDocumentModel.update(index.id, {content: normalizedContent,+ editorData: editorSnapshot.editorData,metadata,policyLoad: PolicyLoad.DISABLED,});diff --git a/src/server/services/skillManagement/types.ts b/src/server/services/skillManagement/types.tsindex 1d859ad9e1b..2ef59e5d784 100644--- a/src/server/services/skillManagement/types.ts+++ b/src/server/services/skillManagement/types.ts@@ -52,6 +52,22 @@ export interface SkillDetail extends SkillSummary {frontmatter: SkillFrontmatter;}+/** Current managed skill target snapshot used by proposal merge preflight checks. */+export interface SkillTargetSnapshot {+ /** Managed skill bundle agent document id. */+ agentDocumentId: string;+ /** Compare-and-set hash of the current SKILL.md content. */+ contentHash?: string;+ /** Managed skill bundle backing document id. */+ documentId?: string;+ /** Whether the target is still managed by the skill-management service. */+ managed: boolean;+ /** Human-readable skill title. */+ targetTitle?: string;+ /** Whether the target can currently be mutated. */+ writable: boolean;+}+/*** Input used to list managed skill bundles for an agent.*/diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsindex f2a29de4a29..26738121715 100644--- a/src/server/workflows/agentSignal/__tests__/run.test.ts+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -57,6 +57,13 @@ const createNightlyReviewContext = (input: {},maintenanceSignals: [],managedSkills: [],+ proposalActivity: {+ active: [],+ dismissedCount: 0,+ expiredCount: 0,+ staleCount: 0,+ supersededCount: 0,+ },receiptActivity: {appliedCount: 0,duplicateGroups: [],@@ -812,17 +819,14 @@ describe('runAgentSignalWorkflow', () => {userId,}),),- executePlan: vi.fn(async () => ({ actions: [], status: ReviewRunStatus.Completed })),- planReviewOutput: vi.fn(() => ({- actions: [],- plannerVersion: 'test',- reviewScope: MaintenanceReviewScope.Nightly,- summary: 'Noop',- })),runMaintenanceReviewAgent: vi.fn(async () => ({- actions: [],- findings: [],- summary: 'Noop',+ execution: { actions: [], status: ReviewRunStatus.Completed },+ projectionPlan: {+ actions: [],+ plannerVersion: 'test',+ reviewScope: MaintenanceReviewScope.Nightly,+ summary: 'Noop',+ },})),};const createNightlyReviewPolicyOptions: NonNullable<