Skip to content

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

⚡️ perf(agent-signal,prompts,types,database,server): fixed many minor self-review issues, harden the structure, verified with eval (#14647)

Nekoccc8ee131510
diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.ts
index 6a1b181a0ba..92e78b0b3c0 100644
--- a/packages/database/src/models/agentSignal/reviewContext.ts
+++ b/packages/database/src/models/agentSignal/reviewContext.ts
@@ -14,11 +14,6 @@ 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;
@@ -244,16 +239,8 @@ 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
- )
- `,
+ correctionCount: sql<number>`0`.mapWith(Number),
+ correctionIds: sql<string[]>`ARRAY[]::text[]`,
failedMessages: sql<AgentSignalFailedMessageSummary[]>`
COALESCE(
jsonb_agg(
@@ -316,16 +303,8 @@ 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
- )
- `,
+ correctionCount: sql<number>`0`.mapWith(Number),
+ correctionIds: sql<string[]>`ARRAY[]::text[]`,
failedMessages: sql<AgentSignalFailedMessageSummary[]>`
COALESCE(
jsonb_agg(
diff --git a/packages/database/src/schemas/task.ts b/packages/database/src/schemas/task.ts
index e02c2bab21b..055924d243c 100644
--- a/packages/database/src/schemas/task.ts
+++ b/packages/database/src/schemas/task.ts
@@ -1,4 +1,4 @@
-import type { BriefArtifacts } from '@lobechat/types';
+import type { BriefArtifacts, BriefMetadata } from '@lobechat/types';
import {
foreignKey,
index,
@@ -252,7 +252,7 @@ export const briefs = pgTable(
resolvedAt: timestamptz('resolved_at'),
trigger: varchar255('trigger'), // field for which module triggered the brief, e.g. task, agent, signal, etc.
- metadata: jsonb('metadata'), // freeform field for business and states.
+ metadata: jsonb('metadata').$type<BriefMetadata>(), // freeform field for business and states.
createdAt: createdAt(),
},
diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts
index 717ae3f8f7e..e77616248ef 100644
--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts
+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts
@@ -14,7 +14,9 @@ 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(
+ 'noop is silent and must not create a Daily Brief or proposal',
+ );
expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain(
'Auto-safe memory candidates must be explicit',
);
@@ -38,8 +40,28 @@ describe('agent signal nightly review prompt', () => {
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 proposalActivity for unresolved proposal refresh, stale proposal, and duplicate proposal checks',
+ 'Use proposalActivity for unresolved proposal refresh, stale proposal, duplicate proposal checks',
+ );
+ });
+
+ /**
+ * @example
+ * expect(prompt).toContain('write tools')
+ */
+ it('instructs nightly maintenance to use tools as the only mutation boundary', () => {
+ const prompt = createAgentSignalNightlyReviewMessages({ maintenanceSignals: [] })
+ .map((message) => message.content)
+ .join('\n');
+
+ expect(prompt).toContain('Mutations only count through write tools');
+ expect(prompt).toContain(
+ 'this structured review may only emit candidate write actions for the server maintenance runtime',
+ );
+ expect(prompt).toContain(
+ 'Never infer intent with regexp, keyword lists, or hard-coded content heuristics',
);
+ expect(prompt).toContain('refine_skill requires complete replacement bodyMarkdown');
+ expect(prompt).toContain('do not emit patch-only');
});
/**
@@ -68,9 +90,9 @@ describe('agent signal nightly review prompt', () => {
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('Proposal only: structural/destructive changes');
expect(system.content).toContain(
- 'Use safe write tools for mutations; every write tool performs freshness and idempotency checks',
+ 'Plan only mutations that can be routed through safe write tools',
);
});
diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts
index a99fa576450..0e0f2b692f3 100644
--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts
+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts
@@ -1,24 +1,32 @@
+const TOOL_FIRST_MAINTENANCE_RULES = [
+ 'Role: maintenance operator, not summarizer.',
+ 'Mutations only count through write tools; this structured review may only emit candidate write actions for the server maintenance runtime.',
+ 'Never infer intent with regexp, keyword lists, or hard-coded content heuristics.',
+ 'Use structured context only: maintenanceSignals, bounded evidence, read tool results, satisfaction, feedback, receipts, and proposal state.',
+ 'refine_skill requires complete replacement bodyMarkdown; do not emit patch-only or prose-only executable refinement payloads.',
+ 'Auto-apply only safe writes: non-structural full-body refine_skill when fresh, or additive create_skill when absent, complete, scoped, and strongly supported.',
+ 'Proposal only: structural/destructive changes, active proposal refresh/supersede/close, consolidation, deletion, move, rebind, split, merge, path/namespace/file-structure/activation changes.',
+].join(' ');
+
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, 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.',
+ TOOL_FIRST_MAINTENANCE_RULES,
+ 'Start from maintenanceSignals; inspect other buckets only when cited or when confirming noop.',
+ 'Use noop for ordinary successful days, weak/ambiguous evidence, or single-source telemetry; noop is silent and must not create a Daily Brief or proposal. Non-noop actions must cite digest evidenceRefs.',
'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.',
+ 'Do not re-judge satisfaction, sentiment, or user intent; feedbackActivity is already judged evidence and is only one feature.',
+ 'Tool activity alone must not trigger skill consolidation, creation, or refinement; it may support repeated workflow/failure signals only 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 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.',
+ 'documentActivity.skillBucket and hintIsSkill:true are primary evidence for skill maintenance, not automatic authorization; generalDocumentBucket cannot independently trigger skill maintenance.',
+ 'Use proposalActivity for unresolved proposal refresh, stale proposal, duplicate proposal checks, suppress, supersede, expire, or lifecycle explanation. Existing maintenance proposals are state, not fresh evidence.',
+ '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.',
'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.',
+ 'Plan only mutations that can be routed through safe write tools; 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 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.',
diff --git a/packages/types/src/brief/index.ts b/packages/types/src/brief/index.ts
index 9d5286b51a3..85737920974 100644
--- a/packages/types/src/brief/index.ts
+++ b/packages/types/src/brief/index.ts
@@ -49,3 +49,19 @@ export interface BriefArtifactDocument {
export interface BriefArtifacts {
documents?: BriefArtifactDocument[];
}
+
+/** Agent Signal-owned Brief metadata namespace. */
+export interface BriefAgentSignalMetadata {
+ /** Future Agent Signal domains can extend this namespace without top-level collisions. */
+ [key: string]: unknown;
+ /** Nightly self-review state written by Agent Signal maintenance runs. */
+ nightlySelfReview?: unknown;
+}
+
+/** Freeform Brief metadata namespaced by feature owner. */
+export interface BriefMetadata {
+ /** Other feature namespaces remain possible without schema churn. */
+ [key: string]: unknown;
+ /** Agent Signal extension metadata. */
+ agentSignal?: BriefAgentSignalMetadata;
+}
diff --git a/src/server/routers/lambda/brief.ts b/src/server/routers/lambda/brief.ts
index 7d728275461..36131002f20 100644
--- a/src/server/routers/lambda/brief.ts
+++ b/src/server/routers/lambda/brief.ts
@@ -5,6 +5,8 @@ import { BriefModel } from '@/database/models/brief';
import { TaskModel } from '@/database/models/task';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentSignalSelfReviewBriefService } from '@/server/services/agentSignal/services/briefs/selfReview';
+import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/maintenance/brief';
import { BriefService } from '@/server/services/brief';
const briefProcedure = authedProcedure.use(serverDatabase);
@@ -173,11 +175,22 @@ export const briefRouter = router({
)
.mutation(async ({ input, ctx }) => {
try {
- const service = new BriefService(ctx.serverDB, ctx.userId);
- const brief = await service.resolve(input.id, {
+ const model = new BriefModel(ctx.serverDB, ctx.userId);
+ const currentBrief = await model.findById(input.id);
+ if (!currentBrief) throw new TRPCError({ code: 'NOT_FOUND', message: 'Brief not found' });
+
+ const resolveOptions = {
action: input.action,
comment: input.comment,
- });
+ };
+ const brief =
+ currentBrief.trigger === NIGHTLY_REVIEW_BRIEF_TRIGGER
+ ? await new AgentSignalSelfReviewBriefService(ctx.serverDB, ctx.userId).resolve(
+ currentBrief,
+ resolveOptions,
+ )
+ : await new BriefService(ctx.serverDB, ctx.userId).resolve(input.id, resolveOptions);
+
if (!brief) throw new TRPCError({ code: 'NOT_FOUND', message: 'Brief not found' });
return { data: brief, message: 'Brief resolved', success: true };
} catch (error) {
diff --git a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts b/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts
index 39711c40a2b..7eae91712bb 100644
--- a/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts
+++ b/src/server/services/agentSignal/policies/reviewNightly/__tests__/nightlyReview.test.ts
@@ -11,6 +11,7 @@ import type {
} from '../../../runtime/middleware';
import type { MaintenanceAgentRunResult } from '../../../services/maintenance/agentRunner';
import type { NightlyReviewContext } from '../../../services/maintenance/nightlyCollector';
+import type { MaintenanceProposalPlan } from '../../../services/maintenance/proposal';
import type {
MaintenancePlan,
MaintenanceReviewRunResult,
@@ -194,9 +195,9 @@ describe('nightly review source handler', () => {
execution: {
actions: [
{
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1',
+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
status: MaintenanceActionStatus.Proposed,
- summary: 'Review the skill consolidation proposal.',
+ summary: 'Review the skill refinement proposal.',
},
],
status: ReviewRunStatus.Completed,
@@ -206,15 +207,33 @@ describe('nightly review source handler', () => {
actions: [
{
...reviewPlan.actions[0],
- actionType: 'proposal_only',
+ actionType: 'refine_skill',
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.',
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'sha256:workflow-summary',
+ documentId: 'doc-skill-doc-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ dedupeKey: 'refine_skill:skill-doc-1',
+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Use the updated workflow summary wording.',
+ skillDocumentId: 'skill-doc-1',
+ userId: 'user-1',
+ },
+ operation: 'refine',
+ },
+ rationale: 'Review the skill refinement proposal.',
risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'skill-doc-1' },
},
],
- } satisfies MaintenancePlan,
+ } satisfies MaintenanceProposalPlan,
})),
writeDailyBrief: vi.fn(async () => {
calls.push('brief');
@@ -233,14 +252,35 @@ 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:proposal_only:skill-doc-1:action',
+ id: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1:action',
}),
]);
expect(deps.writeDailyBrief).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'agent-1',
metadata: expect.objectContaining({
- evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ agentSignal: expect.objectContaining({
+ nightlySelfReview: expect.objectContaining({
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ maintenanceProposal: expect.objectContaining({
+ actions: [
+ expect.objectContaining({
+ actionType: 'refine_skill',
+ baseSnapshot: expect.objectContaining({
+ contentHash: 'sha256:workflow-summary',
+ }),
+ operation: expect.objectContaining({
+ domain: 'skill',
+ input: expect.objectContaining({
+ bodyMarkdown: 'Use the updated workflow summary wording.',
+ }),
+ operation: 'refine',
+ }),
+ }),
+ ],
+ }),
+ }),
+ }),
}),
trigger: 'agent-signal:nightly-review',
type: 'decision',
@@ -314,8 +354,12 @@ describe('nightly review source handler', () => {
expect(deps.writeDailyBrief).toHaveBeenCalledWith(
expect.objectContaining({
metadata: expect.objectContaining({
- actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
- outcome: 'applied',
+ agentSignal: expect.objectContaining({
+ nightlySelfReview: expect.objectContaining({
+ actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
+ outcome: 'applied',
+ }),
+ }),
}),
title: 'Agent self-review updated resources',
trigger: 'agent-signal:nightly-review',
@@ -355,7 +399,7 @@ describe('nightly review source handler', () => {
/**
* @example
- * expect(brief.metadata.proposal.actions[0].operation).toBeDefined();
+ * expect(brief.metadata.agentSignal.nightlySelfReview.maintenanceProposal.actions[0].operation).toBeDefined();
*/
it('projects frozen proposal action operations from the runner projection plan', async () => {
const proposedSkillPlan = {
@@ -364,21 +408,32 @@ describe('nightly review source handler', () => {
{
...reviewPlan.actions[0],
actionType: 'refine_skill',
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'sha256:workflow-summary',
+ documentId: 'doc-skill-doc-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
dedupeKey: 'refine_skill:skill-doc-1',
idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
operation: {
domain: 'skill',
input: {
- patch: 'Use the newer workflow summary wording.',
+ bodyMarkdown: 'Use the newer workflow summary wording.',
skillDocumentId: 'skill-doc-1',
userId: 'user-1',
},
operation: 'refine',
},
+ rationale: 'Review the workflow summary skill refinement.',
+ risk: MaintenanceRisk.Medium,
target: { skillDocumentId: 'skill-doc-1' },
},
],
- } satisfies MaintenancePlan;
+ } satisfies MaintenanceProposalPlan;
const deps = createDependencies({
runMaintenanceReviewAgent: vi.fn(async () => ({
execution: {
@@ -403,16 +458,20 @@ describe('nightly review source handler', () => {
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',
- }),
+ agentSignal: expect.objectContaining({
+ nightlySelfReview: expect.objectContaining({
+ maintenanceProposal: expect.objectContaining({
+ actions: [
+ expect.objectContaining({
+ actionType: 'refine_skill',
+ operation: expect.objectContaining({
+ domain: 'skill',
+ operation: 'refine',
+ }),
+ }),
+ ],
}),
- ],
+ }),
}),
}),
}),
@@ -431,9 +490,9 @@ describe('nightly review source handler', () => {
execution: {
actions: [
{
- idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:proposal_only:skill-doc-1',
+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
status: MaintenanceActionStatus.Proposed,
- summary: 'Review the skill consolidation proposal.',
+ summary: 'Review the skill refinement proposal.',
},
],
status: ReviewRunStatus.Completed,
@@ -443,15 +502,33 @@ describe('nightly review source handler', () => {
actions: [
{
...reviewPlan.actions[0],
- actionType: 'proposal_only',
+ actionType: 'refine_skill',
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.',
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'sha256:workflow-summary',
+ documentId: 'doc-skill-doc-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ dedupeKey: 'refine_skill:skill-doc-1',
+ idempotencyKey: 'nightly-review:user-1:agent-1:2026-05-04:refine_skill:skill-doc-1',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Use the updated workflow summary wording.',
+ skillDocumentId: 'skill-doc-1',
+ userId: 'user-1',
+ },
+ operation: 'refine',
+ },
+ rationale: 'Review the skill refinement proposal.',
risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'skill-doc-1' },
},
],
- } satisfies MaintenancePlan,
+ } satisfies MaintenanceProposalPlan,
})),
writeDailyBrief: vi.fn(async () => {
throw briefError;
diff --git a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts
index 4d21970ced5..0ccd4a418f5 100644
--- a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts
+++ b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts
@@ -6,11 +6,15 @@ 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 {
+ createBriefMaintenanceService,
+ getNightlySelfReviewBriefMetadata,
+} from '../../services/maintenance/brief';
import type {
CollectNightlyReviewContextInput,
NightlyReviewContext,
} from '../../services/maintenance/nightlyCollector';
+import type { MaintenanceProposalPlan } from '../../services/maintenance/proposal';
import type {
EvidenceRef,
MaintenancePlan,
@@ -230,6 +234,22 @@ const collectPlanEvidenceRefs = (plan: MaintenancePlan): EvidenceRef[] => {
return [...evidenceRefs.values()];
};
+const isMergeableProposalAction = (actionType: string) =>
+ actionType === 'create_skill' || actionType === 'refine_skill';
+
+const hasProjectionBaseSnapshot = (action: MaintenancePlan['actions'][number]) => {
+ if (!isMergeableProposalAction(action.actionType)) return true;
+
+ const actionWithSnapshot = action as MaintenancePlan['actions'][number] & {
+ baseSnapshot?: unknown;
+ };
+
+ return actionWithSnapshot.baseSnapshot !== undefined;
+};
+
+const isSnapshotAwareProposalPlan = (plan: MaintenancePlan): plan is MaintenanceProposalPlan =>
+ plan.actions.every(hasProjectionBaseSnapshot);
+
const writeNightlyReceipts = async (
deps: CreateNightlyReviewSourceHandlerDependencies,
receipts: AgentSignalReceipt[],
@@ -269,16 +289,18 @@ const writeNightlyBrief = async (
) => {
if (!deps.writeDailyBrief || !brief) return {};
+ const metadata = getNightlySelfReviewBriefMetadata(brief.metadata);
+
return tracer.startActiveSpan(
'agent_signal.nightly_review.write_brief',
{
attributes: {
'agent.signal.agent_id': brief.agentId ?? '',
- 'agent.signal.nightly.applied_count': brief.metadata.actionCounts.applied,
- 'agent.signal.nightly.failed_count': brief.metadata.actionCounts.failed,
- 'agent.signal.nightly.outcome': brief.metadata.outcome,
- 'agent.signal.nightly.proposed_count': brief.metadata.actionCounts.proposed,
- 'agent.signal.nightly.skipped_count': brief.metadata.actionCounts.skipped,
+ 'agent.signal.nightly.applied_count': metadata?.actionCounts.applied ?? 0,
+ 'agent.signal.nightly.failed_count': metadata?.actionCounts.failed ?? 0,
+ 'agent.signal.nightly.outcome': metadata?.outcome ?? 'unknown',
+ 'agent.signal.nightly.proposed_count': metadata?.actionCounts.proposed ?? 0,
+ 'agent.signal.nightly.skipped_count': metadata?.actionCounts.skipped ?? 0,
},
},
async (span) => {
@@ -466,6 +488,7 @@ export const createNightlyReviewSourceHandler = (
},
);
const plan = agentResult.projectionPlan;
+ const proposalPlan = isSnapshotAwareProposalPlan(plan) ? plan : undefined;
const execution = agentResult.execution;
const receipts = createMaintenanceReviewReceipts({
agentId: payload.agentId,
@@ -495,7 +518,7 @@ export const createNightlyReviewSourceHandler = (
agentId: payload.agentId,
evidenceRefs: collectPlanEvidenceRefs(plan),
localDate: payload.localDate,
- plan,
+ ...(proposalPlan ? { plan: proposalPlan } : {}),
result: executionWithReceipts,
reviewWindowEnd: payload.reviewWindowEnd,
reviewWindowStart: payload.reviewWindowStart,
diff --git a/src/server/services/agentSignal/services/briefs/selfReview.test.ts b/src/server/services/agentSignal/services/briefs/selfReview.test.ts
new file mode 100644
index 00000000000..082771da1cc
--- /dev/null
+++ b/src/server/services/agentSignal/services/briefs/selfReview.test.ts
@@ -0,0 +1,420 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BriefModel } from '@/database/models/brief';
+import type { BriefItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import {
+ AgentSignalSelfReviewBriefService,
+ type AgentSignalSelfReviewBriefServiceOptions,
+} from '@/server/services/agentSignal/services/briefs/selfReview';
+import { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/maintenance/brief';
+import { MaintenanceRisk } from '@/server/services/agentSignal/services/maintenance/types';
+
+const mockCanAgentRunSelfIteration = vi.hoisted(() => vi.fn());
+const mockIsAgentSignalEnabledForUser = vi.hoisted(() => vi.fn());
+const mockPersistAgentSignalReceipts = vi.hoisted(() => vi.fn());
+const mockReadWindow = vi.hoisted(() => vi.fn());
+const mockSkillDocumentService = vi.hoisted(() => ({
+ createSkill: vi.fn(),
+ getSkill: vi.fn(),
+ readSkillTargetSnapshot: vi.fn(),
+ replaceSkillIndex: vi.fn(),
+}));
+const mockBriefModel = vi.hoisted(() => ({
+ findById: vi.fn(),
+ resolve: vi.fn(),
+ updateMetadata: vi.fn(),
+}));
+const mockTaskModel = vi.hoisted(() => ({
+ findById: vi.fn(),
+ getUnlockedTasks: vi.fn(),
+ updateStatus: vi.fn(),
+}));
+const mockTryDedupe = vi.hoisted(() => vi.fn());
+const mockWriteWindow = vi.hoisted(() => vi.fn());
+
+vi.mock('@/database/models/brief', () => ({
+ BriefModel: vi.fn().mockImplementation(() => mockBriefModel),
+}));
+
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn().mockImplementation(() => mockTaskModel),
+}));
+
+vi.mock('@/database/models/agentSignal/reviewContext', () => ({
+ AgentSignalReviewContextModel: vi.fn().mockImplementation(() => ({
+ canAgentRunSelfIteration: mockCanAgentRunSelfIteration,
+ })),
+}));
+
+vi.mock('@/server/services/agentSignal/featureGate', () => ({
+ isAgentSignalEnabledForUser: mockIsAgentSignalEnabledForUser,
+}));
+
+vi.mock('@/server/services/agentSignal/services/receiptService', () => ({
+ createMaintenanceReviewReceipts: vi.fn(() => []),
+ persistAgentSignalReceipts: mockPersistAgentSignalReceipts,
+}));
+
+vi.mock('@/server/services/agentSignal/store/adapters/redis/sourceEventStore', () => ({
+ redisSourceEventStore: {
+ readWindow: mockReadWindow,
+ tryDedupe: mockTryDedupe,
+ writeWindow: mockWriteWindow,
+ },
+}));
+
+vi.mock('@/server/services/skillManagement/SkillManagementDocumentService', () => ({
+ SkillManagementDocumentService: vi.fn().mockImplementation(() => mockSkillDocumentService),
+}));
+
+vi.mock('@/server/services/taskRunner', () => ({
+ TaskRunnerService: vi.fn().mockImplementation(() => ({
+ cascadeOnCompletion: vi.fn().mockResolvedValue({ failed: [], paused: [], started: [] }),
+ })),
+}));
+
+describe('AgentSignalSelfReviewBriefService', () => {
+ const db = {} as LobeChatDatabase;
+ const userId = 'user-1';
+ 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,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (BriefModel as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => mockBriefModel);
+ mockTaskModel.getUnlockedTasks.mockResolvedValue([]);
+ mockBriefModel.findById.mockResolvedValue(null);
+ mockCanAgentRunSelfIteration.mockResolvedValue(true);
+ mockIsAgentSignalEnabledForUser.mockResolvedValue(true);
+ mockPersistAgentSignalReceipts.mockResolvedValue(undefined);
+ mockReadWindow.mockResolvedValue(undefined);
+ mockSkillDocumentService.createSkill.mockResolvedValue({
+ bundle: { agentDocumentId: 'adoc_created' },
+ name: 'code-review',
+ });
+ mockSkillDocumentService.getSkill.mockResolvedValue(undefined);
+ mockSkillDocumentService.readSkillTargetSnapshot.mockResolvedValue(undefined);
+ mockSkillDocumentService.replaceSkillIndex.mockResolvedValue(undefined);
+ mockTryDedupe.mockResolvedValue(true);
+ mockWriteWindow.mockResolvedValue(undefined);
+ });
+
+ const resolveWithMaintenanceProposal = async (
+ id: string,
+ options?: { action?: string; comment?: string },
+ maintenanceProposalResolver?: AgentSignalSelfReviewBriefServiceOptions['maintenanceProposalResolver'],
+ ) => {
+ const brief = (await mockBriefModel.findById(id)) as BriefItem | null;
+ if (!brief) return null;
+
+ return new AgentSignalSelfReviewBriefService(db, userId, {
+ maintenanceProposalResolver,
+ }).resolve(brief, options);
+ };
+
+ /**
+ * @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,
+ });
+ mockBriefModel.findById.mockResolvedValue({
+ id: 'proposal-1',
+ metadata: { proposal: proposalMetadata },
+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ });
+ mockBriefModel.resolve.mockResolvedValue({ id: 'proposal-1', resolvedAction: 'approve' });
+
+ const result = await resolveWithMaintenanceProposal(
+ 'proposal-1',
+ { action: 'approve' },
+ maintenanceProposalResolver,
+ );
+
+ 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: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ };
+ const maintenanceProposalResolver = vi.fn().mockResolvedValue({
+ brief: unresolvedBrief,
+ shouldResolve: false,
+ });
+ mockBriefModel.findById.mockResolvedValue({
+ id: 'proposal-2',
+ metadata: { proposal: proposalMetadata },
+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ });
+
+ const result = await resolveWithMaintenanceProposal(
+ 'proposal-2',
+ { action: 'approve' },
+ maintenanceProposalResolver,
+ );
+
+ 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,
+ });
+ mockBriefModel.findById.mockResolvedValue({
+ id: 'proposal-3',
+ metadata: { proposal: proposalMetadata },
+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ });
+ mockBriefModel.resolve.mockResolvedValue({ id: 'proposal-3', resolvedAction: 'dismiss' });
+
+ await resolveWithMaintenanceProposal(
+ 'proposal-3',
+ { action: 'dismiss' },
+ maintenanceProposalResolver,
+ );
+
+ expect(maintenanceProposalResolver).toHaveBeenCalledWith(
+ expect.objectContaining({ action: 'dismiss' }),
+ );
+ expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-3', { action: 'dismiss' });
+ });
+
+ /**
+ * @example
+ * expect(mockSkillDocumentService.createSkill).toHaveBeenCalledWith(expect.objectContaining({ name: 'code-review' }));
+ */
+ it('applies fresh create_skill maintenance proposals through the default approve resolver', async () => {
+ const createProposalMetadata = {
+ ...proposalMetadata,
+ actionType: 'create_skill' as const,
+ actions: [
+ {
+ actionType: 'create_skill' as const,
+ baseSnapshot: {
+ absent: true,
+ skillName: 'code-review',
+ targetType: 'skill' as const,
+ },
+ evidenceRefs: [],
+ idempotencyKey: 'nightly:create:code-review',
+ operation: {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: 'Review preferences',
+ description: 'Reusable review preferences.',
+ name: 'code-review',
+ title: 'Code Review',
+ userId,
+ },
+ operation: 'create' as const,
+ },
+ rationale: 'Create a managed skill.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillName: 'code-review' },
+ },
+ ],
+ proposalKey: 'agt_1:create_skill:skill:code-review',
+ };
+ const pendingBrief = {
+ agentId: 'agt_1',
+ id: 'proposal-create',
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ localDate: '2026-05-09',
+ maintenanceProposal: createProposalMetadata,
+ sourceId: 'source-create',
+ timezone: 'Asia/Shanghai',
+ },
+ },
+ },
+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ };
+
+ mockBriefModel.findById.mockResolvedValueOnce(pendingBrief).mockResolvedValueOnce({
+ ...pendingBrief,
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: { status: 'applied' },
+ },
+ },
+ },
+ });
+ mockBriefModel.updateMetadata.mockResolvedValue(pendingBrief);
+ mockBriefModel.resolve.mockResolvedValue({
+ id: 'proposal-create',
+ resolvedAction: 'approve',
+ });
+
+ const result = await resolveWithMaintenanceProposal('proposal-create', { action: 'approve' });
+
+ expect(mockSkillDocumentService.getSkill).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ name: 'code-review',
+ });
+ expect(mockSkillDocumentService.createSkill).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ bodyMarkdown: 'Review preferences',
+ description: 'Reusable review preferences.',
+ name: 'code-review',
+ title: 'Code Review',
+ });
+ expect(mockReadWindow).toHaveBeenCalledWith('maintenance-operation:nightly:create:code-review');
+ expect(mockTryDedupe).toHaveBeenCalledWith(
+ 'maintenance-operation-reserve:nightly:create:code-review',
+ expect.any(Number),
+ );
+ expect(mockPersistAgentSignalReceipts).toHaveBeenCalledWith([
+ expect.objectContaining({
+ agentId: 'agt_1',
+ id: 'nightly:create:code-review',
+ kind: 'skill',
+ sourceId: 'source-create',
+ sourceType: 'agent.maintenance_proposal.approved',
+ status: 'applied',
+ topicId: 'source-create',
+ userId,
+ }),
+ ]);
+ expect(mockWriteWindow).toHaveBeenCalledWith(
+ 'maintenance-operation:nightly:create:code-review',
+ {
+ result: JSON.stringify({
+ receiptId: 'nightly:create:code-review',
+ resourceId: 'adoc_created',
+ status: 'applied',
+ summary: 'Created managed skill code-review.',
+ }),
+ },
+ expect.any(Number),
+ );
+ expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-create', {
+ action: 'approve',
+ });
+ expect(result).toEqual({ id: 'proposal-create', resolvedAction: 'approve' });
+ });
+
+ /**
+ * @example
+ * expect(mockSkillDocumentService.createSkill).not.toHaveBeenCalled();
+ */
+ it('dedupes repeated create_skill approvals through the maintenance operation reservation', async () => {
+ const createProposalMetadata = {
+ ...proposalMetadata,
+ actionType: 'create_skill' as const,
+ actions: [
+ {
+ actionType: 'create_skill' as const,
+ baseSnapshot: {
+ absent: true,
+ skillName: 'code-review',
+ targetType: 'skill' as const,
+ },
+ evidenceRefs: [],
+ idempotencyKey: 'nightly:create:code-review',
+ operation: {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: 'Review preferences',
+ description: 'Reusable review preferences.',
+ name: 'code-review',
+ title: 'Code Review',
+ userId,
+ },
+ operation: 'create' as const,
+ },
+ rationale: 'Create a managed skill.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillName: 'code-review' },
+ },
+ ],
+ proposalKey: 'agt_1:create_skill:skill:code-review',
+ };
+ const pendingBrief = {
+ agentId: 'agt_1',
+ id: 'proposal-create',
+ metadata: {
+ proposal: createProposalMetadata,
+ sourceId: 'source-create',
+ },
+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ };
+ mockReadWindow.mockResolvedValue({
+ result: JSON.stringify({
+ receiptId: 'nightly:create:code-review',
+ resourceId: 'adoc_created',
+ status: 'applied',
+ summary: 'Already created.',
+ }),
+ });
+ mockBriefModel.findById
+ .mockResolvedValueOnce(pendingBrief)
+ .mockResolvedValueOnce({ ...pendingBrief, metadata: { proposal: { status: 'applied' } } });
+ mockBriefModel.updateMetadata.mockResolvedValue(pendingBrief);
+ mockBriefModel.resolve.mockResolvedValue({
+ id: 'proposal-create',
+ resolvedAction: 'approve',
+ });
+
+ const result = await resolveWithMaintenanceProposal('proposal-create', { action: 'approve' });
+
+ expect(mockSkillDocumentService.createSkill).not.toHaveBeenCalled();
+ expect(mockTryDedupe).not.toHaveBeenCalled();
+ expect(mockPersistAgentSignalReceipts).toHaveBeenCalledWith([
+ expect.objectContaining({
+ id: 'nightly:create:code-review',
+ kind: 'skill',
+ sourceType: 'agent.maintenance_proposal.approved',
+ status: 'skipped',
+ }),
+ ]);
+ expect(mockWriteWindow).not.toHaveBeenCalled();
+ expect(mockBriefModel.resolve).toHaveBeenCalledWith('proposal-create', {
+ action: 'approve',
+ });
+ expect(result).toEqual({ id: 'proposal-create', resolvedAction: 'approve' });
+ });
+});
diff --git a/src/server/services/agentSignal/services/briefs/selfReview.ts b/src/server/services/agentSignal/services/briefs/selfReview.ts
new file mode 100644
index 00000000000..5f35e1c970a
--- /dev/null
+++ b/src/server/services/agentSignal/services/briefs/selfReview.ts
@@ -0,0 +1,429 @@
+import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
+import { BriefModel } from '@/database/models/brief';
+import type { BriefItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { AGENT_SIGNAL_DEFAULTS } from '@/server/services/agentSignal/constants';
+import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
+import {
+ createBriefMaintenanceService,
+ getNightlySelfReviewBriefMetadata,
+ 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';
+import { createMaintenanceProposalApplyService } from '@/server/services/agentSignal/services/maintenance/proposalApply';
+import { createMaintenanceProposalPreflightService } from '@/server/services/agentSignal/services/maintenance/proposalPreflight';
+import {
+ createMaintenanceTools,
+ type MaintenanceToolOperationReservation,
+ type MaintenanceToolReceiptInput,
+ type MaintenanceToolWriteResult,
+} from '@/server/services/agentSignal/services/maintenance/tools';
+import { MaintenanceRisk } from '@/server/services/agentSignal/services/maintenance/types';
+import { persistAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';
+import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';
+import type { BriefResolveOptions } from '@/server/services/brief';
+import { BriefService } from '@/server/services/brief';
+import { SkillManagementDocumentService } from '@/server/services/skillManagement/SkillManagementDocumentService';
+
+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 AgentSignalSelfReviewBriefServiceOptions {
+ /** Optional override used by tests or alternate runtimes for Agent Signal proposal approval. */
+ maintenanceProposalResolver?: (
+ input: MaintenanceProposalBriefResolutionInput,
+ ) => Promise<MaintenanceProposalBriefResolutionResult>;
+}
+
+const asMetadataRecord = (metadata: unknown): Record<string, unknown> =>
+ metadata && typeof metadata === 'object' && !Array.isArray(metadata)
+ ? (metadata as Record<string, unknown>)
+ : {};
+
+const MAINTENANCE_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;
+const MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE = 'agent.maintenance_proposal.approved';
+
+const maintenanceOperationScopeKey = (idempotencyKey: string) =>
+ `maintenance-operation:${idempotencyKey}`;
+
+const maintenanceOperationReserveKey = (idempotencyKey: string) =>
+ `maintenance-operation-reserve:${idempotencyKey}`;
+
+const parseStoredOperationResult = (
+ payload: Record<string, string> | undefined,
+): MaintenanceToolWriteResult | undefined => {
+ if (!payload?.result) return;
+
+ try {
+ const result = JSON.parse(payload.result) as MaintenanceToolWriteResult;
+
+ if (
+ result.status === 'applied' ||
+ result.status === 'deduped' ||
+ result.status === 'failed' ||
+ result.status === 'proposed' ||
+ result.status === 'skipped_stale' ||
+ result.status === 'skipped_unsupported'
+ ) {
+ return result;
+ }
+ } catch {
+ return;
+ }
+};
+
+const createSkippedOperationResult = (): MaintenanceToolWriteResult => ({
+ status: 'skipped_unsupported',
+ summary:
+ 'Maintenance operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',
+});
+
+const getToolReceiptStatus = (
+ status: MaintenanceToolReceiptInput['status'],
+): 'applied' | 'failed' | 'proposed' | 'skipped' => {
+ if (status === 'applied') return 'applied';
+ if (status === 'failed') return 'failed';
+ if (status === 'proposed') return 'proposed';
+
+ return 'skipped';
+};
+
+/**
+ * Resolves Agent Signal self-review Daily Brief actions.
+ *
+ * Use when:
+ * - API boundaries resolve Daily Briefs that may contain Agent Signal maintenance proposals
+ * - Approve/dismiss must run self-review proposal preflight before normal brief resolution
+ *
+ * Expects:
+ * - `db` and `userId` belong to the current authenticated request
+ * - The API boundary has already dispatched by `brief.trigger`
+ *
+ * Returns:
+ * - The updated brief row, or `null` when the brief does not exist
+ *
+ * Call stack:
+ *
+ * briefRouter.resolve
+ * -> {@link AgentSignalSelfReviewBriefService.resolve}
+ * -> {@link AgentSignalSelfReviewBriefService.resolveMaintenanceProposalIfPending}
+ * -> {@link BriefService.resolve}
+ */
+export class AgentSignalSelfReviewBriefService {
+ private briefService: BriefService;
+ private briefModel: BriefModel;
+ private db: LobeChatDatabase;
+ private maintenanceProposalResolver?: AgentSignalSelfReviewBriefServiceOptions['maintenanceProposalResolver'];
+ private userId: string;
+
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ options: AgentSignalSelfReviewBriefServiceOptions = {},
+ ) {
+ this.db = db;
+ this.userId = userId;
+ this.briefService = new BriefService(db, userId);
+ this.briefModel = new BriefModel(db, userId);
+ this.maintenanceProposalResolver = options.maintenanceProposalResolver;
+ }
+
+ /**
+ * Resolves a self-review brief with proposal handling when applicable.
+ *
+ * Use when:
+ * - A trigger dispatch boundary selected `agent-signal:nightly-review`
+ * - A user clicked approve, dismiss, or another generic brief action
+ *
+ * Expects:
+ * - `brief` was already loaded by the trigger dispatch boundary
+ * - `options.action` may be any generic brief action
+ *
+ * Returns:
+ * - The resolved or still-pending brief row
+ */
+ async resolve(brief: BriefItem, options?: BriefResolveOptions): Promise<BriefItem | null> {
+ const proposalResult = await this.resolveMaintenanceProposalIfPending(brief, options?.action);
+
+ if (proposalResult) {
+ if (!proposalResult.shouldResolve) return proposalResult.brief;
+
+ return this.briefService.resolve(brief.id, {
+ ...options,
+ action: proposalResult.resolveAction ?? options?.action,
+ });
+ }
+
+ return this.briefService.resolve(brief.id, options);
+ }
+
+ private async resolveMaintenanceProposalIfPending(
+ brief: BriefItem,
+ action?: string,
+ ): Promise<MaintenanceProposalBriefResolutionResult | undefined> {
+ if (brief.trigger !== NIGHTLY_REVIEW_BRIEF_TRIGGER) return;
+ const proposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);
+ if (!proposal || proposal.status !== 'pending') return;
+ if (action !== 'approve' && action !== 'dismiss') return;
+ const proposalAction: MaintenanceProposalBriefResolutionInput['action'] = action;
+
+ const input = { action: proposalAction, brief, proposal };
+ if (this.maintenanceProposalResolver) return this.maintenanceProposalResolver(input);
+
+ return this.resolveMaintenanceProposal(input);
+ }
+
+ private async resolveMaintenanceProposal({
+ action,
+ brief,
+ proposal,
+ }: MaintenanceProposalBriefResolutionInput): Promise<MaintenanceProposalBriefResolutionResult> {
+ if (action === 'dismiss') {
+ const updatedBrief = await this.updateProposal(brief, {
+ ...proposal,
+ status: 'dismissed',
+ updatedAt: new Date().toISOString(),
+ });
+
+ return { brief: updatedBrief, shouldResolve: true };
+ }
+
+ if (!brief.agentId) return { brief, shouldResolve: false };
+
+ const metadata = getNightlySelfReviewBriefMetadata(brief.metadata);
+ const sourceId =
+ typeof metadata?.sourceId === 'string'
+ ? metadata.sourceId
+ : `maintenance-proposal-approve:${brief.id}`;
+ const skillDocumentService = new SkillManagementDocumentService(this.db, this.userId);
+ const preflight = createMaintenanceProposalPreflightService({
+ isSkillNameAvailable: async ({ name }) => {
+ const skill = await skillDocumentService.getSkill({
+ agentId: brief.agentId ?? '',
+ name,
+ });
+
+ return !skill;
+ },
+ readSkillTargetSnapshot: (agentDocumentId) =>
+ skillDocumentService.readSkillTargetSnapshot({
+ agentDocumentId,
+ agentId: brief.agentId ?? '',
+ }),
+ });
+ const tools = createMaintenanceTools({
+ createSkill: async (toolInput) => {
+ const result = await skillDocumentService.createSkill({
+ agentId: brief.agentId ?? '',
+ bodyMarkdown: toolInput.bodyMarkdown,
+ description: toolInput.description ?? '',
+ name: toolInput.name,
+ title: toolInput.title ?? toolInput.name,
+ });
+
+ return {
+ resourceId: result.bundle.agentDocumentId,
+ summary: `Created managed skill ${result.name}.`,
+ };
+ },
+ preflight: async (toolInput) => {
+ if (!('baseSnapshot' in toolInput) || !('skillDocumentId' in toolInput)) {
+ return { allowed: false, reason: 'Unsupported maintenance preflight target.' };
+ }
+
+ const result = await preflight.checkAction({
+ actionType: 'refine_skill',
+ baseSnapshot: toolInput.baseSnapshot,
+ evidenceRefs: [],
+ idempotencyKey: toolInput.idempotencyKey,
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: toolInput.bodyMarkdown,
+ skillDocumentId: toolInput.skillDocumentId,
+ userId: toolInput.userId,
+ },
+ operation: 'refine',
+ },
+ rationale: toolInput.summary ?? 'Apply approved maintenance proposal.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: toolInput.skillDocumentId },
+ });
+
+ return result.allowed ? { allowed: true } : { allowed: false, reason: result.reason };
+ },
+ replaceSkill: async (toolInput) => {
+ const result = await skillDocumentService.replaceSkillIndex({
+ agentId: brief.agentId ?? '',
+ agentDocumentId: toolInput.skillDocumentId,
+ bodyMarkdown: toolInput.bodyMarkdown,
+ description: toolInput.description,
+ });
+
+ if (!result) throw new Error('Skill target not found');
+
+ return {
+ resourceId: result.bundle.agentDocumentId,
+ summary: `Refined managed skill ${result.name}.`,
+ };
+ },
+ reserveOperation: async (
+ idempotencyKey: string,
+ ): Promise<MaintenanceToolOperationReservation> => {
+ const scopeKey = maintenanceOperationScopeKey(idempotencyKey);
+ const existing = parseStoredOperationResult(
+ await redisSourceEventStore.readWindow(scopeKey),
+ );
+
+ if (existing) return { existing, reserved: false };
+
+ // NOTICE:
+ // Redis is the only cross-request idempotency boundary available for Daily Brief
+ // proposal approvals. If reservation fails or Redis is unavailable, skip mutation instead
+ // of applying without a durable operation record.
+ // Root cause summary: approve is a user-triggered HTTP path and can be clicked twice or
+ // race across workers.
+ // Source/context: mirrors `reserveMaintenanceOperation` in
+ // `src/server/services/agentSignal/services/maintenance/serverRuntime.ts`.
+ // Removal condition: replace with a database-backed maintenance operation ledger.
+ const reserved = await redisSourceEventStore.tryDedupe(
+ maintenanceOperationReserveKey(idempotencyKey),
+ MAINTENANCE_OPERATION_STATE_TTL_SECONDS,
+ );
+
+ if (reserved) return { reserved: true };
+
+ return {
+ existing:
+ parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ??
+ createSkippedOperationResult(),
+ reserved: false,
+ };
+ },
+ writeReceipt: async (toolInput) => {
+ await persistAgentSignalReceipts([
+ {
+ agentId: brief.agentId ?? '',
+ createdAt: Date.now(),
+ detail:
+ toolInput.summary ??
+ `Maintenance tool ${toolInput.toolName} finished with ${toolInput.status}.`,
+ id: toolInput.idempotencyKey,
+ kind:
+ toolInput.toolName === 'createSkillIfAbsent' ||
+ toolInput.toolName === 'replaceSkillContentCAS'
+ ? 'skill'
+ : 'maintenance',
+ metadata: {
+ sourceType: MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE,
+ },
+ sourceId,
+ sourceType: MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE,
+ status: getToolReceiptStatus(toolInput.status),
+ ...(toolInput.resourceId &&
+ (toolInput.toolName === 'createSkillIfAbsent' ||
+ toolInput.toolName === 'replaceSkillContentCAS')
+ ? {
+ target: {
+ id: toolInput.resourceId,
+ ...(toolInput.summary ? { summary: toolInput.summary } : {}),
+ title: toolInput.summary ?? toolInput.resourceId,
+ type: 'skill',
+ },
+ }
+ : {}),
+ title: toolInput.summary ?? 'Maintenance tool outcome',
+ topicId: sourceId,
+ userId: this.userId,
+ },
+ ]);
+
+ return { receiptId: toolInput.idempotencyKey };
+ },
+ completeOperation: async (toolInput) => {
+ await redisSourceEventStore.writeWindow(
+ maintenanceOperationScopeKey(toolInput.idempotencyKey),
+ {
+ result: JSON.stringify({
+ ...(toolInput.receiptId ? { receiptId: toolInput.receiptId } : {}),
+ ...(toolInput.resourceId ? { resourceId: toolInput.resourceId } : {}),
+ status: toolInput.status,
+ ...(toolInput.summary ? { summary: toolInput.summary } : {}),
+ } satisfies MaintenanceToolWriteResult),
+ },
+ MAINTENANCE_OPERATION_STATE_TTL_SECONDS,
+ );
+ },
+ });
+ 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),
+ }),
+ tools,
+ updateProposal: async (nextProposal) => {
+ await this.updateProposal(brief, nextProposal);
+ },
+ });
+ const result = await applyService.apply({
+ agentId: brief.agentId,
+ proposal,
+ sourceId,
+ sourceType: MAINTENANCE_PROPOSAL_APPROVED_SOURCE_TYPE,
+ userId: this.userId,
+ ...(typeof metadata?.localDate === 'string' ? { localDate: metadata.localDate } : {}),
+ ...(typeof metadata?.timezone === 'string' ? { timezone: metadata.timezone } : {}),
+ });
+ 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 updateProposal(brief: BriefItem, nextProposal: MaintenanceProposalMetadata) {
+ const metadata = asMetadataRecord(brief.metadata);
+ const agentSignal = asMetadataRecord(metadata.agentSignal);
+ const nightlySelfReview = asMetadataRecord(agentSignal.nightlySelfReview);
+
+ return this.briefModel.updateMetadata(brief.id, {
+ ...metadata,
+ agentSignal: {
+ ...agentSignal,
+ nightlySelfReview: {
+ ...nightlySelfReview,
+ maintenanceProposal: nextProposal,
+ },
+ },
+ });
+ }
+}
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/agent.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/agent.test.ts
new file mode 100644
index 00000000000..9e40fce585f
--- /dev/null
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/agent.test.ts
@@ -0,0 +1,432 @@
+// @vitest-environment node
+import type { ChatMethodOptions, ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
+import type * as ModelRuntimeModule from '@lobechat/model-runtime';
+import { consumeStreamUntilDone } from '@lobechat/model-runtime';
+import type { MessageToolCall, ModelUsage } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { runMaintenanceToolFirstRuntime } from '../agent';
+import type { NightlyReviewContext } from '../nightlyCollector';
+import type { MaintenanceTools, MaintenanceToolWriteResult } from '../tools';
+
+vi.mock('@lobechat/model-runtime', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelRuntimeModule>();
+
+ return {
+ ...actual,
+ consumeStreamUntilDone: vi.fn(async () => undefined),
+ };
+});
+
+const reviewContext = {
+ agentId: 'agent-1',
+ documentActivity: {
+ ambiguousBucket: [],
+ excludedSummary: { count: 0, reasons: [] },
+ generalDocumentBucket: [],
+ skillBucket: [],
+ },
+ feedbackActivity: {
+ neutralCount: 0,
+ notSatisfied: [],
+ satisfied: [],
+ },
+ 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;
+
+interface MockChatStep {
+ content: string;
+ toolCalls?: MessageToolCall[];
+ usage?: ModelUsage;
+}
+
+const createMockModelRuntime = (steps: MockChatStep[]) => {
+ const chat = vi.fn(async (_payload: ChatStreamPayload, options?: ChatMethodOptions) => {
+ const step = steps[Math.min(chat.mock.calls.length - 1, steps.length - 1)];
+
+ options?.callback?.onText?.(step.content);
+ options?.callback?.onToolsCalling?.({
+ chunk: [],
+ toolsCalling: step.toolCalls ?? [],
+ });
+ options?.callback?.onCompletion?.({ text: step.content, usage: step.usage });
+
+ return new Response('');
+ });
+
+ return {
+ chat,
+ modelRuntime: { chat: chat as unknown as Pick<ModelRuntime, 'chat'>['chat'] },
+ };
+};
+
+const createMockTools = (writeResult?: MaintenanceToolWriteResult): MaintenanceTools => ({
+ closeMaintenanceProposal: vi.fn(async () => ({
+ receiptId: 'receipt-close',
+ status: 'applied' as const,
+ })),
+ createMaintenanceProposal: vi.fn(async () => ({
+ receiptId: 'receipt-proposal',
+ status: 'proposed' as const,
+ })),
+ createSkillIfAbsent: vi.fn(async () =>
+ writeResult
+ ? writeResult
+ : {
+ receiptId: 'receipt-skill',
+ resourceId: 'skill-1',
+ status: 'applied' as const,
+ summary: 'Created skill.',
+ },
+ ),
+ getEvidenceDigest: vi.fn(async () => ({ evidence: [] })),
+ getManagedSkill: vi.fn(async () => ({ id: 'skill-1' })),
+ listMaintenanceProposals: vi.fn(async () => []),
+ listManagedSkills: vi.fn(async () => []),
+ readMaintenanceProposal: vi.fn(async () => undefined),
+ refreshMaintenanceProposal: vi.fn(async () => ({
+ receiptId: 'receipt-refresh',
+ status: 'proposed' as const,
+ })),
+ replaceSkillContentCAS: vi.fn(async () => ({
+ receiptId: 'receipt-replace',
+ status: 'applied' as const,
+ })),
+ supersedeMaintenanceProposal: vi.fn(async () => ({
+ receiptId: 'receipt-supersede',
+ status: 'applied' as const,
+ })),
+ writeMemory: vi.fn(async () =>
+ writeResult
+ ? writeResult
+ : {
+ receiptId: 'receipt-memory',
+ resourceId: 'memory-1',
+ status: 'applied' as const,
+ summary: 'Wrote memory.',
+ },
+ ),
+});
+
+describe('runMaintenanceToolFirstRuntime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ /**
+ * @example
+ * expect(tools.createSkillIfAbsent).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user-1' }));
+ * expect(result.writeOutcomes).toEqual([{ toolName: 'createSkillIfAbsent', result: writeResult }]);
+ */
+ it('invokes a write tool, records its outcome, and asks the model for a follow-up step', async () => {
+ const writeResult = {
+ receiptId: 'receipt-skill',
+ resourceId: 'skill-1',
+ status: 'applied',
+ summary: 'Created skill.',
+ } satisfies MaintenanceToolWriteResult;
+ const tools = createMockTools(writeResult);
+ const { chat, modelRuntime } = createMockModelRuntime([
+ {
+ content: 'I will create the skill.',
+ toolCalls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ bodyMarkdown: '# Skill',
+ idempotencyKey: 'source-1:create-skill',
+ name: 'debug-skill',
+ summary: 'Create a debug skill.',
+ }),
+ name: 'createSkillIfAbsent',
+ },
+ id: 'tool-call-1',
+ type: 'function',
+ },
+ ],
+ usage: { inputTextTokens: 10, outputTextTokens: 5, totalTokens: 15 },
+ },
+ {
+ content: 'Created the skill.',
+ usage: { inputTextTokens: 5, outputTextTokens: 3, totalTokens: 8 },
+ },
+ ]);
+
+ const result = await runMaintenanceToolFirstRuntime({
+ agentId: 'agent-1',
+ context: reviewContext,
+ maxSteps: 5,
+ model: 'gpt-test',
+ modelRuntime,
+ sourceId: 'source-1',
+ tools,
+ userId: 'user-1',
+ });
+
+ expect(tools.createSkillIfAbsent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ bodyMarkdown: '# Skill',
+ idempotencyKey: 'source-1:create-skill',
+ name: 'debug-skill',
+ userId: 'user-1',
+ }),
+ );
+ expect(chat).toHaveBeenCalledTimes(2);
+ expect(consumeStreamUntilDone).toHaveBeenCalledTimes(2);
+ expect(result.stepCount).toBeGreaterThan(1);
+ expect(result.content).toContain('Created the skill.');
+ expect(result.writeOutcomes).toEqual([
+ { result: writeResult, toolName: 'createSkillIfAbsent' },
+ ]);
+ });
+
+ /**
+ * @example
+ * expect(tools.writeMemory).toHaveBeenCalledWith(expect.objectContaining({ content: 'User prefers concise summaries.' }));
+ * expect(result.writeOutcomes[0]).toMatchObject({ toolName: 'writeMemory' });
+ */
+ it('exposes writeMemory as the auto-apply path for durable user preferences', async () => {
+ const writeResult = {
+ receiptId: 'receipt-memory',
+ resourceId: 'memory-1',
+ status: 'applied',
+ summary: 'Wrote memory.',
+ } satisfies MaintenanceToolWriteResult;
+ const tools = createMockTools(writeResult);
+ const { modelRuntime } = createMockModelRuntime([
+ {
+ content: 'I will remember the durable preference.',
+ toolCalls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ content: 'User prefers concise implementation summaries.',
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'source-1:write-memory',
+ }),
+ name: 'writeMemory',
+ },
+ id: 'tool-call-memory',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'Saved the preference.',
+ },
+ ]);
+
+ const result = await runMaintenanceToolFirstRuntime({
+ agentId: 'agent-1',
+ context: reviewContext,
+ maxSteps: 5,
+ model: 'gpt-test',
+ modelRuntime,
+ sourceId: 'source-1',
+ tools,
+ userId: 'user-1',
+ });
+
+ expect(tools.writeMemory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'User prefers concise implementation summaries.',
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'source-1:write-memory',
+ userId: 'user-1',
+ }),
+ );
+ expect(result.writeOutcomes).toEqual([{ result: writeResult, toolName: 'writeMemory' }]);
+ });
+
+ /**
+ * @example
+ * expect(systemPrompt).toContain('getEvidenceDigest');
+ * expect(systemPrompt).toContain('readMaintenanceProposal');
+ */
+ it('tells the model to keep evidence ids separate from maintenance proposal keys', async () => {
+ const tools = createMockTools();
+ const { chat, modelRuntime } = createMockModelRuntime([{ content: 'No action needed.' }]);
+
+ await runMaintenanceToolFirstRuntime({
+ agentId: 'agent-1',
+ context: reviewContext,
+ maxSteps: 1,
+ model: 'gpt-test',
+ modelRuntime,
+ sourceId: 'source-1',
+ tools,
+ userId: 'user-1',
+ });
+
+ const systemPrompt = chat.mock.calls[0]?.[0].messages[0]?.content;
+
+ expect(systemPrompt).toContain('getEvidenceDigest');
+ expect(systemPrompt).toContain('readMaintenanceProposal');
+ expect(systemPrompt).toContain('Evidence ids and proposal keys are different namespaces');
+ });
+
+ /**
+ * @example
+ * expect(result.writeOutcomes).toEqual([]);
+ * expect(chat).toHaveBeenCalledTimes(2);
+ */
+ it('returns an unsupported tool result to the model without throwing the run', async () => {
+ const tools = createMockTools();
+ const { chat, modelRuntime } = createMockModelRuntime([
+ {
+ content: 'I will call an unknown tool.',
+ toolCalls: [
+ {
+ function: {
+ arguments: '{"unexpected":true}',
+ name: 'missingMaintenanceTool',
+ },
+ id: 'tool-call-unsupported',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'Unsupported tool noted.',
+ },
+ ]);
+
+ const result = await runMaintenanceToolFirstRuntime({
+ agentId: 'agent-1',
+ context: reviewContext,
+ maxSteps: 4,
+ model: 'gpt-test',
+ modelRuntime,
+ sourceId: 'source-1',
+ tools,
+ userId: 'user-1',
+ });
+
+ expect(chat).toHaveBeenCalledTimes(2);
+ expect(tools.createSkillIfAbsent).not.toHaveBeenCalled();
+ expect(result.content).toContain('Unsupported tool noted.');
+ expect(result.writeOutcomes).toEqual([]);
+ });
+
+ /**
+ * @example
+ * expect(tools.createSkillIfAbsent).toHaveBeenCalledTimes(1);
+ * expect(chat).toHaveBeenCalledTimes(2);
+ */
+ it('allows AgentRuntime to execute a tool and final continuation when maxSteps is one', async () => {
+ const tools = createMockTools();
+ const { chat, modelRuntime } = createMockModelRuntime([
+ {
+ content: 'I will create a skill.',
+ toolCalls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ bodyMarkdown: '# Skill',
+ idempotencyKey: 'source-1:max-step-create',
+ name: 'bounded-skill',
+ }),
+ name: 'createSkillIfAbsent',
+ },
+ id: 'tool-call-max-step',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'Finished after the tool result.',
+ },
+ ]);
+
+ const result = await runMaintenanceToolFirstRuntime({
+ agentId: 'agent-1',
+ context: reviewContext,
+ maxSteps: 1,
+ model: 'gpt-test',
+ modelRuntime,
+ sourceId: 'source-1',
+ tools,
+ userId: 'user-1',
+ });
+
+ expect(tools.createSkillIfAbsent).toHaveBeenCalledTimes(1);
+ expect(chat).toHaveBeenCalledTimes(2);
+ expect(chat.mock.calls[1]?.[0].tools).toEqual([]);
+ expect(result.content).toContain('Finished after the tool result.');
+ expect(result.writeOutcomes).toHaveLength(1);
+ });
+
+ /**
+ * @example
+ * expect(modelVisibleMessages).toContain('Maintenance tool call failed.');
+ * expect(modelVisibleMessages).not.toContain('secret-token-123');
+ */
+ it('sanitizes thrown tool errors before adding model-visible tool messages', async () => {
+ const tools = {
+ ...createMockTools(),
+ createSkillIfAbsent: vi.fn(async () => {
+ throw new Error('upstream secret-token-123 failed');
+ }),
+ } satisfies MaintenanceTools;
+ const { chat, modelRuntime } = createMockModelRuntime([
+ {
+ content: 'I will create a skill.',
+ toolCalls: [
+ {
+ function: {
+ arguments: JSON.stringify({
+ bodyMarkdown: '# Skill',
+ idempotencyKey: 'source-1:sensitive-error',
+ name: 'sensitive-skill',
+ }),
+ name: 'createSkillIfAbsent',
+ },
+ id: 'tool-call-sensitive-error',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: 'The tool failed safely.',
+ },
+ ]);
+
+ await runMaintenanceToolFirstRuntime({
+ agentId: 'agent-1',
+ context: reviewContext,
+ maxSteps: 5,
+ model: 'gpt-test',
+ modelRuntime,
+ sourceId: 'source-1',
+ tools,
+ userId: 'user-1',
+ });
+
+ const modelVisibleMessages = JSON.stringify(chat.mock.calls[1]?.[0].messages);
+
+ expect(modelVisibleMessages).toContain('Maintenance tool call failed.');
+ expect(modelVisibleMessages).not.toContain('secret-token-123');
+ });
+});
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts
index 646d6843272..43d1da0a0a2 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/brief.test.ts
@@ -16,6 +16,23 @@ afterEach(() => {
vi.restoreAllMocks();
});
+const completeRefineSkillBaseSnapshot = (agentDocumentId: string) => ({
+ agentDocumentId,
+ contentHash: `sha256:${agentDocumentId}`,
+ documentId: `doc-${agentDocumentId}`,
+ managed: true,
+ targetType: 'skill' as const,
+ writable: true,
+});
+
+const getNightlySelfReview = (
+ brief: ReturnType<ReturnType<typeof createBriefMaintenanceService>['projectNightlyReviewBrief']>,
+) => brief?.metadata.agentSignal.nightlySelfReview;
+
+const getMaintenanceProposal = (
+ brief: ReturnType<ReturnType<typeof createBriefMaintenanceService>['projectNightlyReviewBrief']>,
+) => getNightlySelfReview(brief)?.maintenanceProposal;
+
describe('briefMaintenanceService', () => {
/**
* @example
@@ -52,13 +69,19 @@ describe('briefMaintenanceService', () => {
type: 'insight',
});
expect(brief?.metadata).toMatchObject({
- actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
- localDate: '2026-05-04',
- outcome: 'applied',
- receiptIds: ['receipt-1'],
- sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
- timezone: 'Asia/Shanghai',
+ agentSignal: {
+ nightlySelfReview: {
+ actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
+ localDate: '2026-05-04',
+ outcome: 'applied',
+ receiptIds: ['receipt-1'],
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-04',
+ timezone: 'Asia/Shanghai',
+ },
+ },
});
+ expect(brief?.metadata).not.toHaveProperty('actionCounts');
+ expect(brief?.metadata).not.toHaveProperty('outcome');
});
/**
@@ -179,6 +202,7 @@ describe('briefMaintenanceService', () => {
{
actionType: 'refine_skill',
applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),
confidence: 0.91,
dedupeKey: 'skill:adoc-1',
evidenceRefs: [{ id: 'adoc-1', type: 'agent_document' }],
@@ -225,12 +249,15 @@ describe('briefMaintenanceService', () => {
{ key: 'dismiss', label: 'Dismiss', type: 'resolve' },
{ key: 'feedback', label: 'Request changes', type: 'comment' },
]);
- expect(projected?.metadata.proposal).toMatchObject({
+ const nightlySelfReview = projected?.metadata.agentSignal?.nightlySelfReview;
+
+ expect(nightlySelfReview?.maintenanceProposal).toMatchObject({
proposalKey: 'agent-1:refine_skill:agent_document:adoc-1',
status: 'pending',
version: 1,
});
- expect(projected?.metadata.proposal?.actions[0]).toMatchObject({
+ expect(projected?.metadata).not.toHaveProperty('proposal');
+ expect(nightlySelfReview?.maintenanceProposal?.actions[0]).toMatchObject({
actionType: 'refine_skill',
idempotencyKey: 'source:refine_skill:skill:adoc-1',
operation: {
@@ -264,6 +291,7 @@ describe('briefMaintenanceService', () => {
{
actionType: 'refine_skill',
applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),
confidence: 0.91,
dedupeKey: 'skill:adoc-1',
evidenceRefs: [{ id: 'adoc-1', type: 'agent_document' }],
@@ -310,11 +338,11 @@ describe('briefMaintenanceService', () => {
userId: 'user-1',
});
- expect(projected?.metadata.actionCounts.proposed).toBe(1);
+ expect(getNightlySelfReview(projected)?.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({
+ expect(getMaintenanceProposal(projected)?.actions).toHaveLength(1);
+ expect(getMaintenanceProposal(projected)?.actions[0]).toMatchObject({
actionType: 'refine_skill',
idempotencyKey: 'source:refine_skill:skill:adoc-1',
});
@@ -351,7 +379,11 @@ describe('briefMaintenanceService', () => {
type: 'error',
});
expect(brief?.metadata).toMatchObject({
- outcome: 'error',
+ agentSignal: {
+ nightlySelfReview: {
+ outcome: 'error',
+ },
+ },
});
});
@@ -465,6 +497,7 @@ describe('briefMaintenanceService', () => {
{
actionType: 'refine_skill',
applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),
confidence: 0.91,
dedupeKey: 'skill:adoc-1',
evidenceRefs: [{ id: 'msg-new', type: 'message' }],
@@ -499,13 +532,15 @@ describe('briefMaintenanceService', () => {
userId: 'user-1',
});
- if (!incoming?.metadata.proposal) throw new Error('Expected projected proposal brief');
+ if (!incoming) throw new Error('Expected projected incoming brief');
+ const incomingProposal = getMaintenanceProposal(incoming);
+ if (!incomingProposal) throw new Error('Expected projected proposal brief');
const existingProposal = {
- ...incoming.metadata.proposal,
+ ...incomingProposal,
actions: [
{
- ...incoming.metadata.proposal.actions[0],
+ ...incomingProposal.actions[0],
idempotencyKey: 'source:old',
rationale: 'Old rationale.',
},
@@ -517,12 +552,24 @@ describe('briefMaintenanceService', () => {
const existingBrief = {
agentId: 'agent-1',
id: 'brief-old',
- metadata: { proposal: existingProposal },
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: existingProposal,
+ },
+ },
+ },
trigger: 'agent-signal:nightly-review',
} as Awaited<ReturnType<BriefModel['create']>>;
const updatedBrief = {
...existingBrief,
- metadata: { proposal: { ...existingProposal, actions: incoming.metadata.proposal.actions } },
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: { ...existingProposal, actions: incomingProposal.actions },
+ },
+ },
+ },
} as Awaited<ReturnType<BriefModel['create']>>;
const create = vi.spyOn(BriefModel.prototype, 'create');
const listUnresolvedByAgentAndTrigger = vi
@@ -544,9 +591,13 @@ describe('briefMaintenanceService', () => {
expect(updateMetadata).toHaveBeenCalledWith(
'brief-old',
expect.objectContaining({
- proposal: expect.objectContaining({
- actions: incoming.metadata.proposal.actions,
- status: 'pending',
+ agentSignal: expect.objectContaining({
+ nightlySelfReview: expect.objectContaining({
+ maintenanceProposal: expect.objectContaining({
+ actions: incomingProposal.actions,
+ status: 'pending',
+ }),
+ }),
}),
}),
);
@@ -566,6 +617,7 @@ describe('briefMaintenanceService', () => {
{
actionType: 'refine_skill',
applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),
confidence: 0.91,
dedupeKey: 'skill:adoc-1',
evidenceRefs: [{ id: 'msg-new', type: 'message' }],
@@ -600,14 +652,16 @@ describe('briefMaintenanceService', () => {
userId: 'user-1',
});
- if (!incoming?.metadata.proposal) throw new Error('Expected projected proposal brief');
+ if (!incoming) throw new Error('Expected projected incoming brief');
+ const incomingProposal = getMaintenanceProposal(incoming);
+ if (!incomingProposal) throw new Error('Expected projected proposal brief');
- const existingProposal = incoming.metadata.proposal;
- incoming.metadata.proposal = {
- ...incoming.metadata.proposal,
+ const existingProposal = incomingProposal;
+ incoming.metadata.agentSignal.nightlySelfReview.maintenanceProposal = {
+ ...incomingProposal,
actions: [
{
- ...incoming.metadata.proposal.actions[0],
+ ...incomingProposal.actions[0],
operation: {
domain: 'skill',
input: { bodyMarkdown: 'new skill', name: 'new-skill', userId: 'user-1' },
@@ -619,7 +673,13 @@ describe('briefMaintenanceService', () => {
const existingBrief = {
agentId: 'agent-1',
id: 'brief-old',
- metadata: { proposal: existingProposal },
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: existingProposal,
+ },
+ },
+ },
trigger: 'agent-signal:nightly-review',
} as Awaited<ReturnType<BriefModel['create']>>;
const createdBrief = { id: 'brief-new' } as Awaited<ReturnType<BriefModel['create']>>;
@@ -637,9 +697,14 @@ describe('briefMaintenanceService', () => {
expect(updateMetadata).toHaveBeenCalledWith(
'brief-old',
expect.objectContaining({
- proposal: expect.objectContaining({
- status: 'superseded',
- supersededBy: incoming.metadata.proposal.proposalKey,
+ agentSignal: expect.objectContaining({
+ nightlySelfReview: expect.objectContaining({
+ maintenanceProposal: expect.objectContaining({
+ status: 'superseded',
+ supersededBy:
+ incoming.metadata.agentSignal.nightlySelfReview.maintenanceProposal?.proposalKey,
+ }),
+ }),
}),
}),
);
@@ -660,6 +725,7 @@ describe('briefMaintenanceService', () => {
{
actionType: 'refine_skill',
applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: completeRefineSkillBaseSnapshot('adoc-1'),
confidence: 0.91,
dedupeKey: 'skill:adoc-1',
evidenceRefs: [],
@@ -694,17 +760,25 @@ describe('briefMaintenanceService', () => {
userId: 'user-1',
});
- if (!incoming?.metadata.proposal) throw new Error('Expected projected proposal brief');
+ if (!incoming) throw new Error('Expected projected incoming brief');
+ const incomingProposal = getMaintenanceProposal(incoming);
+ if (!incomingProposal) throw new Error('Expected projected proposal brief');
const existingProposal = {
- ...incoming.metadata.proposal,
+ ...incomingProposal,
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 },
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: existingProposal,
+ },
+ },
+ },
trigger: 'agent-signal:nightly-review',
} as Awaited<ReturnType<BriefModel['create']>>;
const createdBrief = { id: 'brief-new' } as Awaited<ReturnType<BriefModel['create']>>;
@@ -722,7 +796,11 @@ describe('briefMaintenanceService', () => {
expect(updateMetadata).toHaveBeenCalledWith(
'brief-old',
expect.objectContaining({
- proposal: expect.objectContaining({ status: 'expired' }),
+ agentSignal: expect.objectContaining({
+ nightlySelfReview: expect.objectContaining({
+ maintenanceProposal: expect.objectContaining({ status: 'expired' }),
+ }),
+ }),
}),
);
expect(create).toHaveBeenCalledWith(incoming);
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts
new file mode 100644
index 00000000000..9c79e26098a
--- /dev/null
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts
@@ -0,0 +1,506 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ projectMaintenanceToolOutcomes,
+ projectMaintenanceToolRuntimeRun,
+} from '../briefProjection';
+import {
+ MaintenanceActionStatus,
+ MaintenanceApplyMode,
+ MaintenanceReviewScope,
+ MaintenanceRisk,
+ ReviewRunStatus,
+} from '../types';
+
+describe('projectMaintenanceToolOutcomes', () => {
+ /**
+ * @example
+ * Empty tool outcome lists stay silent and carry empty metadata.
+ */
+ it('does not request a brief when no write tools ran', () => {
+ const projection = projectMaintenanceToolOutcomes({ outcomes: [] });
+
+ expect(projection).toEqual({
+ actionCounts: { applied: 0, failed: 0, proposed: 0, skipped: 0 },
+ actions: [],
+ briefKind: 'none',
+ proposalCount: 0,
+ receiptIds: [],
+ });
+ });
+
+ /**
+ * @example
+ * Applied write-tool outcomes become insight metadata with durable receipt links.
+ */
+ it('projects applied writes to insight metadata with action and receipt ids', () => {
+ const projection = projectMaintenanceToolOutcomes({
+ outcomes: [
+ {
+ receiptId: 'receipt-1',
+ resourceId: 'memory-1',
+ status: 'applied',
+ summary: 'Saved concise preference.',
+ toolName: 'writeMemory',
+ },
+ ],
+ });
+
+ expect(projection).toEqual({
+ actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
+ actions: [
+ {
+ receiptId: 'receipt-1',
+ resourceId: 'memory-1',
+ status: 'applied',
+ summary: 'Saved concise preference.',
+ toolName: 'writeMemory',
+ },
+ ],
+ briefKind: 'insight',
+ proposalCount: 0,
+ receiptIds: ['receipt-1'],
+ });
+ });
+
+ /**
+ * @example
+ * Created, refreshed, or superseded proposal tool outcomes ask Daily Brief for a decision.
+ */
+ it('projects proposal lifecycle outcomes to decision metadata with proposal count', () => {
+ const projection = projectMaintenanceToolOutcomes({
+ outcomes: [
+ {
+ receiptId: 'receipt-created',
+ resourceId: 'proposal-1',
+ status: 'proposed',
+ summary: 'Review new skill proposal.',
+ toolName: 'createMaintenanceProposal',
+ },
+ {
+ receiptId: 'receipt-refreshed',
+ resourceId: 'proposal-2',
+ status: 'proposed',
+ summary: 'Review refreshed skill proposal.',
+ toolName: 'refreshMaintenanceProposal',
+ },
+ {
+ receiptId: 'receipt-superseded',
+ resourceId: 'proposal-3',
+ status: 'proposed',
+ summary: 'Review superseding skill proposal.',
+ toolName: 'supersedeMaintenanceProposal',
+ },
+ ],
+ });
+
+ expect(projection.briefKind).toBe('decision');
+ expect(projection.proposalCount).toBe(3);
+ expect(projection.actionCounts).toEqual({
+ applied: 0,
+ failed: 0,
+ proposed: 3,
+ skipped: 0,
+ });
+ expect(projection.receiptIds).toEqual([
+ 'receipt-created',
+ 'receipt-refreshed',
+ 'receipt-superseded',
+ ]);
+ });
+
+ /**
+ * @example
+ * Visible risky write outcomes create insight metadata when no decision exists.
+ */
+ it('projects stale and failed outcomes to insight metadata', () => {
+ const projection = projectMaintenanceToolOutcomes({
+ outcomes: [
+ {
+ receiptId: 'receipt-stale',
+ status: 'skipped_stale',
+ summary: 'Skill changed before apply.',
+ toolName: 'replaceSkillContentCAS',
+ },
+ {
+ status: 'failed',
+ summary: 'Proposal close failed.',
+ toolName: 'closeMaintenanceProposal',
+ },
+ ],
+ });
+
+ expect(projection.briefKind).toBe('insight');
+ expect(projection.actionCounts).toEqual({
+ applied: 0,
+ failed: 1,
+ proposed: 0,
+ skipped: 1,
+ });
+ expect(projection.receiptIds).toEqual(['receipt-stale']);
+ });
+
+ /**
+ * @example
+ * Unsupported and deduped writes are retained as metadata but stay brief-silent.
+ */
+ it('keeps skipped unsupported and deduped outcomes silent when they are the only outcomes', () => {
+ const projection = projectMaintenanceToolOutcomes({
+ outcomes: [
+ {
+ receiptId: 'receipt-unsupported',
+ status: 'skipped_unsupported',
+ summary: 'Tool disabled.',
+ toolName: 'createSkillIfAbsent',
+ },
+ {
+ status: 'deduped',
+ summary: 'Duplicate operation.',
+ toolName: 'refreshMaintenanceProposal',
+ },
+ ],
+ });
+
+ expect(projection.briefKind).toBe('none');
+ expect(projection.actionCounts).toEqual({
+ applied: 0,
+ failed: 0,
+ proposed: 0,
+ skipped: 2,
+ });
+ expect(projection.receiptIds).toEqual(['receipt-unsupported']);
+ });
+});
+
+describe('projectMaintenanceToolRuntimeRun', () => {
+ /**
+ * @example
+ * projectMaintenanceToolRuntimeRun keeps createMaintenanceProposal action payloads approve-ready.
+ */
+ it('preserves proposed create skill actions from proposal lifecycle tool arguments', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ content: 'Created a proposal.',
+ localDate: '2026-05-09',
+ outcomes: [
+ {
+ receiptId: 'receipt-proposal-1',
+ resourceId: 'brief-proposal-1',
+ status: 'proposed',
+ summary: 'Review concise answers skill.',
+ toolName: 'createMaintenanceProposal',
+ },
+ ],
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify({
+ actions: [
+ {
+ actionType: 'create_skill',
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: {
+ absent: true,
+ skillName: 'concise-answers',
+ targetType: 'skill',
+ },
+ confidence: 0.9,
+ dedupeKey: 'skill:concise-answers',
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'source-1:create_skill:concise-answers',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Prefer concise answers.',
+ name: 'concise-answers',
+ title: 'Concise answers',
+ userId: 'user-1',
+ },
+ operation: 'create',
+ },
+ rationale: 'User repeatedly asks for concise answers.',
+ risk: MaintenanceRisk.Low,
+ target: { skillName: 'concise-answers' },
+ },
+ ],
+ idempotencyKey: 'proposal-op-1',
+ proposalKey: 'agent-1:create_skill:skill:concise-answers',
+ summary: 'Review concise answers skill.',
+ }),
+ id: 'call-proposal-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.execution.actions).toEqual([
+ {
+ idempotencyKey: 'source-1:create_skill:concise-answers',
+ receiptId: 'receipt-proposal-1',
+ resourceId: 'brief-proposal-1',
+ status: MaintenanceActionStatus.Proposed,
+ summary: 'Review concise answers skill.',
+ },
+ ]);
+ expect(projection.projectionPlan.actions).toHaveLength(1);
+ expect(projection.projectionPlan.actions[0]).toMatchObject({
+ actionType: 'create_skill',
+ baseSnapshot: {
+ absent: true,
+ skillName: 'concise-answers',
+ targetType: 'skill',
+ },
+ idempotencyKey: 'source-1:create_skill:concise-answers',
+ operation: {
+ domain: 'skill',
+ operation: 'create',
+ },
+ target: { skillName: 'concise-answers' },
+ });
+ });
+
+ /**
+ * @example
+ * projectMaintenanceToolRuntimeRun binds repeated same-name write outcomes by call order.
+ */
+ it('matches repeated same-name tool outcomes to their own ordered tool call arguments', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ outcomes: [
+ {
+ receiptId: 'receipt-first',
+ resourceId: 'skill-first',
+ status: 'applied',
+ toolName: 'createSkillIfAbsent',
+ },
+ {
+ receiptId: 'receipt-second',
+ resourceId: 'skill-second',
+ status: 'applied',
+ toolName: 'createSkillIfAbsent',
+ },
+ ],
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'createSkillIfAbsent',
+ arguments: JSON.stringify({
+ bodyMarkdown: 'First skill body.',
+ idempotencyKey: 'op-first',
+ name: 'first-skill',
+ }),
+ id: 'call-first',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ {
+ apiName: 'createSkillIfAbsent',
+ arguments: JSON.stringify({
+ bodyMarkdown: 'Second skill body.',
+ idempotencyKey: 'op-second',
+ name: 'second-skill',
+ }),
+ id: 'call-second',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.execution.actions.map((action) => action.idempotencyKey)).toEqual([
+ 'op-first',
+ 'op-second',
+ ]);
+ expect(
+ projection.projectionPlan.actions.map((action) => ({
+ bodyMarkdown:
+ action.operation?.domain === 'skill' && 'bodyMarkdown' in action.operation.input
+ ? action.operation.input.bodyMarkdown
+ : undefined,
+ name:
+ action.operation?.domain === 'skill' && 'name' in action.operation.input
+ ? action.operation.input.name
+ : undefined,
+ })),
+ ).toEqual([
+ { bodyMarkdown: 'First skill body.', name: 'first-skill' },
+ { bodyMarkdown: 'Second skill body.', name: 'second-skill' },
+ ]);
+ });
+
+ /**
+ * @example
+ * projectMaintenanceToolRuntimeRun must not emit unapprovable proposal_only actions for refreshes.
+ */
+ it('does not project proposal refresh outcomes without executable actions into decision actions', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ outcomes: [
+ {
+ receiptId: 'receipt-refresh',
+ resourceId: 'brief-proposal-1',
+ status: 'proposed',
+ summary: 'Refreshed existing proposal.',
+ toolName: 'refreshMaintenanceProposal',
+ },
+ ],
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'refreshMaintenanceProposal',
+ arguments: JSON.stringify({
+ idempotencyKey: 'refresh-op-1',
+ proposalId: 'brief-proposal-1',
+ summary: 'Refreshed existing proposal.',
+ }),
+ id: 'call-refresh-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.projectionPlan.actions).toEqual([]);
+ expect(projection.execution.actions).toEqual([
+ {
+ idempotencyKey: 'refresh-op-1',
+ receiptId: 'receipt-refresh',
+ resourceId: 'brief-proposal-1',
+ status: MaintenanceActionStatus.Skipped,
+ summary: 'Refreshed existing proposal.',
+ },
+ ]);
+ expect(projection.execution.status).toBe(ReviewRunStatus.Skipped);
+ });
+
+ /**
+ * @example
+ * projectMaintenanceToolRuntimeRun must not turn malformed create proposal calls into approval work.
+ */
+ it('does not project create proposal outcomes without executable actions into decision actions', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ outcomes: [
+ {
+ receiptId: 'receipt-create-proposal',
+ resourceId: 'brief-proposal-1',
+ status: 'proposed',
+ summary: 'Malformed proposal.',
+ toolName: 'createMaintenanceProposal',
+ },
+ ],
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify({
+ actions: [],
+ idempotencyKey: 'create-proposal-op-1',
+ proposalKey: 'agent-1:create_skill:skill:missing',
+ summary: 'Malformed proposal.',
+ }),
+ id: 'call-create-proposal-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.projectionPlan.actions).toEqual([]);
+ expect(projection.execution.actions).toEqual([
+ {
+ idempotencyKey: 'create-proposal-op-1',
+ receiptId: 'receipt-create-proposal',
+ resourceId: 'brief-proposal-1',
+ status: MaintenanceActionStatus.Skipped,
+ summary: 'Malformed proposal.',
+ },
+ ]);
+ expect(projection.execution.status).toBe(ReviewRunStatus.Skipped);
+ });
+
+ /**
+ * @example
+ * projectMaintenanceToolRuntimeRun accepts proposal actions that inherit the proposal operation id.
+ */
+ it('projects proposal actions that omit per-action idempotency keys', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ outcomes: [
+ {
+ receiptId: 'receipt-create-proposal',
+ resourceId: 'brief-proposal-1',
+ status: 'proposed',
+ summary: 'Review managed skill refinement.',
+ toolName: 'createMaintenanceProposal',
+ },
+ ],
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify({
+ actions: [
+ {
+ actionType: 'refine_skill',
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'hash-before',
+ documentId: 'doc-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: '# Updated skill\n\nUse the managed skill replacement path.',
+ skillDocumentId: 'skill-doc-1',
+ userId: 'user-1',
+ },
+ operation: 'refine',
+ },
+ rationale: 'The repeated failure needs a safe managed-skill refinement.',
+ target: { skillDocumentId: 'skill-doc-1' },
+ },
+ ],
+ idempotencyKey: 'proposal-op-1',
+ proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',
+ summary: 'Review managed skill refinement.',
+ }),
+ id: 'call-create-proposal-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.execution.actions).toEqual([
+ {
+ idempotencyKey: 'proposal-op-1:action:1',
+ receiptId: 'receipt-create-proposal',
+ resourceId: 'brief-proposal-1',
+ status: MaintenanceActionStatus.Proposed,
+ summary: 'Review managed skill refinement.',
+ },
+ ]);
+ expect(projection.execution.status).toBe(ReviewRunStatus.Completed);
+ expect(projection.projectionPlan.actions[0]).toMatchObject({
+ actionType: 'refine_skill',
+ idempotencyKey: 'proposal-op-1:action:1',
+ operation: {
+ domain: 'skill',
+ operation: 'refine',
+ },
+ target: { skillDocumentId: 'skill-doc-1' },
+ });
+ });
+});
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts
index 06160e0cb2f..8f3bda1d090 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlyCollector.test.ts
@@ -76,6 +76,7 @@ describe('nightlyReviewService', () => {
},
{
correctionCount: 1,
+ correctionIds: [],
failedToolCount: 1,
failureCount: 1,
id: 'topic-high',
@@ -118,11 +119,12 @@ describe('nightlyReviewService', () => {
'failed_tool',
'receipt',
]);
- expect(context.maintenanceSignals).toContainEqual(
- expect.objectContaining({
- kind: 'durable_user_preference',
- strength: 'strong',
- }),
+ expect(context.topics[0]).toMatchObject({
+ correctionCount: 1,
+ correctionIds: [],
+ });
+ expect(context.maintenanceSignals.map((signal) => signal.kind)).not.toContain(
+ 'durable_user_preference',
);
expect(context.topics[0]).not.toHaveProperty('rawMessages');
expect(context.topics[1]).not.toHaveProperty('rawMessages');
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts
index 77902ec5f5f..fd2cf25cec2 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/nightlySignals.test.ts
@@ -155,35 +155,29 @@ describe('deriveNightlyMaintenanceSignals', () => {
/**
* @example
- * Explicit future preference corrections become durable memory review signals.
+ * Ordinary message wording and correction metadata are not durable preference evidence.
*/
- 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',
- }),
- );
+ it('does not create durable user preference signals from correction-bearing topics', () => {
+ const signals = 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.',
+ },
+ ],
+ });
+
+ expect(signals.map((signal) => signal.kind)).not.toContain('durable_user_preference');
});
/**
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts
index fc083fb6669..4a79f4ff926 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposal.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import type { MaintenanceProposalMetadata } from '../proposal';
+import type { MaintenanceProposalMetadata, MaintenanceProposalPlan } from '../proposal';
import {
buildMaintenanceProposalFromPlan,
buildMaintenanceProposalKey,
@@ -306,18 +306,222 @@ describe('maintenance proposal metadata', () => {
/**
* @example
- * buildMaintenanceProposalFromPlan({ plan }) stores a target title snapshot for digest mapping.
+ * buildMaintenanceProposalFromPlan({ plan }) stores the complete refine base snapshot.
*/
- it('stores a target title snapshot on frozen proposal actions', () => {
+ it('stores complete base snapshots on mergeable refine_skill proposals', () => {
+ const action = {
+ actionType: 'refine_skill' as const,
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: {
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetType: 'skill' as const,
+ writable: true,
+ },
+ confidence: 0.92,
+ dedupeKey: 'skill:adoc_1',
+ evidenceRefs: [{ id: 'topic_1', type: 'topic' as const }],
+ idempotencyKey: 'source:refine_skill:skill:adoc_1',
+ operation: {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: 'Updated review preferences.',
+ skillDocumentId: 'adoc_1',
+ userId: 'user_1',
+ },
+ operation: 'refine' as const,
+ },
+ rationale: 'Refine the reusable review skill.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'adoc_1' },
+ };
+ 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: [action],
+ plannerVersion: 'test-planner',
+ reviewScope: MaintenanceReviewScope.Nightly,
+ summary: 'Review found a skill refinement proposal.',
+ },
+ results: [
+ {
+ idempotencyKey: 'source:refine_skill:skill:adoc_1',
+ status: MaintenanceActionStatus.Proposed,
+ },
+ ],
+ });
+
+ expect(proposal?.actions[0].baseSnapshot).toEqual({
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ });
+ });
+
+ /**
+ * @example
+ * buildMaintenanceProposalFromPlan({ plan: missingSnapshotPlan }) throws before storing.
+ */
+ it('rejects mergeable refine_skill proposal actions without required base snapshots', () => {
+ const buildProposal = (action: {
+ actionType: 'refine_skill';
+ baseSnapshot?: {
+ agentDocumentId?: string;
+ contentHash?: string;
+ documentId?: string;
+ managed?: boolean;
+ targetType?: 'skill';
+ writable?: boolean;
+ };
+ }) => {
+ const malformedPlan: unknown = {
+ actions: [
+ {
+ ...action,
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ confidence: 0.92,
+ dedupeKey: 'skill:adoc_1',
+ evidenceRefs: [{ id: 'topic_1', type: 'topic' }],
+ idempotencyKey: 'source:refine_skill:skill:adoc_1',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Updated review preferences.',
+ skillDocumentId: 'adoc_1',
+ userId: 'user_1',
+ },
+ operation: 'refine',
+ },
+ rationale: 'Refine the reusable review skill.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'adoc_1' },
+ },
+ ],
+ plannerVersion: 'test-planner',
+ reviewScope: MaintenanceReviewScope.Nightly,
+ summary: 'Review found a skill refinement proposal.',
+ };
+
+ return 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',
+ // NOTICE:
+ // This intentionally bypasses the compile-time snapshot requirement.
+ // The test exercises runtime validation for malformed persisted/runtime proposal data.
+ // Remove this cast when malformed projection plans can no longer reach this boundary.
+ plan: malformedPlan as unknown as MaintenanceProposalPlan,
+ results: [
+ {
+ idempotencyKey: 'source:refine_skill:skill:adoc_1',
+ status: MaintenanceActionStatus.Proposed,
+ },
+ ],
+ });
+ };
+
+ expect(() => buildProposal({ actionType: 'refine_skill' })).toThrow(
+ 'Mergeable proposal action requires a complete base snapshot. actionType=refine_skill',
+ );
+ expect(() =>
+ buildProposal({
+ actionType: 'refine_skill',
+ baseSnapshot: {
+ agentDocumentId: 'adoc_1',
+ documentId: 'doc_1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ }),
+ ).toThrow(
+ 'Mergeable proposal action requires a complete base snapshot. actionType=refine_skill',
+ );
+ });
+
+ /**
+ * @example
+ * buildMaintenanceProposalFromPlan({ plan }) stores the absent create snapshot.
+ */
+ it('accepts complete absent snapshots on mergeable create_skill proposals', () => {
+ const action = {
+ actionType: 'create_skill' as const,
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: {
+ absent: true,
+ skillName: 'code-review',
+ targetType: 'skill' as const,
+ },
+ confidence: 0.92,
+ dedupeKey: 'skill:code-review',
+ evidenceRefs: [{ id: 'topic_1', type: 'topic' as const }],
+ idempotencyKey: 'source:create_skill:skill:code-review',
+ operation: {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: 'Remember review preferences.',
+ name: 'code-review',
+ title: 'Code Review',
+ userId: 'user_1',
+ },
+ operation: 'create' as const,
+ },
+ rationale: 'Create a reusable review skill.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillName: 'code-review' },
+ };
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: [action],
+ plannerVersion: 'test-planner',
+ reviewScope: MaintenanceReviewScope.Nightly,
+ summary: 'Review found a skill creation proposal.',
+ },
+ results: [
+ {
+ idempotencyKey: 'source:create_skill:skill:code-review',
+ status: MaintenanceActionStatus.Proposed,
+ },
+ ],
+ });
+
+ expect(proposal?.actions[0].baseSnapshot).toEqual({
+ absent: true,
+ skillName: 'code-review',
+ targetType: 'skill',
+ });
+ });
+
+ /**
+ * @example
+ * buildMaintenanceProposalFromPlan({ plan: incompleteAbsentSnapshotPlan }) throws.
+ */
+ it('rejects missing or incomplete absent snapshots on mergeable create_skill proposals', () => {
+ const buildProposal = (action: {
+ actionType: 'create_skill';
+ baseSnapshot?: {
+ absent?: boolean;
+ skillName?: string;
+ targetType?: 'skill';
+ };
+ }) => {
+ const malformedPlan: unknown = {
actions: [
{
- actionType: 'create_skill',
+ ...action,
applyMode: MaintenanceApplyMode.ProposalOnly,
confidence: 0.92,
dedupeKey: 'skill:code-review',
@@ -328,7 +532,6 @@ describe('maintenance proposal metadata', () => {
input: {
bodyMarkdown: 'Remember review preferences.',
name: 'code-review',
- title: 'Code Review',
userId: 'user_1',
},
operation: 'create',
@@ -340,18 +543,92 @@ describe('maintenance proposal metadata', () => {
],
plannerVersion: 'test-planner',
reviewScope: MaintenanceReviewScope.Nightly,
- summary: 'Review found a skill proposal.',
+ summary: 'Review found a skill creation proposal.',
+ };
+
+ return 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',
+ // NOTICE:
+ // This intentionally bypasses the compile-time snapshot requirement.
+ // The test exercises runtime validation for malformed persisted/runtime proposal data.
+ // Remove this cast when malformed projection plans can no longer reach this boundary.
+ plan: malformedPlan as unknown as MaintenanceProposalPlan,
+ results: [
+ {
+ idempotencyKey: 'source:create_skill:skill:code-review',
+ status: MaintenanceActionStatus.Proposed,
+ },
+ ],
+ });
+ };
+
+ expect(() => buildProposal({ actionType: 'create_skill' })).toThrow(
+ 'Mergeable proposal action requires a complete base snapshot. actionType=create_skill',
+ );
+ expect(() =>
+ buildProposal({
+ actionType: 'create_skill',
+ baseSnapshot: {
+ absent: true,
+ targetType: 'skill',
+ },
+ }),
+ ).toThrow(
+ 'Mergeable proposal action requires a complete base snapshot. actionType=create_skill',
+ );
+ });
+
+ /**
+ * @example
+ * buildMaintenanceProposalFromPlan({ plan }) keeps target title fallback for consolidate actions.
+ */
+ it('stores targetTitle fallback on non-mergeable skill proposals', () => {
+ 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: 'consolidate_skill',
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ confidence: 0.92,
+ dedupeKey: 'skill:review-practices',
+ evidenceRefs: [{ id: 'topic_1', type: 'topic' }],
+ idempotencyKey: 'source:consolidate_skill:skill:review-practices',
+ operation: {
+ domain: 'skill',
+ input: {
+ approval: { source: 'proposal' },
+ canonicalSkillDocumentId: 'adoc_1',
+ sourceSkillIds: ['adoc_2'],
+ userId: 'user_1',
+ },
+ operation: 'consolidate',
+ },
+ rationale: 'Consolidate overlapping review skills.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillName: 'Review Practices' },
+ },
+ ],
+ plannerVersion: 'test-planner',
+ reviewScope: MaintenanceReviewScope.Nightly,
+ summary: 'Review found a skill consolidation proposal.',
},
results: [
{
- idempotencyKey: 'source:create_skill:skill:code-review',
+ idempotencyKey: 'source:consolidate_skill:skill:review-practices',
status: MaintenanceActionStatus.Proposed,
},
],
});
- expect(proposal?.actions[0].baseSnapshot).toMatchObject({
- targetTitle: 'Code Review',
+ expect(proposal?.actions[0].baseSnapshot).toEqual({
+ targetTitle: 'Review Practices',
});
});
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts
index 2bbd626d540..0dcc00170f4 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts
@@ -3,12 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { MaintenanceProposalMetadata } from '../proposal';
import { createMaintenanceProposalApplyService } from '../proposalApply';
-import {
- MaintenanceActionStatus,
- MaintenanceReviewScope,
- MaintenanceRisk,
- ReviewRunStatus,
-} from '../types';
+import type { RefineMaintenanceSkillInput } from '../skill';
+import { MaintenanceRisk } from '../types';
const { spanEnd, spanSetAttribute, spanSetStatus, startActiveSpan } = vi.hoisted(() => {
interface MockSpan {
@@ -50,14 +46,20 @@ const createProposal = (
contentHash: 'sha256:base',
documentId: 'doc_1',
managed: true,
+ targetType: 'skill',
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',
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: 'new body',
+ description: 'Updated review workflow.',
+ skillDocumentId: 'adoc_1',
+ userId: 'user_1',
+ } as unknown as RefineMaintenanceSkillInput,
+ operation: 'refine' as const,
},
rationale: 'Keep the skill up to date.',
risk: MaintenanceRisk.Medium,
@@ -84,27 +86,23 @@ describe('maintenance proposal apply service', () => {
* @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,
+ it('applies fresh refine_skill proposal actions through replaceSkillContentCAS', async () => {
+ const replaceSkillContentCAS = vi.fn().mockResolvedValue({
+ resourceId: 'adoc_1',
+ status: 'applied',
+ summary: 'Refined managed skill.',
});
+ const createSkillIfAbsent = vi.fn();
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',
+ tools: {
+ createSkillIfAbsent,
+ replaceSkillContentCAS,
+ },
updateProposal,
- writeReceipts,
});
const result = await service.apply({
@@ -115,23 +113,22 @@ describe('maintenance proposal apply service', () => {
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(replaceSkillContentCAS).toHaveBeenCalledWith(
expect.objectContaining({
- plan: expect.objectContaining({ actions: expect.any(Array) }),
- result: expect.objectContaining({ actions: expect.any(Array) }),
+ baseSnapshot: expect.objectContaining({
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ }),
+ bodyMarkdown: 'new body',
+ description: 'Updated review workflow.',
+ idempotencyKey: 'nightly:refine_skill:adoc_1',
+ proposalKey: 'agt_1:refine_skill:agent_document:adoc_1',
+ skillDocumentId: 'adoc_1',
+ userId: 'user_1',
}),
);
+ expect(createSkillIfAbsent).not.toHaveBeenCalled();
expect(result.proposal.status).toBe('applied');
expect(result.proposal.applyAttempts?.[0].actionResults).toEqual([
{
@@ -164,17 +161,103 @@ describe('maintenance proposal apply service', () => {
expect(spanEnd).toHaveBeenCalled();
});
+ /**
+ * @example
+ * expect(tools.createSkillIfAbsent).toHaveBeenCalledWith(expect.objectContaining({ name: 'code-review' }));
+ */
+ it('applies fresh create_skill proposal actions through createSkillIfAbsent', async () => {
+ const createSkillIfAbsent = vi.fn().mockResolvedValue({
+ resourceId: 'adoc_created',
+ status: 'deduped',
+ summary: 'Skill already created.',
+ });
+ const replaceSkillContentCAS = vi.fn();
+ const service = createMaintenanceProposalApplyService({
+ checkAction: vi.fn().mockResolvedValue({ allowed: true }),
+ checkGates: vi.fn().mockResolvedValue({ allowed: true }),
+ now: () => '2026-05-09T01:00:00.000Z',
+ tools: {
+ createSkillIfAbsent,
+ replaceSkillContentCAS,
+ },
+ updateProposal: vi.fn(),
+ });
+
+ const result = await service.apply({
+ agentId: 'agt_1',
+ proposal: createProposal({
+ actionType: 'create_skill',
+ actions: [
+ {
+ actionType: 'create_skill',
+ baseSnapshot: {
+ absent: true,
+ skillName: 'code-review',
+ targetType: 'skill',
+ },
+ evidenceRefs: [],
+ idempotencyKey: 'nightly:create_skill:code-review',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Review preferences',
+ description: 'Reusable review preferences.',
+ name: 'code-review',
+ title: 'Code Review',
+ userId: 'user_1',
+ },
+ operation: 'create',
+ },
+ rationale: 'Create a managed skill.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillName: 'code-review' },
+ },
+ ],
+ proposalKey: 'agt_1:create_skill:skill:code-review',
+ }),
+ sourceId: 'nightly-review:user_1:agt_1:2026-05-09',
+ sourceType: 'agent.nightly_review.requested',
+ userId: 'user_1',
+ });
+
+ expect(createSkillIfAbsent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ bodyMarkdown: 'Review preferences',
+ description: 'Reusable review preferences.',
+ idempotencyKey: 'nightly:create_skill:code-review',
+ name: 'code-review',
+ proposalKey: 'agt_1:create_skill:skill:code-review',
+ title: 'Code Review',
+ userId: 'user_1',
+ }),
+ );
+ expect(replaceSkillContentCAS).not.toHaveBeenCalled();
+ expect(result.proposal.status).toBe('applied');
+ expect(result.proposal.applyAttempts?.[0].actionResults).toEqual([
+ {
+ idempotencyKey: 'nightly:create_skill:code-review',
+ resourceId: 'adoc_created',
+ status: 'deduped',
+ summary: 'Skill already created.',
+ },
+ ]);
+ });
+
/**
* @example
* expect(result.proposal.conflictReason).toBe('document_changed');
*/
- it('skips stale proposal actions without calling the executor', async () => {
- const executePlan = vi.fn();
+ it('skips stale proposal actions without calling safe tools', async () => {
+ const createSkillIfAbsent = vi.fn();
+ const replaceSkillContentCAS = 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',
+ tools: {
+ createSkillIfAbsent,
+ replaceSkillContentCAS,
+ },
updateProposal: vi.fn(),
});
@@ -186,7 +269,8 @@ describe('maintenance proposal apply service', () => {
userId: 'user_1',
});
- expect(executePlan).not.toHaveBeenCalled();
+ expect(createSkillIfAbsent).not.toHaveBeenCalled();
+ expect(replaceSkillContentCAS).not.toHaveBeenCalled();
expect(result.proposal.status).toBe('stale');
expect(result.proposal.conflictReason).toBe('document_changed');
expect(result.proposal.applyAttempts?.[0].actionResults[0]).toMatchObject({
@@ -206,12 +290,16 @@ describe('maintenance proposal apply service', () => {
* expect(result.proposal.applyAttempts?.[0].actionResults[0].status).toBe('skipped_unsupported');
*/
it('records unsupported actions without applying them', async () => {
- const executePlan = vi.fn();
+ const createSkillIfAbsent = vi.fn();
+ const replaceSkillContentCAS = 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',
+ tools: {
+ createSkillIfAbsent,
+ replaceSkillContentCAS,
+ },
updateProposal: vi.fn(),
});
@@ -235,7 +323,8 @@ describe('maintenance proposal apply service', () => {
userId: 'user_1',
});
- expect(executePlan).not.toHaveBeenCalled();
+ expect(createSkillIfAbsent).not.toHaveBeenCalled();
+ expect(replaceSkillContentCAS).not.toHaveBeenCalled();
expect(result.proposal.status).toBe('failed');
expect(result.proposal.applyAttempts?.[0].actionResults).toEqual([
{
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts
index ed1b2533acc..fd82e2d408a 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts
@@ -1,5 +1,6 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import type { MaintenanceProposalPreflightAdapters } from '../proposalPreflight';
import { createMaintenanceProposalPreflightService } from '../proposalPreflight';
import { MaintenanceRisk } from '../types';
@@ -11,6 +12,7 @@ const createRefineAction = (contentHash = 'sha256:base') => ({
documentId: 'doc_1',
managed: true,
targetTitle: 'Skill Index',
+ targetType: 'skill' as const,
writable: true,
},
evidenceRefs: [],
@@ -25,16 +27,71 @@ const createRefineAction = (contentHash = 'sha256:base') => ({
target: { skillDocumentId: 'adoc_1' },
});
+const createCreateAction = () => ({
+ actionType: 'create_skill' as const,
+ baseSnapshot: {
+ absent: true,
+ skillName: 'code-review',
+ targetTitle: 'Code Review',
+ targetType: 'skill' as const,
+ },
+ evidenceRefs: [],
+ idempotencyKey: 'key-create',
+ operation: {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: 'Review preferences',
+ name: 'code-review',
+ title: 'Code Review',
+ userId: 'user_1',
+ },
+ operation: 'create' as const,
+ },
+ rationale: 'Create skill',
+ risk: MaintenanceRisk.Medium,
+ target: { skillName: 'code-review' },
+});
+
+const createAdapters = (
+ overrides: Partial<MaintenanceProposalPreflightAdapters> = {},
+): MaintenanceProposalPreflightAdapters => ({
+ isSkillNameAvailable: async () => true,
+ readSkillTargetSnapshot: async () => ({
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetTitle: 'Skill Index',
+ writable: true,
+ }),
+ ...overrides,
+});
+
describe('maintenance proposal preflight', () => {
/**
* @example
* expect(result.allowed).toBe(true);
*/
- it('allows unchanged skill document targets', async () => {
+ it('allows fresh refine_skill proposals with matching snapshot', async () => {
+ const readSkillTargetSnapshot = vi.fn(createAdapters().readSkillTargetSnapshot);
+ const service = createMaintenanceProposalPreflightService(
+ createAdapters({ readSkillTargetSnapshot }),
+ );
+
+ await expect(service.checkAction(createRefineAction())).resolves.toEqual({ allowed: true });
+ expect(readSkillTargetSnapshot).toHaveBeenCalledWith('adoc_1');
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('content_changed');
+ */
+ it('rejects drifted refine_skill when content hash changed', async () => {
const service = createMaintenanceProposalPreflightService({
- readSkillTarget: async () => ({
+ ...createAdapters(),
+ readSkillTargetSnapshot: async () => ({
agentDocumentId: 'adoc_1',
- contentHash: 'sha256:base',
+ contentHash: 'sha256:current',
documentId: 'doc_1',
managed: true,
targetTitle: 'Skill Index',
@@ -42,28 +99,72 @@ describe('maintenance proposal preflight', () => {
}),
});
- await expect(service.checkAction(createRefineAction())).resolves.toEqual({ allowed: true });
+ await expect(service.checkAction(createRefineAction())).resolves.toEqual({
+ allowed: false,
+ reason: 'content_changed',
+ });
});
/**
* @example
- * expect(result.reason).toBe('document_changed');
+ * expect(result.reason).toBe('target_type_changed');
*/
- it('marks changed content as stale', async () => {
+ it('rejects refine_skill when frozen target identity drifts from the base snapshot', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createRefineAction();
+
+ await expect(
+ service.checkAction({
+ ...action,
+ target: { skillDocumentId: 'adoc_2' },
+ }),
+ ).resolves.toEqual({
+ allowed: false,
+ reason: 'target_type_changed',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('target_type_changed');
+ */
+ it('rejects refine_skill when frozen operation identity drifts from the base snapshot', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createRefineAction();
+
+ await expect(
+ service.checkAction({
+ ...action,
+ operation: {
+ ...action.operation,
+ input: { ...action.operation.input, skillDocumentId: 'adoc_2' },
+ },
+ }),
+ ).resolves.toEqual({
+ allowed: false,
+ reason: 'target_type_changed',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('target_unmanaged');
+ */
+ it('rejects unmanaged targets', async () => {
const service = createMaintenanceProposalPreflightService({
- readSkillTarget: async () => ({
+ ...createAdapters(),
+ readSkillTargetSnapshot: async () => ({
agentDocumentId: 'adoc_1',
- contentHash: 'sha256:current',
+ contentHash: 'sha256:base',
documentId: 'doc_1',
- managed: true,
- targetTitle: 'Skill Index',
+ managed: false,
writable: true,
}),
});
await expect(service.checkAction(createRefineAction())).resolves.toEqual({
allowed: false,
- reason: 'document_changed',
+ reason: 'target_unmanaged',
});
});
@@ -71,14 +172,15 @@ describe('maintenance proposal preflight', () => {
* @example
* expect(result.reason).toBe('target_not_writable');
*/
- it('rejects unmanaged or readonly targets', async () => {
+ it('rejects readonly targets', async () => {
const service = createMaintenanceProposalPreflightService({
- readSkillTarget: async () => ({
+ ...createAdapters(),
+ readSkillTargetSnapshot: async () => ({
agentDocumentId: 'adoc_1',
contentHash: 'sha256:base',
documentId: 'doc_1',
- managed: false,
- writable: true,
+ managed: true,
+ writable: false,
}),
});
@@ -88,13 +190,49 @@ describe('maintenance proposal preflight', () => {
});
});
+ /**
+ * @example
+ * expect(result.reason).toBe('snapshot_missing');
+ */
+ it('does not report missing base snapshots as target_deleted', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createRefineAction();
+ const { baseSnapshot: _baseSnapshot, ...actionWithoutSnapshot } = action;
+
+ await expect(service.checkAction(actionWithoutSnapshot)).resolves.toEqual({
+ allowed: false,
+ reason: 'snapshot_missing',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('snapshot_incomplete');
+ */
+ it('rejects incomplete refine_skill base snapshots', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createRefineAction();
+ const { contentHash: _contentHash, ...incompleteSnapshot } = action.baseSnapshot;
+
+ await expect(
+ service.checkAction({
+ ...action,
+ baseSnapshot: incompleteSnapshot,
+ }),
+ ).resolves.toEqual({
+ allowed: false,
+ reason: 'snapshot_incomplete',
+ });
+ });
+
/**
* @example
* expect(result.reason).toBe('target_deleted');
*/
it('rejects missing targets', async () => {
const service = createMaintenanceProposalPreflightService({
- readSkillTarget: async () => undefined,
+ ...createAdapters(),
+ readSkillTargetSnapshot: async () => undefined,
});
await expect(service.checkAction(createRefineAction())).resolves.toEqual({
@@ -102,4 +240,93 @@ describe('maintenance proposal preflight', () => {
reason: 'target_deleted',
});
});
+
+ /**
+ * @example
+ * expect(result.allowed).toBe(true);
+ */
+ it('allows create_skill proposals when stable name is still absent', async () => {
+ const isSkillNameAvailable = vi.fn(async () => true);
+ const service = createMaintenanceProposalPreflightService(
+ createAdapters({ isSkillNameAvailable }),
+ );
+
+ await expect(service.checkAction(createCreateAction())).resolves.toEqual({ allowed: true });
+ expect(isSkillNameAvailable).toHaveBeenCalledWith({
+ name: 'code-review',
+ userId: 'user_1',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('target_conflict');
+ */
+ it('rejects create_skill proposals when stable name is now taken', async () => {
+ const service = createMaintenanceProposalPreflightService(
+ createAdapters({ isSkillNameAvailable: async () => false }),
+ );
+
+ await expect(service.checkAction(createCreateAction())).resolves.toEqual({
+ allowed: false,
+ reason: 'target_conflict',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('target_type_changed');
+ */
+ it('rejects create_skill when frozen target name drifts from the base snapshot', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createCreateAction();
+
+ await expect(
+ service.checkAction({
+ ...action,
+ target: { skillName: 'incident-review' },
+ }),
+ ).resolves.toEqual({
+ allowed: false,
+ reason: 'target_type_changed',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('target_type_changed');
+ */
+ it('rejects create_skill when frozen operation name drifts from the base snapshot', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createCreateAction();
+
+ await expect(
+ service.checkAction({
+ ...action,
+ operation: {
+ ...action.operation,
+ input: { ...action.operation.input, name: 'incident-review' },
+ },
+ }),
+ ).resolves.toEqual({
+ allowed: false,
+ reason: 'target_type_changed',
+ });
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('unsupported');
+ */
+ it('keeps unsupported actions unsupported', async () => {
+ const service = createMaintenanceProposalPreflightService(createAdapters());
+ const action = createRefineAction();
+
+ await expect(
+ service.checkAction({ ...action, actionType: 'consolidate_skill' }),
+ ).resolves.toEqual({
+ allowed: false,
+ reason: 'unsupported',
+ });
+ });
});
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/proposalSnapshot.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/proposalSnapshot.test.ts
new file mode 100644
index 00000000000..bfd866daeeb
--- /dev/null
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalSnapshot.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createMaintenanceProposalSnapshotService } from '../proposalSnapshot';
+
+describe('maintenance proposal snapshot service', () => {
+ /**
+ * @example
+ * expect(snapshot).toEqual({ targetType: 'skill', contentHash: 'sha256:base' });
+ */
+ it('captures complete refine_skill base snapshots', async () => {
+ const readSkillTargetSnapshot = vi.fn(async () => ({
+ agentDocumentId: 'agent-doc-1',
+ contentHash: 'sha256:base',
+ documentId: 'doc-1',
+ documentUpdatedAt: '2026-05-09T00:00:00.000Z',
+ managed: true,
+ targetTitle: 'Code Review',
+ writable: true,
+ }));
+ const service = createMaintenanceProposalSnapshotService({
+ isSkillNameAvailable: async () => true,
+ readSkillTargetSnapshot,
+ });
+
+ await expect(
+ service.captureActionSnapshot({
+ actionType: 'refine_skill',
+ agentId: 'agent-1',
+ input: { skillDocumentId: 'agent-doc-1' },
+ userId: 'user-1',
+ }),
+ ).resolves.toEqual({
+ agentDocumentId: 'agent-doc-1',
+ contentHash: 'sha256:base',
+ documentId: 'doc-1',
+ documentUpdatedAt: '2026-05-09T00:00:00.000Z',
+ managed: true,
+ targetTitle: 'Code Review',
+ targetType: 'skill',
+ writable: true,
+ });
+ expect(readSkillTargetSnapshot).toHaveBeenCalledWith('agent-doc-1');
+ });
+
+ /**
+ * @example
+ * expect(snapshot).toMatchObject({ absent: true, skillName: 'code-review' });
+ */
+ it('captures absent-target snapshots for create_skill', async () => {
+ const isSkillNameAvailable = vi.fn(async () => true);
+ const service = createMaintenanceProposalSnapshotService({
+ isSkillNameAvailable,
+ readSkillTargetSnapshot: async () => undefined,
+ });
+
+ await expect(
+ service.captureActionSnapshot({
+ actionType: 'create_skill',
+ agentId: 'agent-1',
+ input: { name: 'code-review', title: 'Code Review' },
+ userId: 'user-1',
+ }),
+ ).resolves.toEqual({
+ absent: true,
+ skillName: 'code-review',
+ targetTitle: 'Code Review',
+ targetType: 'skill',
+ });
+ expect(isSkillNameAvailable).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ name: 'code-review',
+ userId: 'user-1',
+ });
+ });
+
+ /**
+ * @example
+ * expect(capture).rejects.toThrow('Skill name is already taken');
+ */
+ it('rejects create_skill snapshots when the stable skill name is already taken', async () => {
+ const service = createMaintenanceProposalSnapshotService({
+ isSkillNameAvailable: async () => false,
+ readSkillTargetSnapshot: async () => undefined,
+ });
+
+ await expect(
+ service.captureActionSnapshot({
+ actionType: 'create_skill',
+ agentId: 'agent-1',
+ input: { name: 'code-review' },
+ userId: 'user-1',
+ }),
+ ).rejects.toThrow('Skill name is already taken');
+ });
+});
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts
index bc5b1e4fbea..fd4b374047e 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts
@@ -1,9 +1,93 @@
// @vitest-environment node
-import { describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BriefItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import type * as SkillManagementModule from '@/server/services/skillManagement';
-import { listServerProposalActivity } from '../serverRuntime';
+import type * as ToolFirstRuntimeModule from '../agent';
+import type { NightlyReviewContext } from '../nightlyCollector';
+import {
+ createServerNightlyReviewPolicyOptions,
+ listServerProposalActivity,
+} from '../serverRuntime';
+import { MaintenanceActionStatus, ReviewRunStatus } from '../types';
+
+const mocks = vi.hoisted(() => ({
+ createMaintenanceExecutorService: vi.fn(() => ({
+ execute: vi.fn(async () => {
+ throw new Error('legacy executor must not execute nightly mutations');
+ }),
+ })),
+ createMaintenancePlannerService: vi.fn(() => ({
+ plan: vi.fn(() => {
+ throw new Error('legacy planner must not plan nightly mutations');
+ }),
+ })),
+ briefCreate: vi.fn(),
+ briefListUnresolvedByAgentAndTrigger: vi.fn(async () => []),
+ briefUpdateMetadata: vi.fn(),
+ initModelRuntimeFromDB: vi.fn(async () => ({ chat: vi.fn() })),
+ runMaintenanceToolFirstRuntime: vi.fn(),
+ skillReadTargetSnapshot: vi.fn(),
+ skillReplaceSkillIndex: vi.fn(),
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
+}));
+
+vi.mock('../executor', () => ({
+ createMaintenanceExecutorService: mocks.createMaintenanceExecutorService,
+}));
+
+vi.mock('../planner', () => ({
+ createMaintenancePlannerService: mocks.createMaintenancePlannerService,
+}));
+
+vi.mock('../agent', async (importOriginal) => ({
+ ...(await importOriginal<typeof ToolFirstRuntimeModule>()),
+ runMaintenanceToolFirstRuntime: mocks.runMaintenanceToolFirstRuntime,
+}));
+
+vi.mock('@/database/models/agentSignal/nightlyReview', () => ({
+ AgentSignalNightlyReviewModel: class {
+ listActiveAgentTargets = vi.fn(async () => []);
+ },
+}));
+
+vi.mock('@/database/models/agentSignal/reviewContext', () => ({
+ AgentSignalReviewContextModel: class {
+ canAgentRunSelfIteration = vi.fn(async () => true);
+ listDocumentActivity = vi.fn(async () => []);
+ listRelevantMemories = vi.fn(async () => []);
+ listToolActivity = vi.fn(async () => []);
+ listTopicActivity = vi.fn(async () => []);
+ },
+}));
+
+vi.mock('@/database/models/brief', () => ({
+ BriefModel: class {
+ create = mocks.briefCreate;
+ listUnresolvedByAgentAndTrigger = mocks.briefListUnresolvedByAgentAndTrigger;
+ updateMetadata = mocks.briefUpdateMetadata;
+ },
+}));
+
+vi.mock('@/server/services/skillManagement', async (importOriginal) => ({
+ ...(await importOriginal<typeof SkillManagementModule>()),
+ SkillManagementDocumentService: class {
+ createSkill = vi.fn();
+ getSkill = vi.fn();
+ listSkills = vi.fn(async () => []);
+ readSkillTargetSnapshot = mocks.skillReadTargetSnapshot;
+ replaceSkillIndex = mocks.skillReplaceSkillIndex;
+ },
+}));
+
+vi.mock('@/server/services/agentSignal/featureGate', () => ({
+ isAgentSignalEnabledForUser: vi.fn(async () => true),
+}));
const baseBrief = (overrides: Partial<BriefItem>): BriefItem => ({
actions: null,
@@ -60,6 +144,122 @@ const proposalMetadata = (
},
});
+const createNightlyContext = (): NightlyReviewContext => ({
+ 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-09T02:00:00.000Z',
+ reviewWindowStart: '2026-05-09T00:00:00.000Z',
+ toolActivity: [],
+ topics: [],
+ userId: 'user-1',
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.briefCreate.mockResolvedValue(baseBrief({ id: 'brief-created' }));
+ mocks.briefListUnresolvedByAgentAndTrigger.mockResolvedValue([]);
+ mocks.briefUpdateMetadata.mockResolvedValue(undefined);
+ mocks.initModelRuntimeFromDB.mockResolvedValue({ chat: vi.fn() });
+ mocks.skillReadTargetSnapshot.mockResolvedValue(undefined);
+ mocks.skillReplaceSkillIndex.mockResolvedValue(undefined);
+ mocks.runMaintenanceToolFirstRuntime.mockResolvedValue({
+ content: 'Created a skill.',
+ stepCount: 3,
+ toolCalls: [
+ {
+ apiName: 'createSkillIfAbsent',
+ arguments: JSON.stringify({
+ bodyMarkdown: 'Use concise answers.',
+ idempotencyKey: 'op-create-skill',
+ name: 'concise-answers',
+ title: 'Concise answers',
+ }),
+ id: 'tool-call-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ usage: [],
+ writeOutcomes: [
+ {
+ result: {
+ receiptId: 'op-create-skill',
+ resourceId: 'skill-1',
+ status: 'applied',
+ summary: 'Created managed skill concise-answers.',
+ },
+ toolName: 'createSkillIfAbsent',
+ },
+ ],
+ });
+});
+
+afterEach(() => {
+ delete (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient;
+});
+
+const createSkillProposalToolArguments = () => ({
+ actions: [
+ {
+ actionType: 'create_skill',
+ applyMode: 'proposal_only',
+ baseSnapshot: {
+ absent: true,
+ skillName: 'concise-answers',
+ targetType: 'skill',
+ },
+ confidence: 0.9,
+ dedupeKey: 'skill:concise-answers',
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'source-1:create_skill:concise-answers',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Prefer concise answers.',
+ name: 'concise-answers',
+ title: 'Concise answers',
+ userId: 'user-1',
+ },
+ operation: 'create',
+ },
+ rationale: 'User repeatedly asks for concise answers.',
+ risk: 'low',
+ target: { skillName: 'concise-answers' },
+ },
+ ],
+ idempotencyKey: 'proposal-op-1',
+ proposalKey: 'agent-1:create_skill:skill:concise-answers',
+ summary: 'Review concise answers skill.',
+});
+
describe('listServerProposalActivity', () => {
/**
* @example
@@ -279,3 +479,362 @@ describe('listServerProposalActivity', () => {
expect(digest.supersededCount).toBe(1);
});
});
+
+describe('createServerNightlyReviewPolicyOptions', () => {
+ /**
+ * @example
+ * createServerNightlyReviewPolicyOptions delegates nightly mutation authority to the
+ * tool-first runtime instead of the legacy reviewer -> planner -> executor chain.
+ */
+ it('runs nightly maintenance through the tool-first runtime with DB model runtime and real tools', async () => {
+ const modelRuntime = { chat: vi.fn() };
+ mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
+
+ const options = createServerNightlyReviewPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
+ });
+ const result = await options.runMaintenanceReviewAgent({
+ context: createNightlyContext(),
+ localDate: '2026-05-09',
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-09',
+ userId: 'user-1',
+ });
+
+ expect(mocks.initModelRuntimeFromDB).toHaveBeenCalledTimes(1);
+ expect(mocks.runMaintenanceToolFirstRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ maxSteps: 10,
+ modelRuntime,
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-09',
+ userId: 'user-1',
+ }),
+ );
+ expect(mocks.createMaintenancePlannerService).not.toHaveBeenCalled();
+ expect(mocks.createMaintenanceExecutorService).not.toHaveBeenCalled();
+ expect(result.stepCount).toBe(3);
+ expect(result.execution).toMatchObject({
+ actions: [
+ {
+ idempotencyKey: 'op-create-skill',
+ resourceId: 'skill-1',
+ status: MaintenanceActionStatus.Applied,
+ },
+ ],
+ sourceId: 'nightly-review:user-1:agent-1:2026-05-09',
+ status: ReviewRunStatus.Completed,
+ });
+ expect(result.projectionPlan.actions).toHaveLength(1);
+ expect(result.projectionPlan.actions[0]).toMatchObject({
+ actionType: 'create_skill',
+ idempotencyKey: 'op-create-skill',
+ });
+ });
+
+ /**
+ * @example
+ * createServerNightlyReviewPolicyOptions exposes createMaintenanceProposal with real brief
+ * persistence instead of returning an unsupported tool result.
+ */
+ it('persists proposal lifecycle tool writes through Daily Brief proposal metadata', async () => {
+ const modelRuntime = { chat: vi.fn() };
+ const toolArguments = createSkillProposalToolArguments();
+ (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient = {
+ expire: vi.fn(async () => 1),
+ hgetall: vi.fn(async () => ({})),
+ hset: vi.fn(async () => 1),
+ set: vi.fn(async () => 'OK'),
+ zadd: vi.fn(async () => 1),
+ };
+ mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
+ mocks.runMaintenanceToolFirstRuntime.mockImplementation(async (input) => {
+ const result = await input.tools.createMaintenanceProposal({
+ actions: toolArguments.actions,
+ idempotencyKey: toolArguments.idempotencyKey,
+ metadata: {},
+ proposalKey: toolArguments.proposalKey,
+ summary: toolArguments.summary,
+ userId: 'user-1',
+ });
+
+ return {
+ content: 'Created a proposal.',
+ stepCount: 2,
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify(toolArguments),
+ id: 'call-proposal-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ usage: [],
+ writeOutcomes: [{ result, toolName: 'createMaintenanceProposal' }],
+ };
+ });
+
+ const options = createServerNightlyReviewPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
+ });
+ const result = await options.runMaintenanceReviewAgent({
+ context: createNightlyContext(),
+ localDate: '2026-05-09',
+ sourceId: 'source-1',
+ userId: 'user-1',
+ });
+
+ expect(mocks.briefCreate).toHaveBeenCalledTimes(1);
+ expect(mocks.briefCreate.mock.calls[0]?.[0]).toMatchObject({
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: {
+ actions: [
+ {
+ actionType: 'create_skill',
+ operation: {
+ domain: 'skill',
+ operation: 'create',
+ },
+ },
+ ],
+ proposalKey: 'agent-1:create_skill:skill:concise-answers',
+ status: 'pending',
+ },
+ },
+ },
+ },
+ type: 'decision',
+ });
+ expect(result.execution.actions[0]).toMatchObject({
+ idempotencyKey: 'source-1:create_skill:concise-answers',
+ resourceId: 'brief-created',
+ status: MaintenanceActionStatus.Proposed,
+ });
+ expect(result.projectionPlan.actions[0]).toMatchObject({
+ actionType: 'create_skill',
+ operation: {
+ domain: 'skill',
+ operation: 'create',
+ },
+ });
+ });
+
+ /**
+ * @example
+ * createMaintenanceProposal({ actions: [{ actionType: 'refine_skill' }] })
+ * snapshots the target skill on the server before creating the approval brief.
+ */
+ it('enriches refine skill proposals with server-side base snapshots', async () => {
+ const modelRuntime = { chat: vi.fn() };
+ const toolArguments = {
+ actions: [
+ {
+ actionType: 'refine_skill',
+ applyMode: 'proposal_only',
+ confidence: 0.9,
+ dedupeKey: 'skill:skill-doc-1',
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'source-1:refine_skill:skill-doc-1',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'Updated skill body.',
+ skillDocumentId: 'skill-doc-1',
+ userId: 'user-1',
+ },
+ operation: 'refine',
+ },
+ rationale: 'Repeated tool failures show this skill needs a safer workflow.',
+ risk: 'low',
+ target: { skillDocumentId: 'skill-doc-1' },
+ },
+ ],
+ idempotencyKey: 'proposal-op-refine-1',
+ proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',
+ summary: 'Review skill refinement.',
+ };
+ (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient = {
+ expire: vi.fn(async () => 1),
+ hgetall: vi.fn(async () => ({})),
+ hset: vi.fn(async () => 1),
+ set: vi.fn(async () => 'OK'),
+ zadd: vi.fn(async () => 1),
+ };
+ mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
+ mocks.skillReadTargetSnapshot.mockResolvedValue({
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'hash-before',
+ documentId: 'document-1',
+ managed: true,
+ targetTitle: 'Existing skill',
+ writable: true,
+ });
+ mocks.runMaintenanceToolFirstRuntime.mockImplementation(async (input) => {
+ const result = await input.tools.createMaintenanceProposal({
+ actions: toolArguments.actions,
+ idempotencyKey: toolArguments.idempotencyKey,
+ metadata: {},
+ proposalKey: toolArguments.proposalKey,
+ summary: toolArguments.summary,
+ userId: 'user-1',
+ });
+
+ return {
+ content: 'Created a refine proposal.',
+ stepCount: 2,
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify(toolArguments),
+ id: 'call-proposal-refine-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ usage: [],
+ writeOutcomes: [{ result, toolName: 'createMaintenanceProposal' }],
+ };
+ });
+
+ const options = createServerNightlyReviewPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
+ });
+ const result = await options.runMaintenanceReviewAgent({
+ context: createNightlyContext(),
+ localDate: '2026-05-09',
+ sourceId: 'source-1',
+ userId: 'user-1',
+ });
+
+ expect(mocks.briefCreate).toHaveBeenCalledTimes(1);
+ expect(mocks.briefCreate.mock.calls[0]?.[0]).toMatchObject({
+ metadata: {
+ agentSignal: {
+ nightlySelfReview: {
+ maintenanceProposal: {
+ actions: [
+ {
+ actionType: 'refine_skill',
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'hash-before',
+ documentId: 'document-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ operation: {
+ domain: 'skill',
+ operation: 'refine',
+ },
+ },
+ ],
+ proposalKey: 'agent-1:refine_skill:agent_document:skill-doc-1',
+ status: 'pending',
+ },
+ },
+ },
+ },
+ type: 'decision',
+ });
+ expect(result.execution.actions[0]).toMatchObject({
+ idempotencyKey: 'proposal-op-refine-1',
+ resourceId: 'brief-created',
+ status: MaintenanceActionStatus.Skipped,
+ });
+ });
+
+ /**
+ * @example
+ * replaceSkillContentCAS({ skillDocumentId: 'skill-index-1', bodyMarkdown: '...' })
+ * captures the CAS snapshot and normalizes index ids to bundle ids before preflight.
+ */
+ it('enriches direct refine skill writes with server-side CAS snapshots', async () => {
+ const modelRuntime = { chat: vi.fn() };
+ (globalThis as { __agentSignalRedisClient?: unknown }).__agentSignalRedisClient = {
+ expire: vi.fn(async () => 1),
+ hgetall: vi.fn(async () => ({})),
+ hset: vi.fn(async () => 1),
+ set: vi.fn(async () => 'OK'),
+ zadd: vi.fn(async () => 1),
+ };
+ mocks.initModelRuntimeFromDB.mockResolvedValue(modelRuntime);
+ mocks.skillReadTargetSnapshot.mockResolvedValue({
+ agentDocumentId: 'skill-bundle-1',
+ contentHash: 'hash-before',
+ documentId: 'document-1',
+ managed: true,
+ targetTitle: 'Existing skill',
+ writable: true,
+ });
+ mocks.skillReplaceSkillIndex.mockResolvedValue({
+ bundle: { agentDocumentId: 'skill-bundle-1' },
+ name: 'existing-skill',
+ });
+ mocks.runMaintenanceToolFirstRuntime.mockImplementation(async (input) => {
+ const result = await input.tools.replaceSkillContentCAS({
+ bodyMarkdown: 'Updated skill body.',
+ idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',
+ skillDocumentId: 'skill-index-1',
+ userId: 'user-1',
+ } as Parameters<typeof input.tools.replaceSkillContentCAS>[0]);
+
+ return {
+ content: 'Updated a skill.',
+ stepCount: 2,
+ toolCalls: [
+ {
+ apiName: 'replaceSkillContentCAS',
+ arguments: JSON.stringify({
+ bodyMarkdown: 'Updated skill body.',
+ idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',
+ skillDocumentId: 'skill-index-1',
+ }),
+ id: 'call-refine-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ usage: [],
+ writeOutcomes: [{ result, toolName: 'replaceSkillContentCAS' }],
+ };
+ });
+
+ const options = createServerNightlyReviewPolicyOptions({
+ agentId: 'agent-1',
+ db: {} as unknown as LobeChatDatabase,
+ selfIterationEnabled: true,
+ userId: 'user-1',
+ });
+ const result = await options.runMaintenanceReviewAgent({
+ context: createNightlyContext(),
+ localDate: '2026-05-09',
+ sourceId: 'source-1',
+ userId: 'user-1',
+ });
+
+ expect(mocks.skillReplaceSkillIndex).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentDocumentId: 'skill-bundle-1',
+ agentId: 'agent-1',
+ bodyMarkdown: 'Updated skill body.',
+ }),
+ );
+ expect(result.execution.actions[0]).toMatchObject({
+ idempotencyKey: 'source-1:replaceSkillContentCAS:skill-index-1',
+ resourceId: 'skill-bundle-1',
+ status: MaintenanceActionStatus.Applied,
+ });
+ });
+});
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts
index 8e620d472e9..830807827af 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/tools.test.ts
@@ -1,6 +1,8 @@
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { MaintenanceProposalBaseSnapshot } from '../proposal';
+
const { spanEnd, spanRecordException, spanSetAttribute, spanSetStatus, startActiveSpan } =
vi.hoisted(() => {
interface MockSpan {
@@ -32,6 +34,15 @@ vi.mock('@lobechat/observability-otel/modules/agent-signal', () => ({
tracer: { startActiveSpan },
}));
+const refineSkillBaseSnapshot = {
+ agentDocumentId: 'skill-1',
+ contentHash: 'hash-before',
+ documentId: 'document-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+} satisfies MaintenanceProposalBaseSnapshot;
+
describe('createMaintenanceTools', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -54,6 +65,7 @@ describe('createMaintenanceTools', () => {
});
const result = await tools.replaceSkillContentCAS({
+ baseSnapshot: refineSkillBaseSnapshot,
bodyMarkdown: 'Updated body',
idempotencyKey: 'op-replace-1',
proposalKey: 'proposal-skill-1',
@@ -105,6 +117,7 @@ describe('createMaintenanceTools', () => {
});
const result = await tools.replaceSkillContentCAS({
+ baseSnapshot: refineSkillBaseSnapshot,
bodyMarkdown: 'Updated body',
idempotencyKey: 'op-replace-1',
proposalKey: 'proposal-skill-1',
@@ -290,6 +303,7 @@ describe('createMaintenanceTools', () => {
});
const result = await tools.replaceSkillContentCAS({
+ baseSnapshot: refineSkillBaseSnapshot,
bodyMarkdown: 'Updated body',
idempotencyKey: 'op-replace-success-1',
proposalKey: 'proposal-skill-1',
@@ -311,6 +325,209 @@ describe('createMaintenanceTools', () => {
);
});
+ /**
+ * @example
+ * await tools.replaceSkillContentCAS({ patchMarkdown: 'diff only' });
+ * skips unsupported refine payloads before calling replaceSkill.
+ */
+ it('rejects patch-only refine payload before mutation with skipped_unsupported and receipt', async () => {
+ const { createMaintenanceTools } = await import('../tools');
+ const preflight = vi.fn().mockResolvedValue({ allowed: true });
+ const replaceSkill = vi.fn();
+ const reserveOperation = vi.fn().mockResolvedValue({ reserved: true });
+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-invalid-refine' });
+ const tools = createMaintenanceTools({
+ preflight,
+ replaceSkill,
+ reserveOperation,
+ writeReceipt,
+ });
+ const patchOnlyInput = {
+ baseSnapshot: refineSkillBaseSnapshot,
+ idempotencyKey: 'op-invalid-refine-1',
+ patchMarkdown: '--- old\n+++ new',
+ skillDocumentId: 'skill-1',
+ userId: 'user-1',
+ } as unknown as Parameters<typeof tools.replaceSkillContentCAS>[0];
+
+ const result = await tools.replaceSkillContentCAS(patchOnlyInput);
+
+ expect(preflight).not.toHaveBeenCalled();
+ expect(replaceSkill).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ receiptId: 'receipt-invalid-refine',
+ resourceId: 'skill-1',
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a non-empty body.',
+ });
+ expect(writeReceipt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ idempotencyKey: 'op-invalid-refine-1',
+ status: 'skipped_unsupported',
+ }),
+ );
+ expect(reserveOperation).toHaveBeenCalledWith('op-invalid-refine-1');
+ });
+
+ /**
+ * @example
+ * await tools.replaceSkillContentCAS({ bodyMarkdown: 'Updated body' });
+ * skips unsupported refine payloads without a complete base snapshot.
+ */
+ it('rejects missing baseSnapshot refine payload before mutation with skipped_unsupported and receipt', async () => {
+ const { createMaintenanceTools } = await import('../tools');
+ const preflight = vi.fn().mockResolvedValue({ allowed: true });
+ const replaceSkill = vi.fn();
+ const tools = createMaintenanceTools({
+ preflight,
+ replaceSkill,
+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),
+ writeReceipt: vi.fn().mockResolvedValue({ receiptId: 'receipt-missing-snapshot' }),
+ });
+ const missingSnapshotInput = {
+ bodyMarkdown: 'Updated body',
+ idempotencyKey: 'op-missing-snapshot-1',
+ skillDocumentId: 'skill-1',
+ userId: 'user-1',
+ } as unknown as Parameters<typeof tools.replaceSkillContentCAS>[0];
+
+ const result = await tools.replaceSkillContentCAS(missingSnapshotInput);
+
+ expect(preflight).not.toHaveBeenCalled();
+ expect(replaceSkill).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ receiptId: 'receipt-missing-snapshot',
+ resourceId: 'skill-1',
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a complete base snapshot.',
+ });
+ });
+
+ /**
+ * @example
+ * await tools.replaceSkillContentCAS({ baseSnapshot: { targetType: 'skill' } });
+ * skips unsupported refine payloads with incomplete snapshots.
+ */
+ it('rejects incomplete baseSnapshot refine payload before mutation with skipped_unsupported and receipt', async () => {
+ const { createMaintenanceTools } = await import('../tools');
+ const preflight = vi.fn().mockResolvedValue({ allowed: true });
+ const replaceSkill = vi.fn();
+ const tools = createMaintenanceTools({
+ preflight,
+ replaceSkill,
+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),
+ writeReceipt: vi.fn().mockResolvedValue({ receiptId: 'receipt-incomplete-snapshot' }),
+ });
+
+ const result = await tools.replaceSkillContentCAS({
+ baseSnapshot: {
+ agentDocumentId: 'skill-1',
+ contentHash: 'hash-before',
+ documentId: '',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ bodyMarkdown: 'Updated body',
+ idempotencyKey: 'op-incomplete-snapshot-1',
+ skillDocumentId: 'skill-1',
+ userId: 'user-1',
+ });
+
+ expect(preflight).not.toHaveBeenCalled();
+ expect(replaceSkill).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ receiptId: 'receipt-incomplete-snapshot',
+ resourceId: 'skill-1',
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a complete base snapshot.',
+ });
+ });
+
+ /**
+ * @example
+ * await tools.createSkillIfAbsent({ name: ' ', bodyMarkdown: '' });
+ * skips unsupported create payloads before calling createSkill.
+ */
+ it('rejects missing or blank create body and name before mutation with skipped_unsupported and receipt', async () => {
+ const { createMaintenanceTools } = await import('../tools');
+ const createSkill = vi.fn();
+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-invalid-create' });
+ const tools = createMaintenanceTools({
+ createSkill,
+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),
+ writeReceipt,
+ });
+
+ const missingInput = {
+ idempotencyKey: 'op-invalid-create-missing-1',
+ userId: 'user-1',
+ } as unknown as Parameters<typeof tools.createSkillIfAbsent>[0];
+ const missingResult = await tools.createSkillIfAbsent(missingInput);
+ const blankResult = await tools.createSkillIfAbsent({
+ bodyMarkdown: '',
+ idempotencyKey: 'op-invalid-create-1',
+ name: ' ',
+ userId: 'user-1',
+ });
+
+ expect(createSkill).not.toHaveBeenCalled();
+ expect(missingResult).toEqual({
+ receiptId: 'receipt-invalid-create',
+ status: 'skipped_unsupported',
+ summary: 'Skill creation requires a non-empty name and body.',
+ });
+ expect(blankResult).toEqual({
+ receiptId: 'receipt-invalid-create',
+ status: 'skipped_unsupported',
+ summary: 'Skill creation requires a non-empty name and body.',
+ });
+ expect(writeReceipt).toHaveBeenCalledWith(
+ expect.objectContaining({
+ idempotencyKey: 'op-invalid-create-1',
+ status: 'skipped_unsupported',
+ }),
+ );
+ });
+
+ /**
+ * @example
+ * await tools.createSkillIfAbsent({ idempotencyKey: 'same-key' });
+ * returns a deduped receipt without calling createSkill.
+ */
+ it('keeps dedupe behavior for valid writes', async () => {
+ const { createMaintenanceTools } = await import('../tools');
+ const createSkill = vi.fn();
+ const writeReceipt = vi.fn().mockResolvedValue({ receiptId: 'receipt-deduped-create' });
+ const tools = createMaintenanceTools({
+ createSkill,
+ reserveOperation: vi.fn().mockResolvedValue({
+ existing: {
+ resourceId: 'skill-created-1',
+ status: 'applied',
+ summary: 'Already created.',
+ },
+ reserved: false,
+ }),
+ writeReceipt,
+ });
+
+ const result = await tools.createSkillIfAbsent({
+ bodyMarkdown: 'Skill body',
+ idempotencyKey: 'op-create-dedupe-1',
+ name: 'skill-name',
+ userId: 'user-1',
+ });
+
+ expect(createSkill).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ receiptId: 'receipt-deduped-create',
+ resourceId: 'skill-created-1',
+ status: 'deduped',
+ summary: 'Already created.',
+ });
+ });
+
/**
* @example
* await tools.closeMaintenanceProposal({ proposalId: 'proposal-1' });
@@ -370,6 +587,99 @@ describe('createMaintenanceTools', () => {
expect(spanEnd).toHaveBeenCalled();
});
+ /**
+ * @example
+ * await tools.listManagedSkills({ agentId: 'agent-1', userId: 'user-1' });
+ * returns adapter data and safe unsupported fallbacks for read tools.
+ */
+ it('read tools call injected adapters and return undefined or empty arrays when unsupported', async () => {
+ const { createMaintenanceTools } = await import('../tools');
+ const listManagedSkills = vi.fn().mockResolvedValue([{ name: 'skill-a' }]);
+ const getManagedSkill = vi.fn().mockResolvedValue({ name: 'skill-a' });
+ const listMaintenanceProposals = vi.fn().mockResolvedValue([{ proposalId: 'proposal-1' }]);
+ const getEvidenceDigest = vi.fn().mockResolvedValue({ evidenceCount: 1 });
+ const tools = createMaintenanceTools({
+ getEvidenceDigest,
+ getManagedSkill,
+ listMaintenanceProposals,
+ listManagedSkills,
+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),
+ writeReceipt: vi.fn(),
+ });
+
+ await expect(
+ tools.listManagedSkills({ agentId: 'agent-1', userId: 'user-1' }),
+ ).resolves.toEqual([{ name: 'skill-a' }]);
+ await expect(
+ tools.getManagedSkill({
+ agentId: 'agent-1',
+ skillDocumentId: 'skill-1',
+ userId: 'user-1',
+ }),
+ ).resolves.toEqual({ name: 'skill-a' });
+ await expect(
+ tools.listMaintenanceProposals({ agentId: 'agent-1', userId: 'user-1' }),
+ ).resolves.toEqual([{ proposalId: 'proposal-1' }]);
+ await expect(
+ tools.getEvidenceDigest({
+ agentId: 'agent-1',
+ evidenceIds: ['topic-1'],
+ reviewWindowEnd: '2026-05-04T14:00:00.000Z',
+ reviewWindowStart: '2026-05-03T14:00:00.000Z',
+ userId: 'user-1',
+ }),
+ ).resolves.toEqual({ evidenceCount: 1 });
+
+ expect(listManagedSkills).toHaveBeenCalledWith({ agentId: 'agent-1', userId: 'user-1' });
+ expect(getManagedSkill).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ skillDocumentId: 'skill-1',
+ userId: 'user-1',
+ });
+ expect(listMaintenanceProposals).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ userId: 'user-1',
+ });
+ expect(getEvidenceDigest).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ evidenceIds: ['topic-1'],
+ reviewWindowEnd: '2026-05-04T14:00:00.000Z',
+ reviewWindowStart: '2026-05-03T14:00:00.000Z',
+ userId: 'user-1',
+ });
+ expect(startActiveSpan).toHaveBeenCalledWith(
+ 'agent_signal.maintenance_tool.read',
+ expect.objectContaining({
+ attributes: expect.objectContaining({
+ 'agent.signal.maintenance_tool.name': 'listManagedSkills',
+ }),
+ }),
+ expect.any(Function),
+ );
+
+ const unsupportedTools = createMaintenanceTools({
+ reserveOperation: vi.fn().mockResolvedValue({ reserved: true }),
+ writeReceipt: vi.fn(),
+ });
+
+ await expect(
+ unsupportedTools.listManagedSkills({ agentId: 'agent-1', userId: 'user-1' }),
+ ).resolves.toEqual([]);
+ await expect(
+ unsupportedTools.getManagedSkill({
+ agentId: 'agent-1',
+ skillDocumentId: 'skill-1',
+ userId: 'user-1',
+ }),
+ ).resolves.toBeUndefined();
+ await expect(
+ unsupportedTools.listMaintenanceProposals({ agentId: 'agent-1', userId: 'user-1' }),
+ ).resolves.toEqual([]);
+ await expect(
+ unsupportedTools.getEvidenceDigest({ agentId: 'agent-1', userId: 'user-1' }),
+ ).resolves.toBeUndefined();
+ });
+
/**
* @example
* await tools.refreshMaintenanceProposal({ proposalId: 'proposal-1' });
diff --git a/src/server/services/agentSignal/services/maintenance/agent.ts b/src/server/services/agentSignal/services/maintenance/agent.ts
new file mode 100644
index 00000000000..629d580f914
--- /dev/null
+++ b/src/server/services/agentSignal/services/maintenance/agent.ts
@@ -0,0 +1,1060 @@
+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
+import { AgentRuntime, GeneralChatAgent } from '@lobechat/agent-runtime';
+import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
+import type { LobeToolManifest } from '@lobechat/context-engine';
+import { generateToolsFromManifest, ToolNameResolver } from '@lobechat/context-engine';
+import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
+import { consumeStreamUntilDone } from '@lobechat/model-runtime';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
+import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
+
+import type { NightlyReviewContext } from './nightlyCollector';
+import type { MaintenanceProposalBaseSnapshot } from './proposal';
+import type {
+ CloseMaintenanceProposalInput,
+ CreateMaintenanceProposalInput,
+ CreateSkillIfAbsentInput,
+ MaintenanceTools,
+ MaintenanceToolWriteInput,
+ MaintenanceToolWriteResult,
+ RefreshMaintenanceProposalInput,
+ ReplaceSkillContentCASInput,
+ SupersedeMaintenanceProposalInput,
+ WriteMemoryInput,
+} from './tools';
+import type { EvidenceRef } from './types';
+
+/** Built-in tool identifier used for maintenance AgentRuntime tool calls. */
+export const maintenanceToolFirstRuntimeToolIdentifier = 'agent-signal-maintenance';
+
+/** Read-only maintenance tools exposed to the tool-first runtime. */
+export type MaintenanceReadToolName =
+ | 'getEvidenceDigest'
+ | 'getManagedSkill'
+ | 'listMaintenanceProposals'
+ | 'listManagedSkills'
+ | 'readMaintenanceProposal';
+
+/** Write maintenance tools whose terminal outcomes must be retained by the runtime. */
+export type MaintenanceWriteToolName =
+ | 'closeMaintenanceProposal'
+ | 'createMaintenanceProposal'
+ | 'createSkillIfAbsent'
+ | 'refreshMaintenanceProposal'
+ | 'replaceSkillContentCAS'
+ | 'supersedeMaintenanceProposal'
+ | 'writeMemory';
+
+/** Maintenance tool names exposed to the model. */
+export type MaintenanceRuntimeToolName = MaintenanceReadToolName | MaintenanceWriteToolName;
+
+/**
+ * Input passed to the tool-first maintenance AgentRuntime loop.
+ */
+export interface MaintenanceToolFirstRuntimeInput {
+ /** Stable agent id being reviewed. */
+ agentId: string;
+ /** Bounded nightly review context collected before the run. */
+ context: NightlyReviewContext;
+ /** Maximum AgentRuntime steps allowed for the LLM/tool loop. */
+ maxSteps: number;
+ /** Model name passed to the injected model runtime. */
+ model: string;
+ /** Minimal model runtime dependency used to stream chat completions. */
+ modelRuntime: Pick<ModelRuntime, 'chat'>;
+ /** Stable source id used for tracing and fallback idempotency keys. */
+ sourceId: string;
+ /** Safe read/write maintenance tools available to this run. */
+ tools: MaintenanceTools;
+ /** Stable user id owning the reviewed agent. */
+ userId: string;
+}
+
+/**
+ * Write result captured from one supported maintenance write tool call.
+ */
+export interface MaintenanceToolFirstRuntimeWriteOutcome {
+ /** Tool result returned by the safe maintenance write boundary. */
+ result: MaintenanceToolWriteResult;
+ /** Supported write tool that produced this outcome. */
+ toolName: MaintenanceWriteToolName;
+}
+
+/**
+ * Result returned after the maintenance AgentRuntime loop stops.
+ */
+export interface MaintenanceToolFirstRuntimeResult {
+ /** Concatenated assistant text streamed across LLM calls. */
+ content: string;
+ /** AgentRuntime steps consumed before stopping. */
+ stepCount: number;
+ /** Model tool calls resolved against the maintenance manifest. */
+ toolCalls: ChatToolPayload[];
+ /** Per-call model usage emitted by streaming callbacks. */
+ usage: ModelUsage[];
+ /** Terminal write outcomes produced by supported maintenance write tools. */
+ writeOutcomes: MaintenanceToolFirstRuntimeWriteOutcome[];
+}
+
+interface MaintenanceToolExecutionResult {
+ data: unknown;
+ isWrite: boolean;
+ success: boolean;
+ toolName?: MaintenanceWriteToolName;
+}
+
+const createObjectSchema = (
+ properties: Record<string, unknown>,
+ required: string[] = [],
+): Record<string, unknown> => ({
+ additionalProperties: false,
+ properties,
+ required,
+ type: 'object',
+});
+
+const stringSchema = { type: 'string' };
+const stringArraySchema = { items: stringSchema, type: 'array' };
+const freeformArraySchema = { items: {}, type: 'array' };
+const freeformObjectSchema = { additionalProperties: true, type: 'object' };
+const proposalActionSchema = createObjectSchema(
+ {
+ actionType: {
+ enum: ['create_skill', 'refine_skill', 'consolidate_skill', 'proposal_only'],
+ type: 'string',
+ },
+ applyMode: { enum: ['auto_apply', 'proposal_only', 'skip'], type: 'string' },
+ baseSnapshot: freeformObjectSchema,
+ confidence: { type: 'number' },
+ dedupeKey: stringSchema,
+ evidenceRefs: freeformArraySchema,
+ idempotencyKey: stringSchema,
+ operation: freeformObjectSchema,
+ rationale: stringSchema,
+ risk: { enum: ['low', 'medium', 'high'], type: 'string' },
+ target: freeformObjectSchema,
+ },
+ ['actionType', 'rationale', 'target'],
+);
+const proposalActionsSchema = { items: proposalActionSchema, type: 'array' };
+
+/**
+ * Tool manifest used to expose current safe maintenance read/write tools to the model.
+ */
+export const maintenanceToolFirstRuntimeManifest = {
+ api: [
+ {
+ description: 'List managed skills visible in the reviewed agent scope.',
+ name: 'listManagedSkills',
+ parameters: createObjectSchema({}),
+ },
+ {
+ description: 'Read one managed skill by skill document id in the reviewed agent scope.',
+ name: 'getManagedSkill',
+ parameters: createObjectSchema({ skillDocumentId: stringSchema }, ['skillDocumentId']),
+ },
+ {
+ description:
+ 'Read bounded evidence details for cited topic, message, tool_call, or agent_document ids in the nightly review window. Use this for evidenceRefs; do not pass evidence ids to proposal tools.',
+ name: 'getEvidenceDigest',
+ parameters: createObjectSchema({
+ evidenceIds: stringArraySchema,
+ reviewWindowEnd: stringSchema,
+ reviewWindowStart: stringSchema,
+ }),
+ },
+ {
+ description: 'List active and historical maintenance proposals in the reviewed agent scope.',
+ name: 'listMaintenanceProposals',
+ parameters: createObjectSchema({}),
+ },
+ {
+ description:
+ 'Read one maintenance proposal by proposal id or proposalKey from proposalActivity.active or listMaintenanceProposals. Never use topic, message, tool_call, or document evidence ids here.',
+ name: 'readMaintenanceProposal',
+ parameters: createObjectSchema({
+ proposalId: stringSchema,
+ proposalKey: stringSchema,
+ }),
+ },
+ {
+ description: 'Create one user-visible maintenance proposal for later approval.',
+ name: 'createMaintenanceProposal',
+ parameters: createObjectSchema(
+ {
+ actions: proposalActionsSchema,
+ idempotencyKey: stringSchema,
+ metadata: freeformObjectSchema,
+ proposalKey: stringSchema,
+ summary: stringSchema,
+ },
+ ['idempotencyKey', 'proposalKey', 'summary', 'actions'],
+ ),
+ },
+ {
+ description: 'Refresh an existing maintenance proposal after rechecking evidence.',
+ name: 'refreshMaintenanceProposal',
+ parameters: createObjectSchema(
+ {
+ idempotencyKey: stringSchema,
+ proposalId: stringSchema,
+ proposalKey: stringSchema,
+ summary: stringSchema,
+ },
+ ['idempotencyKey', 'proposalId'],
+ ),
+ },
+ {
+ description: 'Supersede an existing maintenance proposal with a replacement proposal key.',
+ name: 'supersedeMaintenanceProposal',
+ parameters: createObjectSchema(
+ {
+ idempotencyKey: stringSchema,
+ proposalId: stringSchema,
+ proposalKey: stringSchema,
+ summary: stringSchema,
+ supersededBy: stringSchema,
+ },
+ ['idempotencyKey', 'proposalId', 'supersededBy'],
+ ),
+ },
+ {
+ description: 'Close an existing maintenance proposal with an optional lifecycle reason.',
+ name: 'closeMaintenanceProposal',
+ parameters: createObjectSchema(
+ {
+ idempotencyKey: stringSchema,
+ proposalId: stringSchema,
+ proposalKey: stringSchema,
+ reason: stringSchema,
+ summary: stringSchema,
+ },
+ ['idempotencyKey', 'proposalId'],
+ ),
+ },
+ {
+ description:
+ 'Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.',
+ name: 'writeMemory',
+ parameters: createObjectSchema(
+ {
+ content: stringSchema,
+ evidenceRefs: freeformArraySchema,
+ idempotencyKey: stringSchema,
+ proposalKey: stringSchema,
+ summary: stringSchema,
+ },
+ ['idempotencyKey', 'content', 'evidenceRefs'],
+ ),
+ },
+ {
+ description: 'Create one managed skill when no existing skill is selected.',
+ name: 'createSkillIfAbsent',
+ parameters: createObjectSchema(
+ {
+ bodyMarkdown: stringSchema,
+ description: stringSchema,
+ idempotencyKey: stringSchema,
+ name: stringSchema,
+ proposalKey: stringSchema,
+ summary: stringSchema,
+ title: stringSchema,
+ },
+ ['idempotencyKey', 'name', 'bodyMarkdown'],
+ ),
+ },
+ {
+ description:
+ 'Replace one existing managed skill after compare-and-swap preflight. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.',
+ name: 'replaceSkillContentCAS',
+ parameters: createObjectSchema(
+ {
+ baseSnapshot: freeformObjectSchema,
+ bodyMarkdown: stringSchema,
+ description: stringSchema,
+ idempotencyKey: stringSchema,
+ proposalKey: stringSchema,
+ skillDocumentId: stringSchema,
+ summary: stringSchema,
+ },
+ ['idempotencyKey', 'skillDocumentId', 'bodyMarkdown'],
+ ),
+ },
+ ],
+ identifier: maintenanceToolFirstRuntimeToolIdentifier,
+ meta: {
+ description: 'Read nightly evidence and apply safe maintenance operations.',
+ title: 'Agent Signal Maintenance',
+ },
+ systemRole:
+ 'Use maintenance read tools before writes when evidence is incomplete. Use getEvidenceDigest for topic/message/tool_call/agent_document evidenceRefs. Use readMaintenanceProposal only with proposal keys from proposalActivity.active or listMaintenanceProposals, never with evidence ids. Treat write tool results as the source of truth.',
+ type: 'builtin',
+} satisfies LobeToolManifest;
+
+const MAINTENANCE_TOOL_FIRST_SYSTEM_ROLE = [
+ 'You are the Agent Signal maintenance agent.',
+ 'Inspect the bounded nightly review context and use the provided maintenance tools to read evidence or apply safe write operations.',
+ 'Evidence ids and proposal keys are different namespaces: read topic/message/tool_call/agent_document evidence with getEvidenceDigest; read proposals with readMaintenanceProposal only when using proposalActivity.active[].proposalKey or keys returned from listMaintenanceProposals.',
+ 'Never claim that a write happened unless a write tool result confirms it.',
+ 'Use writeMemory for explicit durable user preferences such as response style, summary structure, or verification-reporting preferences. Do not turn those preference memories into skills or proposals.',
+ 'Use createSkillIfAbsent only when evidence describes a reusable workflow and you can provide a non-empty skill name and full bodyMarkdown.',
+ 'When the evidence supports an approval-gated change, call createMaintenanceProposal in this run; do not offer to draft it later.',
+ 'For createMaintenanceProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, or proposal_only. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }.',
+ 'Stop after the useful maintenance work is complete and summarize the confirmed outcome.',
+].join('\n');
+
+const TOOL_NAME_SEPARATOR = '____';
+const MAINTENANCE_TOOL_ERROR_MESSAGE = 'Maintenance tool call failed.';
+const FORCE_FINISH_EXTRA_STEPS = 4;
+
+const createMaintenanceRuntimePrompt = (input: MaintenanceToolFirstRuntimeInput) =>
+ [
+ `Agent id: ${input.agentId}`,
+ `User id: ${input.userId}`,
+ `Source id: ${input.sourceId}`,
+ `Review window: ${input.context.reviewWindowStart} to ${input.context.reviewWindowEnd}`,
+ 'Nightly review context JSON:',
+ JSON.stringify(input.context),
+ ].join('\n');
+
+const toNullableString = (value: unknown) =>
+ typeof value === 'string' && value.trim().length > 0 ? value : undefined;
+
+const toBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);
+
+const toRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+
+const toUnknownArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
+
+const toStringArray = (value: unknown) =>
+ Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
+
+const toEvidenceRefs = (value: unknown): EvidenceRef[] =>
+ Array.isArray(value)
+ ? value.flatMap((item) => {
+ const record = toRecord(item);
+ const id = toNullableString(record.id);
+ const type = toNullableString(record.type);
+
+ if (
+ !id ||
+ !(
+ type === 'topic' ||
+ type === 'message' ||
+ type === 'operation' ||
+ type === 'source' ||
+ type === 'receipt' ||
+ type === 'tool_call' ||
+ type === 'task' ||
+ type === 'agent_document' ||
+ type === 'memory'
+ )
+ ) {
+ return [];
+ }
+
+ return [
+ {
+ id,
+ ...(toNullableString(record.summary)
+ ? { summary: toNullableString(record.summary) }
+ : {}),
+ type,
+ },
+ ];
+ })
+ : [];
+
+/**
+ * Normalizes model-produced tool arguments.
+ *
+ * Before:
+ * - `"{\"name\":\"skill\"}"`
+ * - `"not json"`
+ *
+ * After:
+ * - `{ name: "skill" }`
+ * - `{}`
+ */
+const parseToolArguments = (value: string | undefined): Record<string, unknown> => {
+ if (!value) return {};
+
+ try {
+ const parsed = JSON.parse(value) as unknown;
+
+ return toRecord(parsed);
+ } catch {
+ return {};
+ }
+};
+
+const getErrorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : String(error);
+
+const getApiNameFromRawToolName = (name: string) => {
+ const [identifier, apiName] = name.split(TOOL_NAME_SEPARATOR);
+
+ return identifier === maintenanceToolFirstRuntimeToolIdentifier && apiName ? apiName : name;
+};
+
+const resolveMaintenanceToolCalls = ({
+ manifestMap,
+ offeredToolNames,
+ rawToolCalls,
+ toolNameResolver,
+}: {
+ manifestMap: Record<string, LobeToolManifest>;
+ offeredToolNames: string[];
+ rawToolCalls: MessageToolCall[];
+ toolNameResolver: ToolNameResolver;
+}): ChatToolPayload[] => {
+ const resolvedToolCalls = toolNameResolver.resolve(rawToolCalls, manifestMap, offeredToolNames);
+ const resolvedIds = new Set(resolvedToolCalls.map((toolCall) => toolCall.id));
+ const unresolvedToolCalls = rawToolCalls
+ .filter((toolCall) => !resolvedIds.has(toolCall.id))
+ .map(
+ (toolCall): ChatToolPayload => ({
+ apiName: getApiNameFromRawToolName(toolCall.function.name),
+ arguments: toolCall.function.arguments,
+ id: toolCall.id,
+ identifier: maintenanceToolFirstRuntimeToolIdentifier,
+ thoughtSignature: toolCall.thoughtSignature,
+ type: 'builtin',
+ }),
+ );
+
+ return [...resolvedToolCalls, ...unresolvedToolCalls];
+};
+
+const createToolError = (message: string): MaintenanceToolExecutionResult => ({
+ data: { error: message },
+ isWrite: false,
+ success: false,
+});
+
+const withUser = <TInput extends MaintenanceToolWriteInput>(
+ toolName: MaintenanceWriteToolName,
+ args: Record<string, unknown>,
+ input: MaintenanceToolFirstRuntimeInput,
+ toolCallId: string,
+ fields: Omit<TInput, keyof MaintenanceToolWriteInput>,
+): TInput =>
+ ({
+ ...fields,
+ idempotencyKey:
+ toNullableString(args.idempotencyKey) ?? `${input.sourceId}:${toolName}:${toolCallId}`,
+ proposalKey: toNullableString(args.proposalKey),
+ summary: toNullableString(args.summary),
+ userId: input.userId,
+ }) as TInput;
+
+const toBaseSnapshot = (value: unknown): MaintenanceProposalBaseSnapshot => {
+ const record = toRecord(value);
+
+ return {
+ absent: toBoolean(record.absent),
+ agentDocumentId: toNullableString(record.agentDocumentId),
+ contentHash: toNullableString(record.contentHash),
+ documentId: toNullableString(record.documentId),
+ documentUpdatedAt: toNullableString(record.documentUpdatedAt),
+ managed: toBoolean(record.managed),
+ skillName: toNullableString(record.skillName),
+ targetTitle: toNullableString(record.targetTitle),
+ targetType: record.targetType === 'skill' ? 'skill' : undefined,
+ writable: toBoolean(record.writable),
+ };
+};
+
+const executeWriteTool = async (
+ toolName: MaintenanceWriteToolName,
+ operation: () => Promise<MaintenanceToolWriteResult>,
+): Promise<MaintenanceToolExecutionResult> => ({
+ data: await operation(),
+ isWrite: true,
+ success: true,
+ toolName,
+});
+
+const executeMaintenanceRuntimeTool = async (
+ toolCall: ChatToolPayload,
+ input: MaintenanceToolFirstRuntimeInput,
+): Promise<MaintenanceToolExecutionResult> => {
+ const args = parseToolArguments(toolCall.arguments);
+
+ if (toolCall.apiName === 'listManagedSkills') {
+ return {
+ data: await input.tools.listManagedSkills({ agentId: input.agentId, userId: input.userId }),
+ isWrite: false,
+ success: true,
+ };
+ }
+
+ if (toolCall.apiName === 'getManagedSkill') {
+ const skillDocumentId = toNullableString(args.skillDocumentId);
+ if (!skillDocumentId) return createToolError('skillDocumentId is required');
+
+ return {
+ data: await input.tools.getManagedSkill({
+ agentId: input.agentId,
+ skillDocumentId,
+ userId: input.userId,
+ }),
+ isWrite: false,
+ success: true,
+ };
+ }
+
+ if (toolCall.apiName === 'getEvidenceDigest') {
+ return {
+ data: await input.tools.getEvidenceDigest({
+ agentId: input.agentId,
+ evidenceIds: toStringArray(args.evidenceIds),
+ reviewWindowEnd: toNullableString(args.reviewWindowEnd) ?? input.context.reviewWindowEnd,
+ reviewWindowStart:
+ toNullableString(args.reviewWindowStart) ?? input.context.reviewWindowStart,
+ userId: input.userId,
+ }),
+ isWrite: false,
+ success: true,
+ };
+ }
+
+ if (toolCall.apiName === 'listMaintenanceProposals') {
+ return {
+ data: await input.tools.listMaintenanceProposals({
+ agentId: input.agentId,
+ userId: input.userId,
+ }),
+ isWrite: false,
+ success: true,
+ };
+ }
+
+ if (toolCall.apiName === 'readMaintenanceProposal') {
+ return {
+ data: await input.tools.readMaintenanceProposal({
+ proposalId: toNullableString(args.proposalId),
+ proposalKey: toNullableString(args.proposalKey),
+ userId: input.userId,
+ }),
+ isWrite: false,
+ success: true,
+ };
+ }
+
+ if (toolCall.apiName === 'createMaintenanceProposal') {
+ return executeWriteTool('createMaintenanceProposal', () =>
+ input.tools.createMaintenanceProposal(
+ withUser<CreateMaintenanceProposalInput>(
+ 'createMaintenanceProposal',
+ args,
+ input,
+ toolCall.id,
+ {
+ actions: toUnknownArray(args.actions),
+ metadata: toRecord(args.metadata),
+ },
+ ),
+ ),
+ );
+ }
+
+ if (toolCall.apiName === 'refreshMaintenanceProposal') {
+ const proposalId = toNullableString(args.proposalId);
+ if (!proposalId) return createToolError('proposalId is required');
+
+ return executeWriteTool('refreshMaintenanceProposal', () =>
+ input.tools.refreshMaintenanceProposal(
+ withUser<RefreshMaintenanceProposalInput>(
+ 'refreshMaintenanceProposal',
+ args,
+ input,
+ toolCall.id,
+ {
+ proposalId,
+ },
+ ),
+ ),
+ );
+ }
+
+ if (toolCall.apiName === 'supersedeMaintenanceProposal') {
+ const proposalId = toNullableString(args.proposalId);
+ const supersededBy = toNullableString(args.supersededBy);
+ if (!proposalId) return createToolError('proposalId is required');
+ if (!supersededBy) return createToolError('supersededBy is required');
+
+ return executeWriteTool('supersedeMaintenanceProposal', () =>
+ input.tools.supersedeMaintenanceProposal(
+ withUser<SupersedeMaintenanceProposalInput>(
+ 'supersedeMaintenanceProposal',
+ args,
+ input,
+ toolCall.id,
+ {
+ proposalId,
+ supersededBy,
+ },
+ ),
+ ),
+ );
+ }
+
+ if (toolCall.apiName === 'closeMaintenanceProposal') {
+ const proposalId = toNullableString(args.proposalId);
+ if (!proposalId) return createToolError('proposalId is required');
+
+ return executeWriteTool('closeMaintenanceProposal', () =>
+ input.tools.closeMaintenanceProposal(
+ withUser<CloseMaintenanceProposalInput>(
+ 'closeMaintenanceProposal',
+ args,
+ input,
+ toolCall.id,
+ {
+ proposalId,
+ reason: toNullableString(args.reason),
+ },
+ ),
+ ),
+ );
+ }
+
+ if (toolCall.apiName === 'writeMemory') {
+ const content = toNullableString(args.content);
+ if (!content) return createToolError('content is required');
+
+ const evidenceRefs = toEvidenceRefs(args.evidenceRefs);
+ if (evidenceRefs.length === 0) return createToolError('evidenceRefs are required');
+
+ return executeWriteTool('writeMemory', () =>
+ input.tools.writeMemory(
+ withUser<WriteMemoryInput>('writeMemory', args, input, toolCall.id, {
+ content,
+ evidenceRefs,
+ }),
+ ),
+ );
+ }
+
+ if (toolCall.apiName === 'createSkillIfAbsent') {
+ return executeWriteTool('createSkillIfAbsent', () =>
+ input.tools.createSkillIfAbsent(
+ withUser<CreateSkillIfAbsentInput>('createSkillIfAbsent', args, input, toolCall.id, {
+ bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',
+ description: toNullableString(args.description),
+ name: toNullableString(args.name) ?? '',
+ title: toNullableString(args.title),
+ }),
+ ),
+ );
+ }
+
+ if (toolCall.apiName === 'replaceSkillContentCAS') {
+ const skillDocumentId = toNullableString(args.skillDocumentId);
+ if (!skillDocumentId) return createToolError('skillDocumentId is required');
+
+ return executeWriteTool('replaceSkillContentCAS', () =>
+ input.tools.replaceSkillContentCAS(
+ withUser<ReplaceSkillContentCASInput>('replaceSkillContentCAS', args, input, toolCall.id, {
+ baseSnapshot: toBaseSnapshot(args.baseSnapshot),
+ bodyMarkdown: toNullableString(args.bodyMarkdown) ?? '',
+ description: toNullableString(args.description),
+ skillDocumentId,
+ }),
+ ),
+ );
+ }
+
+ return createToolError(`Unsupported maintenance tool: ${toolCall.apiName}`);
+};
+
+const createInitialState = ({
+ input,
+ manifestMap,
+ runtimeTools,
+}: {
+ input: MaintenanceToolFirstRuntimeInput;
+ manifestMap: Record<string, LobeToolManifest>;
+ runtimeTools: ReturnType<typeof generateToolsFromManifest>;
+}): AgentState => {
+ const createdAt = new Date().toISOString();
+ const operationId = `agent-signal-maintenance:${input.sourceId}`;
+ const messages: ChatStreamPayload['messages'] = [
+ { content: MAINTENANCE_TOOL_FIRST_SYSTEM_ROLE, role: 'system' },
+ { content: createMaintenanceRuntimePrompt(input), role: 'user' },
+ ];
+
+ return {
+ cost: {
+ calculatedAt: createdAt,
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ createdAt,
+ lastModified: createdAt,
+ maxSteps: Math.max(1, input.maxSteps),
+ messages,
+ metadata: {
+ agentId: input.agentId,
+ sourceId: input.sourceId,
+ trigger: RequestTrigger.AgentSignal,
+ userId: input.userId,
+ },
+ modelRuntimeConfig: {
+ model: input.model,
+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
+ },
+ operationId,
+ operationToolSet: {
+ enabledToolIds: [maintenanceToolFirstRuntimeToolIdentifier],
+ manifestMap,
+ sourceMap: { [maintenanceToolFirstRuntimeToolIdentifier]: 'builtin' },
+ tools: runtimeTools,
+ },
+ status: 'idle',
+ stepCount: 0,
+ toolManifestMap: manifestMap,
+ toolSourceMap: { [maintenanceToolFirstRuntimeToolIdentifier]: 'builtin' },
+ tools: runtimeTools,
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: {
+ apiCalls: 0,
+ processingTimeMs: 0,
+ tokens: { input: 0, output: 0, total: 0 },
+ },
+ tools: {
+ byTool: [],
+ totalCalls: 0,
+ totalTimeMs: 0,
+ },
+ },
+ userInterventionConfig: { approvalMode: 'headless' },
+ };
+};
+
+/**
+ * Runs the tool-first maintenance agent with a bounded AgentRuntime LLM/tool loop.
+ *
+ * Triggering workflow:
+ *
+ * createMaintenanceAgentRunner
+ * -> future server runtime backend
+ * -> `agent_signal.maintenance_agent.run`
+ * -> {@link runMaintenanceToolFirstRuntime}
+ *
+ * Upstream:
+ * - {@link createInitialState}
+ *
+ * Downstream:
+ * - {@link executeMaintenanceRuntimeTool}
+ *
+ * Use when:
+ * - Nightly maintenance needs real LLM -> tool -> LLM behavior
+ * - The caller already has scoped safe maintenance tools and a model runtime
+ *
+ * Expects:
+ * - Tools enforce their own idempotency, preflight, and receipt contracts
+ * - `maxSteps` is a positive finite loop budget
+ *
+ * Returns:
+ * - Final streamed assistant content, step count, model usage, tool calls, and write outcomes
+ */
+export const runMaintenanceToolFirstRuntime = async (
+ input: MaintenanceToolFirstRuntimeInput,
+): Promise<MaintenanceToolFirstRuntimeResult> =>
+ tracer.startActiveSpan(
+ 'agent_signal.maintenance_agent.run',
+ {
+ attributes: {
+ 'agent.signal.agent_id': input.agentId,
+ 'agent.signal.maintenance_agent.max_steps': input.maxSteps,
+ 'agent.signal.source_id': input.sourceId,
+ 'agent.signal.user_id': input.userId,
+ },
+ },
+ async (runSpan) => {
+ const maxSteps = Math.max(1, input.maxSteps);
+ const toolNameResolver = new ToolNameResolver();
+ const manifestMap = {
+ [maintenanceToolFirstRuntimeToolIdentifier]: maintenanceToolFirstRuntimeManifest,
+ };
+ const runtimeTools = generateToolsFromManifest(maintenanceToolFirstRuntimeManifest);
+ const offeredToolNames = runtimeTools.map((tool) => tool.function.name);
+ const contentParts: string[] = [];
+ const toolCalls: ChatToolPayload[] = [];
+ const usage: ModelUsage[] = [];
+ const writeOutcomes: MaintenanceToolFirstRuntimeWriteOutcome[] = [];
+ const runtime = new AgentRuntime(
+ new GeneralChatAgent({
+ compressionConfig: { enabled: false },
+ modelRuntimeConfig: {
+ model: input.model,
+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
+ },
+ operationId: `agent-signal-maintenance:${input.sourceId}`,
+ userId: input.userId,
+ }),
+ {
+ executors: {
+ call_llm: async (instruction, state) => {
+ const payload = (
+ instruction as { payload: { messages: ChatStreamPayload['messages'] } }
+ ).payload;
+ let content = '';
+ let modelUsage: ModelUsage | undefined;
+ let rawToolCalls: MessageToolCall[] = [];
+
+ const response = await input.modelRuntime.chat(
+ {
+ messages: payload.messages,
+ model: input.model,
+ stream: true,
+ tools: state.forceFinish ? [] : runtimeTools,
+ },
+ {
+ callback: {
+ onCompletion: (data) => {
+ modelUsage = data.usage;
+ },
+ onText: (text) => {
+ content += text;
+ },
+ onToolsCalling: ({ toolsCalling }) => {
+ rawToolCalls = toolsCalling;
+ },
+ },
+ metadata: { trigger: RequestTrigger.AgentSignal },
+ },
+ );
+ await consumeStreamUntilDone(response);
+
+ if (content) contentParts.push(content);
+ if (modelUsage) usage.push(modelUsage);
+
+ const assistantMessageId = `maintenance-assistant-${state.stepCount}`;
+ const resolvedToolCalls = resolveMaintenanceToolCalls({
+ manifestMap,
+ offeredToolNames,
+ rawToolCalls,
+ toolNameResolver,
+ });
+ toolCalls.push(...resolvedToolCalls);
+
+ const newState = structuredClone(state);
+ newState.messages.push({
+ content,
+ id: assistantMessageId,
+ role: 'assistant',
+ ...(rawToolCalls.length > 0 ? { tool_calls: rawToolCalls } : {}),
+ });
+
+ return {
+ events: [
+ {
+ result: { content, tool_calls: rawToolCalls, usage: modelUsage },
+ type: 'llm_result',
+ },
+ ],
+ newState,
+ nextContext: {
+ payload: {
+ hasToolsCalling: resolvedToolCalls.length > 0,
+ parentMessageId: assistantMessageId,
+ result: { content, tool_calls: rawToolCalls },
+ toolsCalling: resolvedToolCalls,
+ },
+ phase: 'llm_result',
+ session: {
+ messageCount: newState.messages.length,
+ sessionId: newState.operationId,
+ status: newState.status,
+ stepCount: newState.stepCount,
+ },
+ stepUsage: modelUsage,
+ } satisfies AgentRuntimeContext,
+ };
+ },
+ call_tool: async (instruction, state) => {
+ const payload = (
+ instruction as {
+ payload: {
+ parentMessageId: string;
+ toolCalling: ChatToolPayload;
+ };
+ }
+ ).payload;
+ const startedAt = Date.now();
+ let execution: MaintenanceToolExecutionResult;
+
+ try {
+ execution = await executeMaintenanceRuntimeTool(payload.toolCalling, input);
+ } catch (error) {
+ execution = {
+ data: { error: MAINTENANCE_TOOL_ERROR_MESSAGE },
+ isWrite: false,
+ success: false,
+ };
+ }
+
+ if (execution.isWrite && execution.toolName && execution.success) {
+ writeOutcomes.push({
+ result: execution.data as MaintenanceToolWriteResult,
+ toolName: execution.toolName,
+ });
+ }
+
+ const content = JSON.stringify(execution.data);
+ const newState = structuredClone(state);
+ newState.messages.push({
+ content,
+ role: 'tool',
+ tool_call_id: payload.toolCalling.id,
+ });
+
+ return {
+ events: [
+ {
+ id: payload.toolCalling.id,
+ result: { content, success: execution.success },
+ type: 'tool_result',
+ },
+ ],
+ newState,
+ nextContext: {
+ payload: {
+ data: execution.data,
+ executionTime: Date.now() - startedAt,
+ isSuccess: execution.success,
+ parentMessageId: payload.parentMessageId,
+ toolCall: payload.toolCalling,
+ toolCallId: payload.toolCalling.id,
+ },
+ phase: 'tool_result',
+ session: {
+ messageCount: newState.messages.length,
+ sessionId: newState.operationId,
+ status: newState.status,
+ stepCount: newState.stepCount,
+ },
+ } satisfies AgentRuntimeContext,
+ };
+ },
+ },
+ },
+ );
+ let state = createInitialState({ input, manifestMap, runtimeTools });
+ let context: AgentRuntimeContext = {
+ payload: {
+ model: input.model,
+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
+ tools: runtimeTools,
+ },
+ phase: 'user_input',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: state.status,
+ stepCount: state.stepCount,
+ },
+ };
+
+ try {
+ // NOTICE:
+ // The public maxSteps policy lives in AgentRuntime via state.maxSteps.
+ // The outer loop is only a hard safety cap so force-finish and the final
+ // tool-result continuation can run after AgentRuntime crosses maxSteps.
+ // Source/context: packages/agent-runtime/src/core/runtime.ts forceFinish handling.
+ // Removal condition: AgentRuntime exposes a bounded run-until-done API.
+ const hardSafetyStepCap = maxSteps + FORCE_FINISH_EXTRA_STEPS;
+
+ for (let stepIndex = 0; stepIndex < hardSafetyStepCap; stepIndex += 1) {
+ if (
+ state.status === 'done' ||
+ state.status === 'error' ||
+ state.status === 'interrupted'
+ ) {
+ break;
+ }
+
+ const result = await tracer.startActiveSpan(
+ 'agent_signal.maintenance_agent.step',
+ {
+ attributes: {
+ 'agent.signal.agent_id': input.agentId,
+ 'agent.signal.maintenance_agent.max_steps': maxSteps,
+ 'agent.signal.maintenance_agent.step_count': state.stepCount + 1,
+ 'agent.signal.source_id': input.sourceId,
+ 'agent.signal.user_id': input.userId,
+ },
+ },
+ async (stepSpan) => {
+ try {
+ const stepResult = await runtime.step(state, context);
+ stepSpan.setAttribute(
+ 'agent.signal.maintenance_agent.step_count',
+ stepResult.newState.stepCount,
+ );
+
+ if (stepResult.newState.status === 'error') {
+ stepSpan.setStatus({ code: SpanStatusCode.ERROR });
+ } else {
+ stepSpan.setStatus({ code: SpanStatusCode.OK });
+ }
+
+ return stepResult;
+ } catch (error) {
+ stepSpan.recordException(error as Error);
+ stepSpan.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: getErrorMessage(error),
+ });
+
+ throw error;
+ } finally {
+ stepSpan.end();
+ }
+ },
+ );
+
+ state = result.newState;
+
+ if (!result.nextContext) break;
+ context = result.nextContext;
+ }
+
+ runSpan.setAttribute('agent.signal.maintenance_agent.step_count', state.stepCount);
+ runSpan.setStatus({
+ code: state.status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,
+ });
+
+ return {
+ content: contentParts.join(''),
+ stepCount: state.stepCount,
+ toolCalls,
+ usage,
+ writeOutcomes,
+ };
+ } catch (error) {
+ runSpan.recordException(error as Error);
+ runSpan.setStatus({ code: SpanStatusCode.ERROR, message: getErrorMessage(error) });
+
+ throw error;
+ } finally {
+ runSpan.end();
+ }
+ },
+ );
diff --git a/src/server/services/agentSignal/services/maintenance/brief.ts b/src/server/services/agentSignal/services/maintenance/brief.ts
index 909a7f0a6f1..372f9f43c09 100644
--- a/src/server/services/agentSignal/services/maintenance/brief.ts
+++ b/src/server/services/agentSignal/services/maintenance/brief.ts
@@ -1,11 +1,12 @@
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
+import type { BriefMetadata } from '@lobechat/types';
import { BriefModel } from '@/database/models/brief';
import type { BriefItem, NewBrief } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
-import type { MaintenanceProposalMetadata } from './proposal';
+import type { MaintenanceProposalMetadata, MaintenanceProposalPlan } from './proposal';
import {
AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS,
buildMaintenanceProposalFromPlan,
@@ -15,7 +16,7 @@ import {
shouldSupersedeMaintenanceProposal,
supersedeMaintenanceProposal,
} from './proposal';
-import type { EvidenceRef, MaintenancePlan, MaintenanceReviewRunResult } from './types';
+import type { EvidenceRef, MaintenanceReviewRunResult } from './types';
import { MaintenanceActionStatus, ReviewRunStatus } from './types';
export const NIGHTLY_REVIEW_BRIEF_TRIGGER = 'agent-signal:nightly-review';
@@ -39,10 +40,10 @@ export interface MaintenanceBriefMetadata {
evidenceRefs: EvidenceRef[];
/** User-local review date in YYYY-MM-DD form. */
localDate: string;
+ /** Frozen maintenance proposal state for approve/dismiss flows. */
+ maintenanceProposal?: MaintenanceProposalMetadata;
/** 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. */
@@ -55,9 +56,20 @@ export interface MaintenanceBriefMetadata {
windowStart: string;
}
+/** Namespaced metadata payload stored by Agent Signal nightly self-review briefs. */
+export interface AgentSignalNightlySelfReviewBriefMetadata extends BriefMetadata {
+ /** Agent Signal-owned metadata namespace. */
+ agentSignal: {
+ /** Nightly self-review status, receipts, and optional frozen proposal. */
+ nightlySelfReview: MaintenanceBriefMetadata;
+ /** Future Agent Signal domains can live beside nightly self-review. */
+ [key: string]: unknown;
+ };
+}
+
/** Create payload for a maintenance Daily Brief. */
export type MaintenanceBriefProjection = Omit<NewBrief, 'id' | 'userId'> & {
- metadata: MaintenanceBriefMetadata;
+ metadata: AgentSignalNightlySelfReviewBriefMetadata;
trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;
};
@@ -68,12 +80,161 @@ const updateBriefProposalMetadata = (
brief: BriefItem,
proposal: MaintenanceProposalMetadata,
): BriefItem['metadata'] => ({
- ...(brief.metadata && typeof brief.metadata === 'object' && !Array.isArray(brief.metadata)
- ? (brief.metadata as Record<string, unknown>)
- : {}),
+ ...asMetadataRecord(brief.metadata),
+ agentSignal: {
+ ...asMetadataRecord(asMetadataRecord(brief.metadata).agentSignal),
+ nightlySelfReview: {
+ ...asMetadataRecord(
+ asMetadataRecord(asMetadataRecord(brief.metadata).agentSignal).nightlySelfReview,
+ ),
+ maintenanceProposal: proposal,
+ },
+ },
+});
+
+const asMetadataRecord = (metadata: unknown): Record<string, unknown> =>
+ metadata && typeof metadata === 'object' && !Array.isArray(metadata)
+ ? (metadata as Record<string, unknown>)
+ : {};
+
+/** Reads Agent Signal nightly self-review metadata from a namespaced Brief payload. */
+export const getNightlySelfReviewBriefMetadata = (
+ metadata: unknown,
+): MaintenanceBriefMetadata | undefined => {
+ const agentSignal = asMetadataRecord(asMetadataRecord(metadata).agentSignal);
+ const nightlySelfReview = agentSignal.nightlySelfReview;
+
+ return nightlySelfReview &&
+ typeof nightlySelfReview === 'object' &&
+ !Array.isArray(nightlySelfReview)
+ ? (nightlySelfReview as MaintenanceBriefMetadata)
+ : undefined;
+};
+
+const createNightlySelfReviewBriefMetadata = ({
+ actionCounts,
+ evidenceRefs,
+ input,
+ outcome,
proposal,
+}: {
+ actionCounts: MaintenanceBriefActionCounts;
+ evidenceRefs: EvidenceRef[];
+ input: ProjectNightlyReviewBriefInput;
+ outcome: MaintenanceBriefMetadata['outcome'];
+ proposal?: MaintenanceProposalMetadata;
+}): AgentSignalNightlySelfReviewBriefMetadata => ({
+ agentSignal: {
+ nightlySelfReview: {
+ actionCounts,
+ evidenceRefs,
+ localDate: input.localDate,
+ outcome,
+ ...(proposal ? { maintenanceProposal: proposal } : {}),
+ receiptIds: getReceiptIds(input.result),
+ ...(input.result.sourceId ? { sourceId: input.result.sourceId } : {}),
+ timezone: input.timezone,
+ windowEnd: input.reviewWindowEnd,
+ windowStart: input.reviewWindowStart,
+ },
+ },
});
+const ACTIVE_PROPOSAL_REFRESH_STATUSES = new Set<MaintenanceProposalMetadata['status']>([
+ 'expired',
+ 'pending',
+ 'stale',
+]);
+
+const findExistingProposalBrief = async ({
+ agentId,
+ incomingProposal,
+ model,
+ trigger,
+}: {
+ agentId: string;
+ incomingProposal: MaintenanceProposalMetadata;
+ model: BriefModel;
+ trigger: typeof NIGHTLY_REVIEW_BRIEF_TRIGGER;
+}) => {
+ const rows = await model.listUnresolvedByAgentAndTrigger({
+ agentId,
+ limit: 20,
+ trigger,
+ });
+
+ return rows.find((row) => {
+ const proposal = getMaintenanceProposalFromBriefMetadata(row.metadata);
+
+ return (
+ proposal?.proposalKey === incomingProposal.proposalKey &&
+ ACTIVE_PROPOSAL_REFRESH_STATUSES.has(proposal.status)
+ );
+ });
+};
+
+const updateProposalMetadata = async (
+ model: BriefModel,
+ brief: BriefItem,
+ proposal: MaintenanceProposalMetadata,
+) => model.updateMetadata(brief.id, updateBriefProposalMetadata(brief, proposal));
+
+const refreshProposalBrief = ({
+ fallbackBrief,
+ model,
+ proposal,
+ targetBrief,
+}: {
+ fallbackBrief: MaintenanceBriefProjection;
+ model: BriefModel;
+ proposal: MaintenanceProposalMetadata;
+ targetBrief: BriefItem;
+}) =>
+ tracer.startActiveSpan(
+ 'agent_signal.maintenance_proposal.refresh',
+ {
+ attributes: {
+ 'agent.signal.proposal.key': proposal.proposalKey,
+ 'agent.signal.proposal.status': proposal.status,
+ },
+ },
+ async (span) => {
+ try {
+ const updatedBrief = await updateProposalMetadata(model, targetBrief, proposal);
+
+ return updatedBrief ?? model.create(fallbackBrief);
+ } finally {
+ span.end();
+ }
+ },
+ );
+
+const supersedeProposalBrief = ({
+ model,
+ proposal,
+ targetBrief,
+}: {
+ model: BriefModel;
+ proposal: MaintenanceProposalMetadata;
+ targetBrief: BriefItem;
+}) =>
+ tracer.startActiveSpan(
+ 'agent_signal.maintenance_proposal.supersede',
+ {
+ attributes: {
+ 'agent.signal.proposal.key': proposal.proposalKey,
+ 'agent.signal.proposal.status': proposal.status,
+ },
+ },
+ async (span) => {
+ try {
+ await updateProposalMetadata(model, targetBrief, proposal);
+ } finally {
+ span.end();
+ }
+ },
+ );
+
/** Input used to project one nightly maintenance result to a Daily Brief payload. */
export interface ProjectNightlyReviewBriefInput {
/** Agent reviewed by the nightly maintenance run. */
@@ -83,7 +244,7 @@ export interface ProjectNightlyReviewBriefInput {
/** User-local date reviewed by the nightly run. */
localDate: string;
/** Frozen maintenance plan used to preserve proposal actions. */
- plan?: MaintenancePlan;
+ plan?: MaintenanceProposalPlan;
/** Executor result for the nightly maintenance run. */
result: MaintenanceReviewRunResult;
/** Review window end ISO timestamp. */
@@ -124,14 +285,14 @@ export interface MaintenanceProposalVisibilityInput {
trigger?: string | null;
}
-const getPlanActionByIdempotencyKey = (plan?: MaintenancePlan) =>
+const getPlanActionByIdempotencyKey = (plan?: MaintenanceProposalPlan) =>
new Map(plan?.actions.map((action) => [action.idempotencyKey, action]));
const isVisibleProposalResult = (
action: MaintenanceReviewRunResult['actions'][number],
planActionByIdempotencyKey: Map<
string,
- MaintenancePlan['actions'][number]
+ MaintenanceProposalPlan['actions'][number]
> = getPlanActionByIdempotencyKey(),
) => {
if (action.status !== MaintenanceActionStatus.Proposed || !action.receiptId) return false;
@@ -143,7 +304,7 @@ const isVisibleProposalResult = (
const countActions = (
result: MaintenanceReviewRunResult,
- plan?: MaintenancePlan,
+ plan?: MaintenanceProposalPlan,
): MaintenanceBriefActionCounts => {
const counts: MaintenanceBriefActionCounts = {
applied: 0,
@@ -188,7 +349,7 @@ const formatActionSummaries = (
result: MaintenanceReviewRunResult,
status: MaintenanceActionStatus,
heading: string,
- plan?: MaintenancePlan,
+ plan?: MaintenanceProposalPlan,
) => {
const planActionByIdempotencyKey = getPlanActionByIdempotencyKey(plan);
const summaries = result.actions
@@ -210,7 +371,7 @@ const createDetailedSummary = (
result: MaintenanceReviewRunResult,
status: MaintenanceActionStatus,
heading: string,
- plan?: MaintenancePlan,
+ plan?: MaintenanceProposalPlan,
) => {
const details = formatActionSummaries(result, status, heading, plan);
@@ -221,7 +382,7 @@ const createBriefCopy = (
outcome: MaintenanceBriefMetadata['outcome'],
counts: MaintenanceBriefActionCounts,
result: MaintenanceReviewRunResult,
- plan?: MaintenancePlan,
+ plan?: MaintenanceProposalPlan,
) => {
if (outcome === 'proposal') {
const summary = `${counts.proposed} maintenance proposal${counts.proposed === 1 ? '' : 's'} need review.`;
@@ -353,18 +514,13 @@ export const createBriefMaintenanceService = () => ({
return {
...(proposal ? { actions: AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS } : {}),
agentId: input.agentId,
- metadata: {
+ metadata: createNightlySelfReviewBriefMetadata({
actionCounts,
evidenceRefs: input.evidenceRefs ?? [],
- localDate: input.localDate,
+ input,
outcome,
- ...(proposal ? { proposal } : {}),
- receiptIds: getReceiptIds(input.result),
- ...(input.result.sourceId ? { sourceId: input.result.sourceId } : {}),
- timezone: input.timezone,
- windowEnd: input.reviewWindowEnd,
- windowStart: input.reviewWindowStart,
- },
+ proposal,
+ }),
priority: copy.priority,
summary: copy.summary,
title: copy.title,
@@ -391,43 +547,35 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:
const model = new BriefModel(db, userId);
return {
- writeDailyBrief: (brief: MaintenanceBriefProjection) =>
- tracer.startActiveSpan(
+ writeDailyBrief: (brief: MaintenanceBriefProjection) => {
+ const incomingProposal = brief.metadata.agentSignal.nightlySelfReview.maintenanceProposal;
+
+ return 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
+ ...(incomingProposal
? {
- 'agent.signal.proposal.action_count': brief.metadata.proposal.actions.length,
- 'agent.signal.proposal.key': brief.metadata.proposal.proposalKey,
+ 'agent.signal.proposal.action_count': incomingProposal.actions.length,
+ 'agent.signal.proposal.key': incomingProposal.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({
+ const existingBrief = await findExistingProposalBrief({
agentId: brief.agentId,
- limit: 20,
+ incomingProposal,
+ model,
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);
@@ -442,10 +590,7 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:
status: 'expired',
updatedAt: now,
};
- await model.updateMetadata(
- existingBrief.id,
- updateBriefProposalMetadata(existingBrief, expiredProposal),
- );
+ await updateProposalMetadata(model, existingBrief, expiredProposal);
span.setAttribute('agent.signal.proposal.status', 'expired');
return model.create(brief);
@@ -471,27 +616,12 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:
});
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();
- }
- },
- );
+ return refreshProposalBrief({
+ fallbackBrief: brief,
+ model,
+ proposal: refreshedProposal,
+ targetBrief: existingBrief,
+ });
}
const supersede = shouldSupersedeMaintenanceProposal({
@@ -505,25 +635,11 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:
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();
- }
- },
- );
+ await supersedeProposalBrief({
+ model,
+ proposal: supersededProposal,
+ targetBrief: existingBrief,
+ });
span.setAttribute('agent.signal.proposal.status', 'superseded');
return model.create(brief);
@@ -541,6 +657,7 @@ export const createServerMaintenanceBriefWriter = (db: LobeChatDatabase, userId:
span.end();
}
},
- ),
+ );
+ },
};
};
diff --git a/src/server/services/agentSignal/services/maintenance/briefProjection.ts b/src/server/services/agentSignal/services/maintenance/briefProjection.ts
new file mode 100644
index 00000000000..8bd7aaf26a3
--- /dev/null
+++ b/src/server/services/agentSignal/services/maintenance/briefProjection.ts
@@ -0,0 +1,745 @@
+import type { ChatToolPayload } from '@lobechat/types';
+
+import type { MaintenanceProposalBaseSnapshot, MaintenanceProposalPlan } from './proposal';
+import type { MaintenanceToolWriteResult } from './tools';
+import type {
+ MaintenanceActionPlan,
+ MaintenanceActionStatus as MaintenanceActionStatusValue,
+ MaintenanceActionTarget,
+ MaintenanceReviewRunResult,
+ MaintenanceReviewScope,
+} from './types';
+import {
+ MaintenanceActionStatus,
+ MaintenanceApplyMode,
+ MaintenanceRisk,
+ ReviewRunStatus,
+} from './types';
+
+/** Brief category selected from maintenance write-tool outcomes. */
+export type MaintenanceBriefKind = 'decision' | 'insight' | 'none';
+
+/** Write-tool result enriched with the tool name that produced it. */
+export interface MaintenanceToolOutcome extends MaintenanceToolWriteResult {
+ /** Stable write-tool name used for brief metadata and diagnostics. */
+ toolName: string;
+}
+
+/** Input for projecting maintenance write-tool outcomes to Daily Brief metadata. */
+export interface ProjectMaintenanceToolOutcomesInput {
+ /** Terminal write-tool outcomes collected from one maintenance turn. */
+ outcomes: MaintenanceToolOutcome[];
+}
+
+/** Input for projecting a complete tool-first runtime result into legacy brief contracts. */
+export interface ProjectMaintenanceToolRuntimeRunInput extends ProjectMaintenanceToolOutcomesInput {
+ /** Assistant summary emitted by the tool-first runtime. */
+ content?: string;
+ /** User-local nightly date used in the projected maintenance plan. */
+ localDate?: string;
+ /** Review scope attached to the projected maintenance plan. */
+ reviewScope: MaintenanceReviewScope;
+ /** Stable source id used for idempotency-key fallbacks. */
+ sourceId: string;
+ /** Tool calls captured by the runtime in execution order. */
+ toolCalls: ChatToolPayload[];
+ /** Stable user id owning this run. */
+ userId: string;
+}
+
+/** Legacy contracts projected from a tool-first runtime run. */
+export interface ProjectedMaintenanceToolRuntimeRun {
+ /** Executor-shaped result consumed by receipt and brief projection. */
+ execution: MaintenanceReviewRunResult;
+ /** Plan-shaped projection consumed by Daily Brief proposal metadata. */
+ projectionPlan: MaintenanceProposalPlan;
+}
+
+/** Per-status counts retained in brief-compatible metadata. */
+export interface ProjectedMaintenanceToolOutcomeCounts {
+ /** Number of write tools that mutated durable state. */
+ applied: number;
+ /** Number of write tools that failed. */
+ failed: number;
+ /** Number of user-visible proposal writes. */
+ proposed: number;
+ /** Number of write tools skipped or deduped without mutation. */
+ skipped: number;
+}
+
+/** Brief-compatible metadata projected from maintenance write-tool outcomes. */
+export interface ProjectedMaintenanceToolOutcomes {
+ /** Per-status counts used by brief copy and filtering. */
+ actionCounts: ProjectedMaintenanceToolOutcomeCounts;
+ /** Bounded write-tool action fields safe to retain in brief metadata. */
+ actions: MaintenanceToolOutcome[];
+ /** Coarse brief kind selected from visible write-tool outcomes. */
+ briefKind: MaintenanceBriefKind;
+ /** Number of proposed write outcomes that should request a decision brief. */
+ proposalCount: number;
+ /** Durable receipt ids linked to the projected outcomes. */
+ receiptIds: string[];
+}
+
+/**
+ * Normalizes one write-tool outcome to bounded brief action metadata.
+ *
+ * Before:
+ * - `{ toolName: "writeMemory", status: "applied", receiptId: undefined }`
+ *
+ * After:
+ * - `{ toolName: "writeMemory", status: "applied" }`
+ */
+const projectAction = (outcome: MaintenanceToolOutcome): MaintenanceToolOutcome => ({
+ ...(outcome.receiptId === undefined ? {} : { receiptId: outcome.receiptId }),
+ ...(outcome.resourceId === undefined ? {} : { resourceId: outcome.resourceId }),
+ status: outcome.status,
+ ...(outcome.summary === undefined ? {} : { summary: outcome.summary }),
+ toolName: outcome.toolName,
+});
+
+/**
+ * Projects maintenance write-tool outcomes into brief-compatible metadata.
+ *
+ * Use when:
+ * - Maintenance tools need a compact Daily Brief projection
+ * - Tool outcomes should be classified as decision, insight, or silent metadata
+ *
+ * Expects:
+ * - Outcomes are already bounded by write-tool result contracts
+ * - Proposal create, refresh, and supersede tools use `proposed` status for visible decisions
+ *
+ * Returns:
+ * - Counts, receipt ids, bounded actions, and the selected brief kind
+ */
+export const projectMaintenanceToolOutcomes = (
+ input: ProjectMaintenanceToolOutcomesInput,
+): ProjectedMaintenanceToolOutcomes => {
+ const actionCounts: ProjectedMaintenanceToolOutcomeCounts = {
+ applied: 0,
+ failed: 0,
+ proposed: 0,
+ skipped: 0,
+ };
+ const receiptIds: string[] = [];
+
+ for (const outcome of input.outcomes) {
+ if (outcome.receiptId !== undefined) receiptIds.push(outcome.receiptId);
+
+ if (outcome.status === 'applied') actionCounts.applied += 1;
+ if (outcome.status === 'failed') actionCounts.failed += 1;
+ if (outcome.status === 'proposed') actionCounts.proposed += 1;
+ if (
+ outcome.status === 'deduped' ||
+ outcome.status === 'skipped_stale' ||
+ outcome.status === 'skipped_unsupported'
+ ) {
+ actionCounts.skipped += 1;
+ }
+ }
+
+ const proposalCount = input.outcomes.filter(
+ (outcome) =>
+ outcome.status === 'proposed' &&
+ (outcome.toolName === 'createMaintenanceProposal' ||
+ outcome.toolName === 'refreshMaintenanceProposal' ||
+ outcome.toolName === 'supersedeMaintenanceProposal'),
+ ).length;
+ const hasVisibleRiskOutcome = input.outcomes.some(
+ (outcome) => outcome.status === 'failed' || outcome.status === 'skipped_stale',
+ );
+ const briefKind: MaintenanceBriefKind =
+ proposalCount > 0
+ ? 'decision'
+ : actionCounts.applied > 0 || hasVisibleRiskOutcome
+ ? 'insight'
+ : 'none';
+
+ return {
+ actionCounts,
+ actions: input.outcomes.map(projectAction),
+ briefKind,
+ proposalCount,
+ receiptIds,
+ };
+};
+
+const WRITE_TOOL_NAMES = new Set([
+ 'closeMaintenanceProposal',
+ 'createMaintenanceProposal',
+ 'createSkillIfAbsent',
+ 'refreshMaintenanceProposal',
+ 'replaceSkillContentCAS',
+ 'supersedeMaintenanceProposal',
+]);
+
+const parseToolArguments = (value: string | undefined): Record<string, unknown> => {
+ if (!value) return {};
+
+ try {
+ const parsed = JSON.parse(value) as unknown;
+
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+};
+
+const getString = (value: unknown) =>
+ typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+
+const getBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);
+
+const getRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+
+const getBaseSnapshot = (value: unknown): MaintenanceProposalBaseSnapshot | undefined => {
+ const record = getRecord(value);
+ if (Object.keys(record).length === 0) return;
+
+ return {
+ absent: getBoolean(record.absent),
+ agentDocumentId: getString(record.agentDocumentId),
+ contentHash: getString(record.contentHash),
+ documentId: getString(record.documentId),
+ documentUpdatedAt: getString(record.documentUpdatedAt),
+ managed: getBoolean(record.managed),
+ skillName: getString(record.skillName),
+ targetTitle: getString(record.targetTitle),
+ targetType: record.targetType === 'skill' ? 'skill' : undefined,
+ writable: getBoolean(record.writable),
+ };
+};
+
+const toActionStatus = (
+ status: MaintenanceToolWriteResult['status'],
+): MaintenanceActionStatusValue => {
+ if (status === 'applied') return MaintenanceActionStatus.Applied;
+ if (status === 'deduped') return MaintenanceActionStatus.Deduped;
+ if (status === 'failed') return MaintenanceActionStatus.Failed;
+ if (status === 'proposed') return MaintenanceActionStatus.Proposed;
+
+ return MaintenanceActionStatus.Skipped;
+};
+
+const getRunStatus = (actions: MaintenanceReviewRunResult['actions']): ReviewRunStatus => {
+ if (actions.length === 0) return ReviewRunStatus.Skipped;
+
+ const failedCount = actions.filter(
+ (action) => action.status === MaintenanceActionStatus.Failed,
+ ).length;
+ const successfulCount = actions.filter(
+ (action) =>
+ action.status === MaintenanceActionStatus.Applied ||
+ action.status === MaintenanceActionStatus.Proposed,
+ ).length;
+
+ if (failedCount > 0 && successfulCount > 0) return ReviewRunStatus.PartiallyApplied;
+ if (failedCount > 0) return ReviewRunStatus.Failed;
+ if (successfulCount === 0) return ReviewRunStatus.Skipped;
+
+ return ReviewRunStatus.Completed;
+};
+
+const getActionType = (toolName: string): MaintenanceActionPlan['actionType'] => {
+ if (toolName === 'createSkillIfAbsent') return 'create_skill';
+ if (toolName === 'replaceSkillContentCAS') return 'refine_skill';
+
+ return 'proposal_only';
+};
+
+const getWriteToolCalls = (toolCalls: ChatToolPayload[]) =>
+ toolCalls.filter((toolCall) => WRITE_TOOL_NAMES.has(toolCall.apiName));
+
+const getToolCallForOutcome = (
+ writeToolCalls: ChatToolPayload[],
+ outcome: MaintenanceToolOutcome,
+ cursors: Map<string, number>,
+) => {
+ const startIndex = cursors.get(outcome.toolName) ?? 0;
+ const matchingIndex = writeToolCalls.findIndex(
+ (toolCall, index) => index >= startIndex && toolCall.apiName === outcome.toolName,
+ );
+
+ if (matchingIndex === -1) return;
+
+ cursors.set(outcome.toolName, matchingIndex + 1);
+
+ return writeToolCalls[matchingIndex];
+};
+
+const getIdempotencyKey = ({
+ args,
+ sourceId,
+ toolCall,
+ toolName,
+}: {
+ args: Record<string, unknown>;
+ sourceId: string;
+ toolCall?: ChatToolPayload;
+ toolName: string;
+}) =>
+ getString(args.idempotencyKey) ??
+ outcomeFallbackIdempotencyKey({
+ sourceId,
+ toolCallId: toolCall?.id,
+ toolName,
+ });
+
+const outcomeFallbackIdempotencyKey = ({
+ sourceId,
+ toolCallId,
+ toolName,
+}: {
+ sourceId: string;
+ toolCallId?: string;
+ toolName: string;
+}) => `${sourceId}:${toolName}:${toolCallId ?? 'tool-outcome'}`;
+
+const getSkillCreateOperation = (args: Record<string, unknown>, userId: string) => ({
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: getString(args.bodyMarkdown),
+ description: getString(args.description),
+ name: getString(args.name),
+ title: getString(args.title),
+ userId,
+ },
+ operation: 'create' as const,
+});
+
+const getSkillRefineOperation = (args: Record<string, unknown>, userId: string) => {
+ const skillDocumentId = getString(args.skillDocumentId);
+ if (!skillDocumentId) return;
+
+ return {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: getString(args.bodyMarkdown),
+ description: getString(args.description),
+ skillDocumentId,
+ userId,
+ },
+ operation: 'refine' as const,
+ };
+};
+
+const toEvidenceRefs = (value: unknown): MaintenanceActionPlan['evidenceRefs'] =>
+ Array.isArray(value)
+ ? value.flatMap((item) => {
+ const record = getRecord(item);
+ const id = getString(record.id);
+ const type = getString(record.type);
+
+ return id && type
+ ? [{ id, type: type as MaintenanceActionPlan['evidenceRefs'][number]['type'] }]
+ : [];
+ })
+ : [];
+
+const toTarget = (value: unknown): MaintenanceActionTarget | undefined => {
+ const record = getRecord(value);
+ const memoryId = getString(record.memoryId);
+ const skillDocumentId = getString(record.skillDocumentId);
+ const skillName = getString(record.skillName);
+ const targetReadonly = getBoolean(record.targetReadonly);
+
+ if (!memoryId && !skillDocumentId && !skillName && targetReadonly === undefined) return;
+
+ return {
+ ...(memoryId ? { memoryId } : {}),
+ ...(skillDocumentId ? { skillDocumentId } : {}),
+ ...(skillName ? { skillName } : {}),
+ ...(targetReadonly === undefined ? {} : { targetReadonly }),
+ };
+};
+
+const toRisk = (value: unknown) => {
+ if (value === MaintenanceRisk.High) return MaintenanceRisk.High;
+ if (value === MaintenanceRisk.Medium) return MaintenanceRisk.Medium;
+
+ return MaintenanceRisk.Low;
+};
+
+const toApplyMode = (value: unknown, outcome: MaintenanceToolOutcome) => {
+ if (value === MaintenanceApplyMode.AutoApply) return MaintenanceApplyMode.AutoApply;
+ if (value === MaintenanceApplyMode.Skip) return MaintenanceApplyMode.Skip;
+ if (value === MaintenanceApplyMode.ProposalOnly) return MaintenanceApplyMode.ProposalOnly;
+
+ return outcome.status === 'proposed'
+ ? MaintenanceApplyMode.ProposalOnly
+ : MaintenanceApplyMode.AutoApply;
+};
+
+const toConfidence = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 1;
+
+const toSkillOperation = (value: unknown, userId: string): MaintenanceActionPlan['operation'] => {
+ const record = getRecord(value);
+ if (record.domain !== 'skill') return;
+
+ const input = getRecord(record.input);
+
+ if (record.operation === 'create') {
+ return {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: getString(input.bodyMarkdown),
+ description: getString(input.description),
+ name: getString(input.name),
+ title: getString(input.title),
+ userId: getString(input.userId) ?? userId,
+ },
+ operation: 'create',
+ };
+ }
+
+ if (record.operation === 'refine') {
+ const skillDocumentId = getString(input.skillDocumentId);
+ if (!skillDocumentId) return;
+
+ return {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: getString(input.bodyMarkdown),
+ patch: getString(input.patch),
+ skillDocumentId,
+ userId: getString(input.userId) ?? userId,
+ },
+ operation: 'refine',
+ };
+ }
+};
+
+const getRawActionType = (value: unknown): MaintenanceActionPlan['actionType'] | undefined => {
+ if (
+ value === 'write_memory' ||
+ value === 'create_skill' ||
+ value === 'refine_skill' ||
+ value === 'consolidate_skill' ||
+ value === 'noop' ||
+ value === 'proposal_only'
+ ) {
+ return value;
+ }
+};
+
+const getTargetDedupeKey = (
+ actionType: MaintenanceActionPlan['actionType'],
+ target: MaintenanceActionTarget | undefined,
+) => {
+ if (target?.skillDocumentId) return `skill:${target.skillDocumentId}`;
+ if (target?.skillName) return `skill:${target.skillName}`;
+ if (target?.memoryId) return `memory:${target.memoryId}`;
+
+ return actionType;
+};
+
+const getCompleteBaseSnapshot = ({
+ actionType,
+ baseSnapshot,
+ operation,
+ target,
+}: {
+ actionType: MaintenanceActionPlan['actionType'];
+ baseSnapshot: MaintenanceProposalBaseSnapshot | undefined;
+ operation: MaintenanceActionPlan['operation'];
+ target: MaintenanceActionTarget | undefined;
+}): MaintenanceProposalBaseSnapshot | undefined => {
+ if (actionType === 'create_skill') {
+ return {
+ absent: true,
+ ...baseSnapshot,
+ skillName:
+ baseSnapshot?.skillName ??
+ target?.skillName ??
+ (operation?.domain === 'skill' && operation.operation === 'create'
+ ? operation.input.name
+ : undefined),
+ targetType: 'skill',
+ };
+ }
+
+ if (actionType === 'refine_skill') return baseSnapshot;
+
+ return baseSnapshot;
+};
+
+const getProjectionActionFromRaw = ({
+ fallbackIdempotencyKey,
+ index,
+ outcome,
+ rawAction,
+ userId,
+}: {
+ fallbackIdempotencyKey: string;
+ index: number;
+ outcome: MaintenanceToolOutcome;
+ rawAction: unknown;
+ userId: string;
+}): MaintenanceProposalPlan['actions'][number] | undefined => {
+ const record = getRecord(rawAction);
+ const actionType = getRawActionType(record.actionType);
+ const idempotencyKey =
+ getString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:action:${index + 1}`;
+
+ if (!actionType) return;
+
+ const operation = toSkillOperation(record.operation, userId);
+ const target = toTarget(record.target);
+ const baseSnapshot = getCompleteBaseSnapshot({
+ actionType,
+ baseSnapshot: getBaseSnapshot(record.baseSnapshot),
+ operation,
+ target,
+ });
+ const baseAction = {
+ applyMode: toApplyMode(record.applyMode, outcome),
+ confidence: toConfidence(record.confidence),
+ dedupeKey: getString(record.dedupeKey) ?? getTargetDedupeKey(actionType, target),
+ evidenceRefs: toEvidenceRefs(record.evidenceRefs),
+ idempotencyKey,
+ rationale: getString(record.rationale) ?? outcome.summary ?? 'Maintenance proposal action.',
+ risk: toRisk(record.risk),
+ ...(operation ? { operation } : {}),
+ ...(target ? { target } : {}),
+ };
+
+ if (actionType === 'create_skill') {
+ return {
+ ...baseAction,
+ actionType,
+ baseSnapshot: baseSnapshot ?? { absent: true, targetType: 'skill' },
+ };
+ }
+
+ if (actionType === 'refine_skill') {
+ if (!baseSnapshot) return;
+
+ return {
+ ...baseAction,
+ actionType,
+ baseSnapshot,
+ };
+ }
+
+ return {
+ ...baseAction,
+ actionType,
+ ...(baseSnapshot ? { baseSnapshot } : {}),
+ };
+};
+
+const getProjectionActionsFromProposalArgs = ({
+ args,
+ idempotencyKey,
+ outcome,
+ sourceId,
+ userId,
+}: {
+ args: Record<string, unknown>;
+ idempotencyKey: string;
+ outcome: MaintenanceToolOutcome;
+ sourceId: string;
+ userId: string;
+}): MaintenanceProposalPlan['actions'] =>
+ Array.isArray(args.actions)
+ ? args.actions.flatMap((rawAction, index) => {
+ const action = getProjectionActionFromRaw({
+ fallbackIdempotencyKey: idempotencyKey,
+ index,
+ outcome,
+ rawAction,
+ userId,
+ });
+
+ return action ? [action] : [];
+ })
+ : [];
+
+const getProjectionAction = ({
+ args,
+ idempotencyKey,
+ outcome,
+ toolName,
+ userId,
+}: {
+ args: Record<string, unknown>;
+ idempotencyKey: string;
+ outcome: MaintenanceToolOutcome;
+ toolName: string;
+ userId: string;
+}): MaintenanceProposalPlan['actions'][number] => {
+ const actionType = getActionType(toolName);
+ const skillDocumentId = getString(args.skillDocumentId) ?? outcome.resourceId;
+ const skillName = getString(args.name);
+ const baseSnapshot = getBaseSnapshot(args.baseSnapshot);
+ const baseAction = {
+ applyMode:
+ outcome.status === 'proposed'
+ ? MaintenanceApplyMode.ProposalOnly
+ : MaintenanceApplyMode.AutoApply,
+ confidence: 1,
+ dedupeKey: getString(args.proposalKey) ?? outcome.resourceId ?? idempotencyKey,
+ evidenceRefs: [],
+ idempotencyKey,
+ rationale: outcome.summary ?? 'Maintenance tool write outcome.',
+ risk: outcome.status === 'failed' ? MaintenanceRisk.Medium : MaintenanceRisk.Low,
+ ...(skillDocumentId || skillName
+ ? {
+ target: {
+ ...(skillDocumentId ? { skillDocumentId } : {}),
+ ...(skillName ? { skillName } : {}),
+ },
+ }
+ : {}),
+ };
+
+ if (actionType === 'create_skill') {
+ return {
+ ...baseAction,
+ actionType,
+ baseSnapshot: baseSnapshot ?? {
+ absent: true,
+ ...(skillName ? { skillName } : {}),
+ targetType: 'skill',
+ },
+ operation: getSkillCreateOperation(args, userId),
+ };
+ }
+
+ if (actionType === 'refine_skill') {
+ return {
+ ...baseAction,
+ actionType,
+ baseSnapshot: baseSnapshot ?? {
+ ...(skillDocumentId ? { agentDocumentId: skillDocumentId } : {}),
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ ...(getSkillRefineOperation(args, userId)
+ ? { operation: getSkillRefineOperation(args, userId) }
+ : {}),
+ };
+ }
+
+ return {
+ ...baseAction,
+ actionType,
+ ...(baseSnapshot ? { baseSnapshot } : {}),
+ };
+};
+
+/**
+ * Projects a tool-first runtime run into legacy execution and proposal contracts.
+ *
+ * Use when:
+ * - The nightly server runtime has write-tool outcomes instead of executor results
+ * - Daily Brief projection still expects `MaintenanceReviewRunResult` and `MaintenanceProposalPlan`
+ *
+ * Expects:
+ * - Runtime write outcomes and write tool calls are in execution order
+ * - Tool write results have already passed safe mutation boundaries
+ *
+ * Returns:
+ * - A completed/skipped/failed execution result plus a plan containing only confirmed tool writes
+ */
+export const projectMaintenanceToolRuntimeRun = (
+ input: ProjectMaintenanceToolRuntimeRunInput,
+): ProjectedMaintenanceToolRuntimeRun => {
+ const writeToolCalls = getWriteToolCalls(input.toolCalls);
+ const projectionActions: MaintenanceProposalPlan['actions'] = [];
+ const executionActions: MaintenanceReviewRunResult['actions'] = [];
+ const toolCallCursors = new Map<string, number>();
+
+ for (const outcome of input.outcomes) {
+ const toolCall = getToolCallForOutcome(writeToolCalls, outcome, toolCallCursors);
+ const args = parseToolArguments(toolCall?.arguments);
+ const idempotencyKey = getIdempotencyKey({
+ args,
+ sourceId: input.sourceId,
+ toolCall,
+ toolName: outcome.toolName,
+ });
+ const proposalActions =
+ outcome.toolName === 'createMaintenanceProposal' ||
+ outcome.toolName === 'refreshMaintenanceProposal' ||
+ outcome.toolName === 'supersedeMaintenanceProposal'
+ ? getProjectionActionsFromProposalArgs({
+ args,
+ idempotencyKey,
+ outcome,
+ sourceId: input.sourceId,
+ userId: input.userId,
+ })
+ : [];
+
+ if (
+ outcome.toolName === 'createMaintenanceProposal' ||
+ outcome.toolName === 'refreshMaintenanceProposal' ||
+ outcome.toolName === 'supersedeMaintenanceProposal'
+ ) {
+ if (proposalActions.length > 0) {
+ projectionActions.push(...proposalActions);
+ executionActions.push(
+ ...proposalActions.map((action) => ({
+ idempotencyKey: action.idempotencyKey,
+ ...(outcome.receiptId ? { receiptId: outcome.receiptId } : {}),
+ ...(outcome.resourceId ? { resourceId: outcome.resourceId } : {}),
+ status: toActionStatus(outcome.status),
+ ...(outcome.summary ? { summary: outcome.summary } : {}),
+ })),
+ );
+ continue;
+ }
+
+ executionActions.push({
+ idempotencyKey,
+ ...(outcome.receiptId ? { receiptId: outcome.receiptId } : {}),
+ ...(outcome.resourceId ? { resourceId: outcome.resourceId } : {}),
+ status: MaintenanceActionStatus.Skipped,
+ summary:
+ outcome.summary ??
+ 'Maintenance proposal lifecycle update did not include executable proposal actions.',
+ });
+ continue;
+ }
+
+ projectionActions.push(
+ getProjectionAction({
+ args,
+ idempotencyKey,
+ outcome,
+ toolName: outcome.toolName,
+ userId: input.userId,
+ }),
+ );
+ executionActions.push({
+ idempotencyKey,
+ ...(outcome.receiptId ? { receiptId: outcome.receiptId } : {}),
+ ...(outcome.resourceId ? { resourceId: outcome.resourceId } : {}),
+ status: toActionStatus(outcome.status),
+ ...(outcome.summary ? { summary: outcome.summary } : {}),
+ });
+ }
+
+ const projectionPlan: MaintenanceProposalPlan = {
+ actions: projectionActions,
+ ...(input.localDate ? { localDate: input.localDate } : {}),
+ plannerVersion: 'maintenance-tool-first-runtime-v1',
+ reviewScope: input.reviewScope,
+ summary: input.content?.trim() || 'Maintenance tool-first runtime completed.',
+ };
+ const execution: MaintenanceReviewRunResult = {
+ actions: executionActions,
+ sourceId: input.sourceId,
+ status: getRunStatus(executionActions),
+ };
+
+ return { execution, projectionPlan };
+};
diff --git a/src/server/services/agentSignal/services/maintenance/nightlySignals.ts b/src/server/services/agentSignal/services/maintenance/nightlySignals.ts
index d6fb8099efe..b5eb1cb2025 100644
--- a/src/server/services/agentSignal/services/maintenance/nightlySignals.ts
+++ b/src/server/services/agentSignal/services/maintenance/nightlySignals.ts
@@ -49,26 +49,6 @@ 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/proposal.ts b/src/server/services/agentSignal/services/maintenance/proposal.ts
index c91adc0cd3a..0c5a6a31939 100644
--- a/src/server/services/agentSignal/services/maintenance/proposal.ts
+++ b/src/server/services/agentSignal/services/maintenance/proposal.ts
@@ -1,4 +1,5 @@
import type { BriefAction } from '@lobechat/types';
+import { z } from 'zod';
import type {
EvidenceRef,
@@ -54,8 +55,13 @@ const MAINTENANCE_RISKS = [
export type MaintenanceProposalConflictReason =
| 'agent_gate_disabled'
+ | 'content_changed'
| 'document_changed'
+ | 'snapshot_incomplete'
+ | 'snapshot_missing'
+ | 'target_conflict'
| 'target_deleted'
+ | 'target_unmanaged'
| 'target_not_writable'
| 'target_type_changed'
| 'user_gate_disabled'
@@ -73,6 +79,8 @@ export interface BuildMaintenanceProposalKeyInput {
}
export interface MaintenanceProposalBaseSnapshot {
+ /** Whether the target was absent when the proposal was approved for creation. */
+ absent?: boolean;
/** Agent document id when the proposal targets managed skill/document state. */
agentDocumentId?: string;
/** Content hash observed when the proposal was created. */
@@ -83,8 +91,12 @@ export interface MaintenanceProposalBaseSnapshot {
documentUpdatedAt?: string;
/** Whether the target was managed by Agent Signal. */
managed?: boolean;
+ /** Stable skill name observed or reserved when the proposal was created. */
+ skillName?: string;
/** Human-readable target title observed at proposal time. */
targetTitle?: string;
+ /** Target domain captured by the proposal snapshot. */
+ targetType?: 'skill';
/** Whether the target was writable at proposal time. */
writable?: boolean;
}
@@ -108,6 +120,45 @@ export interface MaintenanceProposalAction {
target?: MaintenanceActionTarget;
}
+/**
+ * Proposal projection action for mergeable skill mutations.
+ *
+ * @param TActionType - Mergeable action type that must carry a complete base snapshot.
+ */
+export type MergeableMaintenanceProposalActionPlan<
+ TActionType extends 'create_skill' | 'refine_skill' = 'create_skill' | 'refine_skill',
+> = MaintenanceActionPlan & {
+ /** Mergeable action type that will be applied from a frozen proposal. */
+ actionType: TActionType;
+ /** Complete merge base captured before proposal projection. */
+ baseSnapshot: MaintenanceProposalBaseSnapshot;
+};
+
+/**
+ * Proposal projection action for non-mergeable maintenance mutations.
+ */
+export type NonMergeableMaintenanceProposalActionPlan = MaintenanceActionPlan & {
+ /** Non-mergeable action type that can use legacy title-only fallback snapshots. */
+ actionType: Exclude<MaintenanceActionType, 'create_skill' | 'refine_skill'>;
+ /** Optional proposal snapshot supplied by callers before projection. */
+ baseSnapshot?: MaintenanceProposalBaseSnapshot;
+};
+
+/**
+ * Snapshot-aware action accepted by proposal metadata projection.
+ */
+export type MaintenanceProposalActionPlan =
+ | MergeableMaintenanceProposalActionPlan
+ | NonMergeableMaintenanceProposalActionPlan;
+
+/**
+ * Snapshot-aware maintenance plan accepted by proposal metadata projection.
+ */
+export type MaintenanceProposalPlan = Omit<MaintenancePlan, 'actions'> & {
+ /** Planned actions with required base snapshots for mergeable proposal mutations. */
+ actions: MaintenanceProposalActionPlan[];
+};
+
export interface MaintenanceProposalActionApplyResult {
/** Frozen action idempotency key this apply result belongs to. */
idempotencyKey: string;
@@ -160,6 +211,16 @@ export interface MaintenanceProposalMetadata {
}
export interface MaintenanceProposalBriefMetadata {
+ /** Namespaced Agent Signal metadata stored inside Daily Brief metadata. */
+ agentSignal?: {
+ /** Nightly self-review metadata owned by Agent Signal maintenance. */
+ nightlySelfReview?: {
+ /** Frozen maintenance proposal state for approve/dismiss flows. */
+ maintenanceProposal?: MaintenanceProposalMetadata;
+ /** Legacy transition field accepted while local data is migrated. */
+ proposal?: MaintenanceProposalMetadata;
+ };
+ };
/** Agent Signal maintenance proposal metadata stored inside Daily Brief metadata. */
proposal?: MaintenanceProposalMetadata;
}
@@ -170,33 +231,100 @@ export const AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS = [
{ 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 EvidenceRefSchema = z
+ .object({
+ id: z.string(),
+ summary: z.string().optional(),
+ type: z.enum([
+ 'topic',
+ 'message',
+ 'operation',
+ 'source',
+ 'receipt',
+ 'tool_call',
+ 'task',
+ 'agent_document',
+ 'memory',
+ ]),
+ })
+ .passthrough();
+
+const MaintenanceProposalBaseSnapshotSchema = z
+ .object({
+ absent: z.boolean().optional(),
+ agentDocumentId: z.string().optional(),
+ contentHash: z.string().optional(),
+ documentId: z.string().optional(),
+ documentUpdatedAt: z.string().optional(),
+ managed: z.boolean().optional(),
+ skillName: z.string().optional(),
+ targetTitle: z.string().optional(),
+ targetType: z.literal('skill').optional(),
+ writable: z.boolean().optional(),
+ })
+ .passthrough();
+
+const MaintenanceProposalActionSchema = z
+ .object({
+ actionType: z.enum(MAINTENANCE_ACTION_TYPES),
+ baseSnapshot: MaintenanceProposalBaseSnapshotSchema.optional(),
+ evidenceRefs: z.array(EvidenceRefSchema),
+ idempotencyKey: z.string(),
+ operation: z.unknown().optional(),
+ rationale: z.string(),
+ risk: z.enum(MAINTENANCE_RISKS),
+ target: z.unknown().optional(),
+ })
+ .passthrough();
+
+const MaintenanceProposalMetadataSchema = z
+ .object({
+ actions: z.array(MaintenanceProposalActionSchema),
+ actionType: z.enum(MAINTENANCE_ACTION_TYPES),
+ applyAttempts: z.unknown().optional(),
+ conflictReason: z.unknown().optional(),
+ createdAt: z.string(),
+ evidenceRefs: z.array(EvidenceRefSchema).optional(),
+ evidenceWindowEnd: z.string(),
+ evidenceWindowStart: z.string(),
+ expiresAt: z.string(),
+ proposalKey: z.string(),
+ status: z.enum(MAINTENANCE_PROPOSAL_STATUSES),
+ supersededBy: z.string().optional(),
+ updatedAt: z.string(),
+ version: z.literal(MAINTENANCE_PROPOSAL_VERSION),
+ })
+ .passthrough();
+
+const getMergeableProposalSnapshotError = (action: MaintenanceProposalActionPlan) =>
+ `Mergeable proposal action requires a complete base snapshot. actionType=${action.actionType}`;
+
+const isMergeableProposalAction = (actionType: string) =>
+ actionType === 'create_skill' || actionType === 'refine_skill';
+
+const hasRequiredString = (value: unknown) => typeof value === 'string' && value.trim().length > 0;
+
+const hasCompleteMergeableSnapshot = (
+ actionType: string,
+ snapshot: MaintenanceProposalBaseSnapshot | undefined,
+) => {
+ if (!snapshot || snapshot.targetType !== 'skill') return false;
+
+ if (actionType === 'refine_skill') {
+ return (
+ hasRequiredString(snapshot.agentDocumentId) &&
+ hasRequiredString(snapshot.documentId) &&
+ hasRequiredString(snapshot.contentHash) &&
+ snapshot.managed === true &&
+ snapshot.writable === true
+ );
+ }
- const action = value as Record<string, unknown>;
+ if (actionType === 'create_skill') {
+ return snapshot.absent === true && hasRequiredString(snapshot.skillName);
+ }
- return (
- isKnownStringValue(action.actionType, MAINTENANCE_ACTION_TYPES) &&
- isEvidenceRefArray(action.evidenceRefs) &&
- typeof action.idempotencyKey === 'string' &&
- typeof action.rationale === 'string' &&
- isKnownStringValue(action.risk, MAINTENANCE_RISKS)
- );
+ return false;
};
/**
@@ -257,26 +385,8 @@ export const getNextProposalExpiry = ({ createdAt, now }: { createdAt: string; n
*/
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)
- );
-};
+): value is MaintenanceProposalMetadata =>
+ MaintenanceProposalMetadataSchema.safeParse(value).success;
/**
* Reads proposal metadata from a Daily Brief metadata object.
@@ -296,7 +406,11 @@ export const getMaintenanceProposalFromBriefMetadata = (
): MaintenanceProposalMetadata | undefined => {
if (!metadata || typeof metadata !== 'object') return;
- const proposal = (metadata as MaintenanceProposalBriefMetadata).proposal;
+ const payload = metadata as MaintenanceProposalBriefMetadata;
+ const proposal =
+ payload.agentSignal?.nightlySelfReview?.maintenanceProposal ??
+ payload.agentSignal?.nightlySelfReview?.proposal ??
+ payload.proposal;
return isMaintenanceProposalMetadata(proposal) ? proposal : undefined;
};
@@ -323,11 +437,19 @@ const getOperationTargetTitle = (action: MaintenanceActionPlan) => {
};
const getProposalBaseSnapshot = (
- action: MaintenanceActionPlan,
+ action: MaintenanceProposalActionPlan,
): MaintenanceProposalBaseSnapshot | undefined => {
+ if (isMergeableProposalAction(action.actionType)) {
+ if (!hasCompleteMergeableSnapshot(action.actionType, action.baseSnapshot)) {
+ throw new Error(getMergeableProposalSnapshotError(action));
+ }
+
+ return action.baseSnapshot;
+ }
+
const targetTitle = getOperationTargetTitle(action) ?? action.target?.skillName;
- return targetTitle ? { targetTitle } : undefined;
+ return action.baseSnapshot ?? (targetTitle ? { targetTitle } : undefined);
};
export interface BuildMaintenanceProposalFromPlanInput {
@@ -339,8 +461,8 @@ export interface BuildMaintenanceProposalFromPlanInput {
evidenceWindowStart: string;
/** Stable timestamp to use for created/updated proposal metadata. */
now: string;
- /** Frozen maintenance plan generated before execution. */
- plan: MaintenancePlan;
+ /** Snapshot-aware maintenance plan generated before proposal projection. */
+ plan: MaintenanceProposalPlan;
/** Execution results that identify which actions stayed proposed. */
results: MaintenanceActionResult[];
}
diff --git a/src/server/services/agentSignal/services/maintenance/proposalApply.ts b/src/server/services/agentSignal/services/maintenance/proposalApply.ts
index 7c59060ab17..6c6cf8f106e 100644
--- a/src/server/services/agentSignal/services/maintenance/proposalApply.ts
+++ b/src/server/services/agentSignal/services/maintenance/proposalApply.ts
@@ -1,7 +1,6 @@
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,
@@ -11,14 +10,9 @@ import type {
MaintenanceProposalMetadata,
} from './proposal';
import type { MaintenanceProposalPreflightResult } from './proposalPreflight';
-import type { MaintenanceActionResult, MaintenancePlan, MaintenanceReviewRunResult } from './types';
-import {
- MaintenanceActionStatus,
- MaintenanceApplyMode,
- MaintenanceReviewScope,
- MaintenanceRisk,
- ReviewRunStatus,
-} from './types';
+import type { MaintenanceTools, MaintenanceToolWriteResult } from './tools';
+import type { MaintenanceReviewRunResult } from './types';
+import { MaintenanceActionStatus, ReviewRunStatus } from './types';
export interface ApplyMaintenanceProposalInput {
/** Agent that owns the proposal target. */
@@ -40,7 +34,7 @@ export interface ApplyMaintenanceProposalInput {
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. */
+ /** Synthetic review result projected from approve-time tool outcomes. */
result: MaintenanceReviewRunResult;
}
@@ -49,40 +43,19 @@ export interface MaintenanceProposalApplyAdapters {
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;
+ /** Safe maintenance write tools used for approve-time proposal application. */
+ tools: Pick<MaintenanceTools, 'createSkillIfAbsent' | 'replaceSkillContentCAS'>;
/** Persists updated proposal metadata. */
updateProposal: (proposal: MaintenanceProposalMetadata) => Promise<void>;
- /** Persists approve-time receipts for the executed subset. */
- writeReceipts?: (input: CreateMaintenanceReviewReceiptsInput) => Promise<void>;
}
-interface PreparedAction {
+interface PreparedToolAction {
action: MaintenanceProposalAction;
- planAction: MaintenancePlan['actions'][number];
+ apply: () => Promise<MaintenanceToolWriteResult>;
}
-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'],
@@ -93,12 +66,22 @@ const toApplyResult = (
summary,
});
-const mapExecutionStatus = (
- result: MaintenanceActionResult,
+const getOptionalString = (value: unknown) => (typeof value === 'string' ? value : undefined);
+
+const getRequiredString = (value: unknown) => {
+ const text = getOptionalString(value)?.trim();
+
+ return text || undefined;
+};
+
+const mapToolStatus = (
+ result: MaintenanceToolWriteResult,
): MaintenanceProposalActionApplyResult['status'] => {
- if (result.status === MaintenanceActionStatus.Applied) return 'applied';
- if (result.status === MaintenanceActionStatus.Deduped) return 'deduped';
- if (result.status === MaintenanceActionStatus.Failed) return 'failed';
+ if (result.status === 'applied') return 'applied';
+ if (result.status === 'deduped') return 'deduped';
+ if (result.status === 'failed') return 'failed';
+ if (result.status === 'skipped_stale') return 'skipped_stale';
+ if (result.status === 'skipped_unsupported') return 'skipped_unsupported';
return 'skipped_unsupported';
};
@@ -155,9 +138,110 @@ const buildSyntheticResult = (
})),
status: actionResults.some((result) => result.status === 'failed')
? ReviewRunStatus.Failed
- : ReviewRunStatus.Skipped,
+ : actionResults.some((result) => result.status === 'applied' || result.status === 'deduped')
+ ? ReviewRunStatus.Completed
+ : ReviewRunStatus.Skipped,
});
+const buildUnsupportedResult = (action: MaintenanceProposalAction) =>
+ toApplyResult(
+ action,
+ 'skipped_unsupported',
+ 'Proposal action is not supported by approve-time apply.',
+ );
+
+const prepareToolAction = (
+ action: MaintenanceProposalAction,
+ input: ApplyMaintenanceProposalInput,
+ adapters: MaintenanceProposalApplyAdapters,
+): MaintenanceProposalActionApplyResult | PreparedToolAction => {
+ if (action.actionType === 'consolidate_skill') return buildUnsupportedResult(action);
+
+ if (action.actionType === 'refine_skill') {
+ if (
+ action.operation?.domain !== 'skill' ||
+ action.operation.operation !== 'refine' ||
+ !action.baseSnapshot
+ ) {
+ return toApplyResult(
+ action,
+ 'skipped_unsupported',
+ 'Proposal action is missing an executable operation.',
+ );
+ }
+
+ const operation = action.operation;
+ const operationInput = operation.input as unknown as Record<string, unknown>;
+ const bodyMarkdown = getRequiredString(operation.input.bodyMarkdown);
+ const description = getOptionalString(operationInput.description);
+ const skillDocumentId = getRequiredString(operation.input.skillDocumentId);
+
+ if (!bodyMarkdown || !skillDocumentId) {
+ return toApplyResult(
+ action,
+ 'skipped_unsupported',
+ 'Proposal action is missing an executable operation.',
+ );
+ }
+
+ return {
+ action,
+ apply: () =>
+ adapters.tools.replaceSkillContentCAS({
+ baseSnapshot: action.baseSnapshot!,
+ bodyMarkdown,
+ ...(description ? { description } : {}),
+ idempotencyKey: action.idempotencyKey,
+ proposalKey: input.proposal.proposalKey,
+ skillDocumentId,
+ summary: action.rationale,
+ userId: input.userId,
+ }),
+ };
+ }
+
+ if (action.actionType === 'create_skill') {
+ if (action.operation?.domain !== 'skill' || action.operation.operation !== 'create') {
+ return toApplyResult(
+ action,
+ 'skipped_unsupported',
+ 'Proposal action is missing an executable operation.',
+ );
+ }
+
+ const operation = action.operation;
+ const bodyMarkdown = getRequiredString(operation.input.bodyMarkdown);
+ const description = getOptionalString(operation.input.description);
+ const name = getRequiredString(operation.input.name);
+ const title = getOptionalString(operation.input.title);
+
+ if (!bodyMarkdown || !name) {
+ return toApplyResult(
+ action,
+ 'skipped_unsupported',
+ 'Proposal action is missing an executable operation.',
+ );
+ }
+
+ return {
+ action,
+ apply: () =>
+ adapters.tools.createSkillIfAbsent({
+ bodyMarkdown,
+ ...(description ? { description } : {}),
+ idempotencyKey: action.idempotencyKey,
+ name,
+ proposalKey: input.proposal.proposalKey,
+ summary: action.rationale,
+ ...(title ? { title } : {}),
+ userId: input.userId,
+ }),
+ };
+ }
+
+ return buildUnsupportedResult(action);
+};
+
/**
* Creates the approve-time merge path for Agent Signal maintenance proposals.
*
@@ -167,7 +251,7 @@ const buildSyntheticResult = (
*
* Expects:
* - Callers persist proposal metadata through `updateProposal`
- * - `executePlan` is the same executor family used by nightly maintenance
+ * - `tools` are safe maintenance write tools with their own idempotency and mutation guards
*
* Returns:
* - A service that records one apply attempt and never reruns reviewer/planner
@@ -192,7 +276,7 @@ export const createMaintenanceProposalApplyService = (
const now = adapters.now?.() ?? new Date().toISOString();
const gateResult = await adapters.checkGates();
const skippedResults: MaintenanceProposalActionApplyResult[] = [];
- const executableActions: PreparedAction[] = [];
+ const executableActions: PreparedToolAction[] = [];
let conflictReason: MaintenanceProposalConflictReason | undefined;
if (!gateResult.allowed) {
@@ -219,49 +303,27 @@ export const createMaintenanceProposalApplyService = (
continue;
}
- const planAction = toPlanAction(action);
- if (!planAction) {
- skippedResults.push(
- toApplyResult(
- action,
- 'skipped_unsupported',
- 'Proposal action is missing an executable operation.',
- ),
- );
+ const prepared = prepareToolAction(action, input, adapters);
+ if ('status' in prepared) {
+ skippedResults.push(prepared);
continue;
}
- executableActions.push({ action, planAction });
+ executableActions.push(prepared);
}
}
- 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 {
+ const executedResults = [];
+ for (const { action, apply } of executableActions) {
+ const result = await apply();
+ executedResults.push({
idempotencyKey: action.idempotencyKey,
...(result.resourceId ? { resourceId: result.resourceId } : {}),
- status: mapExecutionStatus(result),
+ status: mapToolStatus(result),
...(result.summary ? { summary: result.summary } : {}),
- };
- });
+ });
+ }
+
const applyResultByKey = new Map(
[...executedResults, ...skippedResults].map((result) => [
result.idempotencyKey,
@@ -286,24 +348,14 @@ export const createMaintenanceProposalApplyService = (
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,
- });
- }
+ const execution = buildSyntheticResult(actionResults);
await adapters.updateProposal(proposal);
span.setAttribute('agent.signal.proposal.apply_status', proposal.status);
- span.setAttribute('agent.signal.proposal.executable_action_count', plan.actions.length);
+ span.setAttribute(
+ 'agent.signal.proposal.executable_action_count',
+ executableActions.length,
+ );
if (conflictReason) {
span.setAttribute('agent.signal.proposal.conflict_reason', conflictReason);
}
diff --git a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts b/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts
index 9e8a4cf07c2..e7cada95b54 100644
--- a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts
+++ b/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts
@@ -1,29 +1,26 @@
-import type { MaintenanceProposalAction, MaintenanceProposalConflictReason } from './proposal';
+import type {
+ MaintenanceProposalAction,
+ MaintenanceProposalBaseSnapshot,
+ 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 {
+ /** Checks whether a proposed stable skill name is still absent. */
+ isSkillNameAvailable: (input: {
+ /** Agent namespace when the caller can provide it. */
+ agentId?: string;
+ /** Stable skill name requested by the proposal. */
+ name: string;
+ /** User namespace when the caller can provide it. */
+ userId?: string;
+ }) => Promise<boolean>;
/** Reads current managed skill target state by agent document id. */
- readSkillTarget: (
- agentDocumentId: string,
- ) => Promise<MaintenanceProposalSkillTargetSnapshot | undefined>;
+ readSkillTargetSnapshot: (
+ skillDocumentId: string,
+ ) => Promise<MaintenanceProposalBaseSnapshot | undefined>;
}
/** Successful proposal preflight result. */
@@ -53,10 +50,10 @@ export type MaintenanceProposalPreflightResult =
*
* Expects:
* - Proposal actions include the base snapshot captured when the proposal was created
- * - `readSkillTarget` returns current truth for the same user/agent boundary
+ * - Adapters return current truth for the same user/agent boundary
*
* Returns:
- * - A service that accepts unchanged `refine_skill` targets and rejects drifted targets
+ * - A service that accepts fresh create/refine skill proposals and rejects stale targets
*/
export const createMaintenanceProposalPreflightService = (
adapters: MaintenanceProposalPreflightAdapters,
@@ -64,35 +61,119 @@ export const createMaintenanceProposalPreflightService = (
checkAction: async (
action: MaintenanceProposalAction,
): Promise<MaintenanceProposalPreflightResult> => {
- if (action.actionType !== 'refine_skill') {
- return { allowed: false, reason: 'unsupported' };
+ if (action.actionType === 'refine_skill') {
+ return checkRefineSkillAction(action, adapters);
}
- const targetId = action.target?.skillDocumentId;
- if (!targetId || !action.baseSnapshot) {
- return { allowed: false, reason: 'target_deleted' };
+ if (action.actionType === 'create_skill') {
+ return checkCreateSkillAction(action, adapters);
}
- const current = await adapters.readSkillTarget(targetId);
- if (!current) {
- return { allowed: false, reason: 'target_deleted' };
- }
+ return { allowed: false, reason: 'unsupported' };
+ },
+});
- if (!current.writable || !current.managed) {
- return { allowed: false, reason: 'target_not_writable' };
- }
+const hasRequiredString = (value: unknown): value is string =>
+ typeof value === 'string' && value.trim().length > 0;
- if (action.baseSnapshot.documentId && current.documentId !== action.baseSnapshot.documentId) {
- return { allowed: false, reason: 'target_type_changed' };
- }
+const getOperationInputString = (action: MaintenanceProposalAction, key: string) => {
+ const input = action.operation?.input;
- if (
- action.baseSnapshot.contentHash &&
- current.contentHash !== action.baseSnapshot.contentHash
- ) {
- return { allowed: false, reason: 'document_changed' };
- }
+ if (!input || typeof input !== 'object' || !(key in input)) return;
- return { allowed: true };
- },
-});
+ const record = input as unknown as Record<string, unknown>;
+ const value = record[key];
+
+ return hasRequiredString(value) ? value.trim() : undefined;
+};
+
+const isCompleteRefineSnapshot = (
+ snapshot: MaintenanceProposalBaseSnapshot,
+): snapshot is MaintenanceProposalBaseSnapshot & {
+ agentDocumentId: string;
+ contentHash: string;
+ documentId: string;
+} =>
+ snapshot.targetType === 'skill' &&
+ hasRequiredString(snapshot.agentDocumentId) &&
+ hasRequiredString(snapshot.contentHash) &&
+ hasRequiredString(snapshot.documentId) &&
+ snapshot.managed === true &&
+ snapshot.writable === true;
+
+const checkRefineSkillAction = async (
+ action: MaintenanceProposalAction,
+ adapters: MaintenanceProposalPreflightAdapters,
+): Promise<MaintenanceProposalPreflightResult> => {
+ const { baseSnapshot } = action;
+ if (!baseSnapshot) return { allowed: false, reason: 'snapshot_missing' };
+ if (!isCompleteRefineSnapshot(baseSnapshot)) {
+ return { allowed: false, reason: 'snapshot_incomplete' };
+ }
+
+ if (
+ action.target?.skillDocumentId &&
+ action.target.skillDocumentId !== baseSnapshot.agentDocumentId
+ ) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ const operationSkillDocumentId = getOperationInputString(action, 'skillDocumentId');
+ if (operationSkillDocumentId && operationSkillDocumentId !== baseSnapshot.agentDocumentId) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ const current = await adapters.readSkillTargetSnapshot(baseSnapshot.agentDocumentId);
+ if (!current) return { allowed: false, reason: 'target_deleted' };
+
+ if (current.managed !== true) return { allowed: false, reason: 'target_unmanaged' };
+ if (current.writable !== true) return { allowed: false, reason: 'target_not_writable' };
+
+ if (current.agentDocumentId && current.agentDocumentId !== baseSnapshot.agentDocumentId) {
+ return { allowed: false, reason: 'document_changed' };
+ }
+
+ if (current.documentId !== baseSnapshot.documentId) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ if (current.contentHash !== baseSnapshot.contentHash) {
+ return { allowed: false, reason: 'content_changed' };
+ }
+
+ return { allowed: true };
+};
+
+const checkCreateSkillAction = async (
+ action: MaintenanceProposalAction,
+ adapters: MaintenanceProposalPreflightAdapters,
+): Promise<MaintenanceProposalPreflightResult> => {
+ const { baseSnapshot } = action;
+ if (!baseSnapshot) return { allowed: false, reason: 'snapshot_missing' };
+ if (
+ baseSnapshot.targetType !== 'skill' ||
+ baseSnapshot.absent !== true ||
+ !hasRequiredString(baseSnapshot.skillName)
+ ) {
+ return { allowed: false, reason: 'snapshot_incomplete' };
+ }
+
+ const skillName = baseSnapshot.skillName.trim();
+
+ if (action.target?.skillName && action.target.skillName !== skillName) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ const operationName = getOperationInputString(action, 'name');
+ if (operationName && operationName !== skillName) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ const available = await adapters.isSkillNameAvailable({
+ agentId: getOperationInputString(action, 'agentId'),
+ name: skillName,
+ userId: getOperationInputString(action, 'userId'),
+ });
+
+ return available ? { allowed: true } : { allowed: false, reason: 'target_conflict' };
+};
diff --git a/src/server/services/agentSignal/services/maintenance/proposalSnapshot.ts b/src/server/services/agentSignal/services/maintenance/proposalSnapshot.ts
new file mode 100644
index 00000000000..462ece0a558
--- /dev/null
+++ b/src/server/services/agentSignal/services/maintenance/proposalSnapshot.ts
@@ -0,0 +1,112 @@
+import type { MaintenanceProposalBaseSnapshot } from './proposal';
+
+/** Persistence adapters required to capture approve-time proposal target snapshots. */
+export interface MaintenanceProposalSnapshotAdapters {
+ /** Checks whether a stable skill name is still available for the agent and user. */
+ isSkillNameAvailable: (input: {
+ /** Agent that will own the created skill. */
+ agentId: string;
+ /** Stable skill name requested by the proposal action. */
+ name: string;
+ /** User that owns the agent. */
+ userId: string;
+ }) => Promise<boolean>;
+ /** Reads the current managed skill target snapshot by agent document id. */
+ readSkillTargetSnapshot: (
+ skillDocumentId: string,
+ ) => Promise<Omit<MaintenanceProposalBaseSnapshot, 'targetType'> | undefined>;
+}
+
+/** Input for capturing a complete proposal base snapshot before merge/apply. */
+export interface CaptureMaintenanceProposalSnapshotInput {
+ /** Mergeable proposal action type to snapshot. */
+ actionType: 'create_skill' | 'refine_skill';
+ /** Agent that owns the target skill namespace. */
+ agentId: string;
+ /** Frozen action input from the proposal operation. */
+ input: Record<string, unknown>;
+ /** User that owns the target agent. */
+ userId: string;
+}
+
+const getRequiredStringInput = (
+ input: Record<string, unknown>,
+ key: string,
+ errorMessage: string,
+) => {
+ const value = input[key];
+
+ if (typeof value === 'string' && value.trim().length > 0) return value.trim();
+
+ throw new Error(errorMessage);
+};
+
+const getOptionalStringInput = (input: Record<string, unknown>, key: string) => {
+ const value = input[key];
+
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+};
+
+const requireCompleteRefineSkillSnapshot = (
+ snapshot: Omit<MaintenanceProposalBaseSnapshot, 'targetType'> | undefined,
+): Omit<MaintenanceProposalBaseSnapshot, 'targetType'> => {
+ if (!snapshot) throw new Error('Skill target snapshot is required');
+
+ if (!snapshot.agentDocumentId) throw new Error('Skill target agentDocumentId is required');
+ if (!snapshot.documentId) throw new Error('Skill target documentId is required');
+ if (!snapshot.contentHash) throw new Error('Skill target contentHash is required');
+ if (!snapshot.managed) throw new Error('Skill target must be managed');
+ if (!snapshot.writable) throw new Error('Skill target must be writable');
+
+ return snapshot;
+};
+
+/**
+ * Creates the approve-time proposal snapshot service.
+ *
+ * Use when:
+ * - Proposal approval needs to freeze the current merge base before mutation
+ * - Skill creation proposals need to reserve an absent target contract
+ *
+ * Expects:
+ * - `refine_skill` input includes a managed skill `skillDocumentId`
+ * - `create_skill` input includes a stable skill `name`
+ *
+ * Returns:
+ * - A service that captures complete skill target snapshots for mergeable proposal actions
+ */
+export const createMaintenanceProposalSnapshotService = (
+ adapters: MaintenanceProposalSnapshotAdapters,
+) => ({
+ captureActionSnapshot: async ({
+ actionType,
+ agentId,
+ input,
+ userId,
+ }: CaptureMaintenanceProposalSnapshotInput): Promise<MaintenanceProposalBaseSnapshot> => {
+ if (actionType === 'refine_skill') {
+ const skillDocumentId = getRequiredStringInput(
+ input,
+ 'skillDocumentId',
+ 'skillDocumentId is required',
+ );
+ const snapshot = requireCompleteRefineSkillSnapshot(
+ await adapters.readSkillTargetSnapshot(skillDocumentId),
+ );
+
+ return { ...snapshot, targetType: 'skill' };
+ }
+
+ const name = getRequiredStringInput(input, 'name', 'Skill name is required');
+ const available = await adapters.isSkillNameAvailable({ agentId, name, userId });
+
+ if (!available) throw new Error('Skill name is already taken');
+
+ return {
+ absent: true,
+ skillName: name,
+ targetTitle: getOptionalStringInput(input, 'title') ?? name,
+ targetType: 'skill',
+ };
+ },
+});
diff --git a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts b/src/server/services/agentSignal/services/maintenance/serverRuntime.ts
index 6c98100a554..353dcdba705 100644
--- a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts
+++ b/src/server/services/agentSignal/services/maintenance/serverRuntime.ts
@@ -9,6 +9,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 { BriefItem } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
@@ -31,8 +32,10 @@ import { redisPolicyStateStore } from '../../store/adapters/redis/policyStateSto
import { redisSourceEventStore } from '../../store/adapters/redis/sourceEventStore';
import { persistAgentSignalReceipts } from '../receiptService';
import { createSelfReflectionService } from '../selfReflection';
+import { runMaintenanceToolFirstRuntime } from './agent';
import { createMaintenanceAgentRunner } from './agentRunner';
-import { createServerMaintenanceBriefWriter } from './brief';
+import { createBriefMaintenanceService, createServerMaintenanceBriefWriter } from './brief';
+import { projectMaintenanceToolRuntimeRun } from './briefProjection';
import { createMaintenanceExecutorService } from './executor';
import { createMemoryMaintenanceService } from './memory';
import type {
@@ -48,8 +51,27 @@ import type {
import { createNightlyReviewService } from './nightlyCollector';
import { mapNightlyDocumentActivityRows } from './nightlyDocumentActivity';
import { createMaintenancePlannerService } from './planner';
-import { getMaintenanceProposalFromBriefMetadata } from './proposal';
+import type { MaintenanceProposalAction, MaintenanceProposalMetadata } from './proposal';
+import {
+ getMaintenanceProposalFromBriefMetadata,
+ refreshMaintenanceProposal,
+ supersedeMaintenanceProposal,
+} from './proposal';
+import { createMaintenanceProposalPreflightService } from './proposalPreflight';
+import { createMaintenanceProposalSnapshotService } from './proposalSnapshot';
import { createSkillManagementService } from './skill';
+import type {
+ CloseMaintenanceProposalInput,
+ CreateMaintenanceProposalInput,
+ CreateSkillIfAbsentInput,
+ MaintenanceToolOperationReservation,
+ MaintenanceToolReceiptInput,
+ MaintenanceToolWriteResult,
+ RefreshMaintenanceProposalInput,
+ ReplaceSkillContentCASInput,
+ SupersedeMaintenanceProposalInput,
+ WriteMemoryInput,
+} from './tools';
import { createMaintenanceTools } from './tools';
import type {
EvidenceRef,
@@ -58,6 +80,7 @@ import type {
MaintenanceActionTarget,
MaintenancePlanDraft,
} from './types';
+import { MaintenanceReviewScope, MaintenanceRisk } from './types';
// NOTICE:
// This schema is intentionally hand-authored for `generateObject` structured output.
@@ -732,6 +755,709 @@ export const listServerProposalActivity = async ({
},
);
+const NIGHTLY_REVIEW_SOURCE_TYPE = 'agent.nightly_review.requested';
+const MAINTENANCE_OPERATION_STATE_TTL_SECONDS = AGENT_SIGNAL_DEFAULTS.receiptTtlSeconds;
+
+const maintenanceOperationScopeKey = (idempotencyKey: string) =>
+ `maintenance-operation:${idempotencyKey}`;
+
+const maintenanceOperationReserveKey = (idempotencyKey: string) =>
+ `maintenance-operation-reserve:${idempotencyKey}`;
+
+const parseStoredOperationResult = (
+ payload: Record<string, string> | undefined,
+): MaintenanceToolWriteResult | undefined => {
+ if (!payload?.result) return;
+
+ try {
+ const result = JSON.parse(payload.result) as MaintenanceToolWriteResult;
+
+ if (
+ result.status === 'applied' ||
+ result.status === 'deduped' ||
+ result.status === 'failed' ||
+ result.status === 'proposed' ||
+ result.status === 'skipped_stale' ||
+ result.status === 'skipped_unsupported'
+ ) {
+ return result;
+ }
+ } catch {
+ return;
+ }
+};
+
+const createSkippedOperationResult = (): MaintenanceToolWriteResult => ({
+ status: 'skipped_unsupported',
+ summary:
+ 'Maintenance operation is already reserved or Redis is unavailable; skipped to avoid duplicate mutation.',
+});
+
+const reserveMaintenanceOperation = async (
+ idempotencyKey: string,
+): Promise<MaintenanceToolOperationReservation> => {
+ const scopeKey = maintenanceOperationScopeKey(idempotencyKey);
+ const existing = parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey));
+
+ if (existing) return { existing, reserved: false };
+
+ // NOTICE:
+ // Redis is the only available cross-worker idempotency boundary for nightly tool writes.
+ // `tryDedupe` also returns false when the Redis client is unavailable, so the safe fallback is
+ // to skip mutation instead of writing without a durable reservation.
+ // Source/context: `src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts`.
+ // Removal condition: replace with a database-backed maintenance operation ledger.
+ const reserved = await redisSourceEventStore.tryDedupe(
+ maintenanceOperationReserveKey(idempotencyKey),
+ MAINTENANCE_OPERATION_STATE_TTL_SECONDS,
+ );
+
+ if (reserved) return { reserved: true };
+
+ return {
+ existing:
+ parseStoredOperationResult(await redisSourceEventStore.readWindow(scopeKey)) ??
+ createSkippedOperationResult(),
+ reserved: false,
+ };
+};
+
+const completeMaintenanceOperation = async (input: MaintenanceToolReceiptInput) => {
+ await redisSourceEventStore.writeWindow(
+ maintenanceOperationScopeKey(input.idempotencyKey),
+ {
+ result: JSON.stringify({
+ ...(input.receiptId ? { receiptId: input.receiptId } : {}),
+ ...(input.resourceId ? { resourceId: input.resourceId } : {}),
+ status: input.status,
+ ...(input.summary ? { summary: input.summary } : {}),
+ } satisfies MaintenanceToolWriteResult),
+ },
+ MAINTENANCE_OPERATION_STATE_TTL_SECONDS,
+ );
+};
+
+const getToolReceiptStatus = (
+ status: MaintenanceToolReceiptInput['status'],
+): 'applied' | 'failed' | 'proposed' | 'skipped' => {
+ if (status === 'applied') return 'applied';
+ if (status === 'failed') return 'failed';
+ if (status === 'proposed') return 'proposed';
+
+ return 'skipped';
+};
+
+const writeMaintenanceToolReceipt = async ({
+ agentId,
+ input,
+ sourceId,
+ userId,
+}: {
+ agentId: string;
+ input: MaintenanceToolReceiptInput;
+ sourceId: string;
+ userId: string;
+}) => {
+ await persistAgentSignalReceipts([
+ {
+ agentId,
+ createdAt: Date.now(),
+ detail: input.summary ?? `Maintenance tool ${input.toolName} finished with ${input.status}.`,
+ id: input.idempotencyKey,
+ kind:
+ input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS'
+ ? 'skill'
+ : 'maintenance',
+ metadata: {
+ sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,
+ },
+ sourceId,
+ sourceType: NIGHTLY_REVIEW_SOURCE_TYPE,
+ status: getToolReceiptStatus(input.status),
+ ...(input.resourceId &&
+ (input.toolName === 'createSkillIfAbsent' || input.toolName === 'replaceSkillContentCAS')
+ ? {
+ target: {
+ id: input.resourceId,
+ ...(input.summary ? { summary: input.summary } : {}),
+ title: input.summary ?? input.resourceId,
+ type: 'skill',
+ },
+ }
+ : {}),
+ title: input.summary ?? 'Maintenance tool outcome',
+ topicId: sourceId,
+ userId,
+ },
+ ]);
+
+ return { receiptId: input.idempotencyKey };
+};
+
+const createSkillProposalAction = (input: CreateSkillIfAbsentInput): MaintenanceProposalAction => ({
+ actionType: 'create_skill',
+ baseSnapshot: {
+ absent: true,
+ skillName: input.name,
+ targetType: 'skill',
+ },
+ evidenceRefs: [],
+ idempotencyKey: input.idempotencyKey,
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: input.bodyMarkdown,
+ description: input.description,
+ name: input.name,
+ title: input.title,
+ userId: input.userId,
+ },
+ operation: 'create',
+ },
+ rationale: input.summary ?? `Create managed skill ${input.name}.`,
+ risk: MaintenanceRisk.Low,
+ target: { skillName: input.name },
+});
+
+const createRefineProposalAction = (
+ input: ReplaceSkillContentCASInput,
+): MaintenanceProposalAction => ({
+ actionType: 'refine_skill',
+ baseSnapshot: input.baseSnapshot,
+ evidenceRefs: [],
+ idempotencyKey: input.idempotencyKey,
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: input.bodyMarkdown,
+ patch: input.summary,
+ skillDocumentId: input.skillDocumentId,
+ userId: input.userId,
+ },
+ operation: 'refine',
+ },
+ rationale: input.summary ?? `Refine managed skill ${input.skillDocumentId}.`,
+ risk: MaintenanceRisk.Low,
+ target: { skillDocumentId: input.skillDocumentId },
+});
+
+const getBriefMetadataWithProposal = (
+ brief: BriefItem,
+ proposal: MaintenanceProposalMetadata,
+): BriefItem['metadata'] => {
+ const metadata = getRecord(brief.metadata);
+ const agentSignal = getRecord(metadata.agentSignal);
+ const nightlySelfReview = getRecord(agentSignal.nightlySelfReview);
+
+ return {
+ ...metadata,
+ agentSignal: {
+ ...agentSignal,
+ nightlySelfReview: {
+ ...nightlySelfReview,
+ maintenanceProposal: proposal,
+ },
+ },
+ };
+};
+
+const getProposalToolCallPayload = (
+ toolName: string,
+ input:
+ | CreateMaintenanceProposalInput
+ | RefreshMaintenanceProposalInput
+ | SupersedeMaintenanceProposalInput,
+) => ({
+ apiName: toolName,
+ arguments: JSON.stringify(input),
+ id: `${input.idempotencyKey}:tool-call`,
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin' as const,
+});
+
+const collectPlanEvidenceRefs = (
+ plan: ReturnType<typeof projectMaintenanceToolRuntimeRun>['projectionPlan'],
+) => {
+ const evidenceRefs = new Map<string, EvidenceRef>();
+
+ for (const action of plan.actions) {
+ for (const evidenceRef of action.evidenceRefs) {
+ evidenceRefs.set(`${evidenceRef.type}:${evidenceRef.id}`, evidenceRef);
+ }
+ }
+
+ return [...evidenceRefs.values()];
+};
+
+const getRecord = (value: unknown): Record<string, unknown> =>
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+
+const getString = (value: unknown) =>
+ typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+
+const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {
+ const operation = getRecord(action.operation);
+ const operationInput = getRecord(operation.input);
+ const target = getRecord(action.target);
+
+ return {
+ ...operationInput,
+ name: getString(operationInput.name) ?? getString(target.skillName),
+ skillDocumentId: getString(operationInput.skillDocumentId) ?? getString(target.skillDocumentId),
+ title: getString(operationInput.title) ?? getString(target.skillName),
+ };
+};
+
+const withCompleteProposalSnapshots = async ({
+ agentId,
+ input,
+ snapshotService,
+ userId,
+}: {
+ agentId: string;
+ input: CreateMaintenanceProposalInput;
+ snapshotService: ReturnType<typeof createMaintenanceProposalSnapshotService>;
+ userId: string;
+}): Promise<CreateMaintenanceProposalInput> => {
+ if (!input.actions || input.actions.length === 0) {
+ throw new Error('Maintenance proposal requires at least one action.');
+ }
+
+ const actions = await Promise.all(
+ input.actions.map(async (rawAction) => {
+ const action = getRecord(rawAction);
+ const actionType = action.actionType;
+
+ if (actionType !== 'create_skill' && actionType !== 'refine_skill') return rawAction;
+
+ return {
+ ...action,
+ baseSnapshot: await snapshotService.captureActionSnapshot({
+ actionType,
+ agentId,
+ input: getProposalActionSnapshotInput(action),
+ userId,
+ }),
+ };
+ }),
+ );
+
+ return { ...input, actions };
+};
+
+const isCompleteRefineToolSnapshot = (
+ snapshot: ReplaceSkillContentCASInput['baseSnapshot'],
+): snapshot is NonNullable<ReplaceSkillContentCASInput['baseSnapshot']> & {
+ agentDocumentId: string;
+ contentHash: string;
+ documentId: string;
+} =>
+ snapshot?.targetType === 'skill' &&
+ typeof snapshot.agentDocumentId === 'string' &&
+ snapshot.agentDocumentId.trim().length > 0 &&
+ typeof snapshot.contentHash === 'string' &&
+ snapshot.contentHash.trim().length > 0 &&
+ typeof snapshot.documentId === 'string' &&
+ snapshot.documentId.trim().length > 0 &&
+ snapshot.managed === true &&
+ snapshot.writable === true;
+
+const withCompleteReplaceSkillSnapshot = async ({
+ agentId,
+ input,
+ snapshotService,
+ userId,
+}: {
+ agentId: string;
+ input: ReplaceSkillContentCASInput;
+ snapshotService: ReturnType<typeof createMaintenanceProposalSnapshotService>;
+ userId: string;
+}): Promise<ReplaceSkillContentCASInput> => {
+ if (isCompleteRefineToolSnapshot(input.baseSnapshot)) return input;
+
+ const baseSnapshot = await snapshotService.captureActionSnapshot({
+ actionType: 'refine_skill',
+ agentId,
+ input: {
+ skillDocumentId: input.skillDocumentId,
+ },
+ userId,
+ });
+
+ return {
+ ...input,
+ baseSnapshot,
+ // NOTICE:
+ // `replaceSkillContentCAS` can be called with either the managed skill bundle id or its
+ // SKILL.md index agent document id. Snapshot capture resolves both to the bundle id, and
+ // approve-time preflight compares the action target against that resolved bundle id.
+ // Without normalizing here, a valid index-targeted write is reported as target drift
+ // (`target_type_changed`) even though it points to the same managed skill.
+ // Removal condition: remove only if preflight natively accepts equivalent bundle/index ids.
+ skillDocumentId: baseSnapshot.agentDocumentId ?? input.skillDocumentId,
+ };
+};
+
+const createProposalProjectionFromToolInput = ({
+ input,
+ localDate,
+ sourceId,
+ toolName,
+ userId,
+}: {
+ input: CreateMaintenanceProposalInput;
+ localDate: string;
+ sourceId: string;
+ toolName: 'createMaintenanceProposal';
+ userId: string;
+}) =>
+ projectMaintenanceToolRuntimeRun({
+ content: input.summary,
+ localDate,
+ outcomes: [
+ {
+ receiptId: input.idempotencyKey,
+ status: 'proposed',
+ summary: input.summary,
+ toolName,
+ },
+ ],
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId,
+ toolCalls: [getProposalToolCallPayload(toolName, input)],
+ userId,
+ });
+
+const findMaintenanceProposalBrief = async ({
+ agentId,
+ briefModel,
+ proposalId,
+ proposalKey,
+}: {
+ agentId: string;
+ briefModel: ProposalBriefReader;
+ proposalId?: string;
+ proposalKey?: string;
+}) => {
+ const rows = await briefModel.listUnresolvedByAgentAndTrigger({
+ agentId,
+ limit: NIGHTLY_PROPOSAL_ACTIVITY_LIMIT,
+ trigger: NIGHTLY_REVIEW_BRIEF_TRIGGER,
+ });
+
+ return rows.find((row) => {
+ if (proposalId && row.id === proposalId) return true;
+
+ const proposal = getMaintenanceProposalFromBriefMetadata(row.metadata);
+
+ return proposalKey ? proposal?.proposalKey === proposalKey : false;
+ });
+};
+
+const updateMaintenanceProposalBrief = async ({
+ agentId,
+ briefModel,
+ proposalId,
+ proposalKey,
+ updateProposal,
+}: {
+ agentId: string;
+ briefModel: BriefModel;
+ proposalId?: string;
+ proposalKey?: string;
+ updateProposal: (proposal: MaintenanceProposalMetadata) => MaintenanceProposalMetadata;
+}) => {
+ const brief = await findMaintenanceProposalBrief({
+ agentId,
+ briefModel,
+ proposalId,
+ proposalKey,
+ });
+
+ if (!brief) throw new Error('Maintenance proposal not found');
+
+ const existingProposal = getMaintenanceProposalFromBriefMetadata(brief.metadata);
+ if (!existingProposal) throw new Error('Maintenance proposal metadata not found');
+
+ const updatedProposal = updateProposal(existingProposal);
+ const updatedBrief = await briefModel.updateMetadata(
+ brief.id,
+ getBriefMetadataWithProposal(brief, updatedProposal),
+ );
+
+ return {
+ resourceId: updatedBrief?.id ?? brief.id,
+ summary: `Updated maintenance proposal ${updatedProposal.proposalKey}.`,
+ };
+};
+
+const createServerMaintenanceToolset = ({
+ agentId,
+ briefModel,
+ context,
+ db,
+ localDate,
+ proposalBriefWriter,
+ skillDocumentService,
+ sourceId,
+ userId,
+}: {
+ agentId: string;
+ briefModel: BriefModel;
+ context: NightlyReviewContext;
+ db: LobeChatDatabase;
+ localDate: string;
+ proposalBriefWriter: ReturnType<typeof createServerMaintenanceBriefWriter>;
+ skillDocumentService: SkillManagementDocumentService;
+ sourceId: string;
+ userId: string;
+}) => {
+ const proposalPreflight = createMaintenanceProposalPreflightService({
+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
+
+ return !skills.some((skill) => skill.name === name);
+ },
+ readSkillTargetSnapshot: (skillDocumentId) =>
+ skillDocumentService.readSkillTargetSnapshot({
+ agentDocumentId: skillDocumentId,
+ agentId,
+ }),
+ });
+ const proposalSnapshot = createMaintenanceProposalSnapshotService({
+ isSkillNameAvailable: async ({ agentId: targetAgentId, name }) => {
+ const skills = await skillDocumentService.listSkills({ agentId: targetAgentId ?? agentId });
+
+ return !skills.some((skill) => skill.name === name);
+ },
+ readSkillTargetSnapshot: (skillDocumentId) =>
+ skillDocumentService.readSkillTargetSnapshot({
+ agentDocumentId: skillDocumentId,
+ agentId,
+ }),
+ });
+
+ return createMaintenanceTools({
+ closeProposal: async (input: CloseMaintenanceProposalInput) =>
+ updateMaintenanceProposalBrief({
+ agentId,
+ briefModel,
+ proposalId: input.proposalId,
+ proposalKey: input.proposalKey,
+ updateProposal: (proposal) => ({
+ ...proposal,
+ status: 'dismissed',
+ updatedAt: new Date().toISOString(),
+ }),
+ }),
+ completeOperation: completeMaintenanceOperation,
+ completeReplaceSkillInput: (input) =>
+ withCompleteReplaceSkillSnapshot({
+ agentId,
+ input,
+ snapshotService: proposalSnapshot,
+ userId,
+ }),
+ createProposal: async (input) => {
+ const projectionInput = await withCompleteProposalSnapshots({
+ agentId,
+ input,
+ snapshotService: proposalSnapshot,
+ userId,
+ });
+ const projection = createProposalProjectionFromToolInput({
+ input: projectionInput,
+ localDate,
+ sourceId,
+ toolName: 'createMaintenanceProposal',
+ userId,
+ });
+ const brief = createBriefMaintenanceService().projectNightlyReviewBrief({
+ agentId,
+ evidenceRefs: collectPlanEvidenceRefs(projection.projectionPlan),
+ localDate,
+ plan: projection.projectionPlan,
+ result: projection.execution,
+ reviewWindowEnd: context.reviewWindowEnd,
+ reviewWindowStart: context.reviewWindowStart,
+ timezone: 'UTC',
+ userId,
+ });
+
+ if (!brief) throw new Error('Maintenance proposal projection produced no brief');
+
+ const result = await proposalBriefWriter.writeDailyBrief(brief);
+
+ return {
+ proposalId: result?.id,
+ resourceId: result?.id,
+ summary: input.summary ?? 'Created maintenance proposal.',
+ };
+ },
+ createSkill: async (input) => {
+ const preflight = await proposalPreflight.checkAction(createSkillProposalAction(input));
+ if (!preflight.allowed) {
+ throw new Error(`Skill creation preflight failed: ${preflight.reason}`);
+ }
+
+ const result = await skillDocumentService.createSkill({
+ agentId,
+ bodyMarkdown: input.bodyMarkdown,
+ description: input.description ?? 'Agent Signal managed skill.',
+ name: input.name,
+ title: input.title ?? input.name,
+ });
+
+ return {
+ resourceId: result.bundle.agentDocumentId,
+ summary: `Created managed skill ${result.name}.`,
+ };
+ },
+ writeMemory: async (input: WriteMemoryInput) => {
+ // TODO: Harden the real writeMemory E2E path. Local QStash verification showed this
+ // tool reaches the memory action agent, but the agent does not always converge to an
+ // applied receipt/brief. Keep this marker until the memory auto-apply case has a
+ // deterministic eval plus a passing end-to-end run.
+ const memoryService = createMemoryMaintenanceService({
+ writeMemory: async ({ content, evidenceRefs, idempotencyKey }) => {
+ const result = await runMemoryActionAgent(
+ {
+ agentId,
+ message: content,
+ reason: `Agent Signal maintenance memory candidate from ${evidenceRefs.length} evidence refs.`,
+ },
+ {
+ db,
+ userId,
+ },
+ );
+
+ if (result.status !== 'applied') {
+ throw new Error(
+ result.detail ?? 'Memory action agent did not apply a durable memory write.',
+ );
+ }
+
+ return {
+ memoryId: idempotencyKey,
+ summary: result.detail ?? content,
+ };
+ },
+ });
+ const result = await memoryService.writeMemory({
+ evidenceRefs: input.evidenceRefs,
+ idempotencyKey: input.idempotencyKey,
+ input: {
+ content: input.content,
+ userId: input.userId,
+ },
+ });
+
+ return {
+ resourceId: result.memoryId,
+ summary: result.summary,
+ };
+ },
+ getEvidenceDigest: async ({ evidenceIds }) => {
+ const selectedEvidenceIds = new Set(evidenceIds ?? []);
+ const includeAll = selectedEvidenceIds.size === 0;
+
+ return {
+ documentActivity: context.documentActivity,
+ proposalActivity: context.proposalActivity,
+ receiptActivity: context.receiptActivity,
+ toolActivity: context.toolActivity,
+ topics: includeAll
+ ? context.topics
+ : context.topics.filter((topic) =>
+ topic.evidenceRefs.some((ref) => selectedEvidenceIds.has(ref.id)),
+ ),
+ };
+ },
+ getManagedSkill: ({ agentId: targetAgentId, skillDocumentId }) =>
+ skillDocumentService.getSkill({
+ agentDocumentId: skillDocumentId,
+ agentId: targetAgentId,
+ includeContent: true,
+ }),
+ listMaintenanceProposals: ({ agentId: targetAgentId }) =>
+ listServerProposalActivity({
+ agentId: targetAgentId,
+ briefModel,
+ userId,
+ }).then((digest) => [digest]),
+ listManagedSkills: ({ agentId: targetAgentId }) =>
+ skillDocumentService.listSkills({ agentId: targetAgentId }),
+ preflight: async (input) => {
+ if ('skillDocumentId' in input) {
+ const result = await proposalPreflight.checkAction(createRefineProposalAction(input));
+
+ return result.allowed ? { allowed: true } : { allowed: false, reason: result.reason };
+ }
+
+ return { allowed: true };
+ },
+ readProposal: async ({ proposalId, proposalKey }) => {
+ const digest = await listServerProposalActivity({
+ agentId,
+ briefModel,
+ userId,
+ });
+
+ return digest.active.find(
+ (proposal) =>
+ (proposalId && proposal.proposalId === proposalId) ||
+ (proposalKey && proposal.proposalKey === proposalKey),
+ );
+ },
+ refreshProposal: async (input: RefreshMaintenanceProposalInput) =>
+ updateMaintenanceProposalBrief({
+ agentId,
+ briefModel,
+ proposalId: input.proposalId,
+ proposalKey: input.proposalKey,
+ updateProposal: (proposal) =>
+ refreshMaintenanceProposal({
+ existing: proposal,
+ incoming: proposal,
+ now: new Date().toISOString(),
+ }),
+ }),
+ replaceSkill: async (input) => {
+ const result = await skillDocumentService.replaceSkillIndex({
+ agentDocumentId: input.skillDocumentId,
+ agentId,
+ bodyMarkdown: input.bodyMarkdown,
+ description: input.description,
+ });
+
+ if (!result) throw new Error('Skill target not found');
+
+ return {
+ resourceId: result.bundle.agentDocumentId,
+ summary: `Refined managed skill ${result.name}.`,
+ };
+ },
+ reserveOperation: reserveMaintenanceOperation,
+ supersedeProposal: async (input: SupersedeMaintenanceProposalInput) =>
+ updateMaintenanceProposalBrief({
+ agentId,
+ briefModel,
+ proposalId: input.proposalId,
+ proposalKey: input.proposalKey,
+ updateProposal: (proposal) =>
+ supersedeMaintenanceProposal({
+ existing: proposal,
+ now: new Date().toISOString(),
+ supersededBy: input.supersededBy,
+ }),
+ }),
+ writeReceipt: (input) => writeMaintenanceToolReceipt({ agentId, input, sourceId, userId }),
+ });
+};
+
/**
* Creates server runtime handlers for the self-reflection source handler.
*
@@ -925,7 +1651,6 @@ export const createServerNightlyReviewPolicyOptions = ({
selfIterationEnabled = false,
userId,
}: CreateServerMaintenancePolicyOptions): CreateNightlyReviewSourceHandlerDependencies => {
- const planner = createMaintenancePlannerService();
const nightlyReviewModel = new AgentSignalNightlyReviewModel(db);
const reviewContextModel = new AgentSignalReviewContextModel(db, userId);
const briefModel = new BriefModel(db, userId);
@@ -1133,37 +1858,6 @@ export const createServerNightlyReviewPolicyOptions = ({
}));
},
});
- const executor = createServerMaintenanceExecutor({
- agentId,
- db,
- 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 {
@@ -1189,13 +1883,64 @@ export const createServerNightlyReviewPolicyOptions = ({
return targets.length > 0;
},
collectContext: (input) => collector.collectNightlyReviewContext(input),
- runMaintenanceReviewAgent: ({ context, localDate, sourceId, userId: runnerUserId }) =>
- maintenanceAgentRunner.run({
+ runMaintenanceReviewAgent: async ({ context, localDate, sourceId, userId: runnerUserId }) => {
+ const modelRuntime = await initModelRuntimeFromDB(
+ db,
+ runnerUserId,
+ DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
+ );
+ const maintenanceTools = createServerMaintenanceToolset({
+ agentId: context.agentId,
+ briefModel,
+ context,
+ db,
+ localDate: localDate ?? context.reviewWindowEnd.slice(0, 10),
+ proposalBriefWriter: briefWriter,
+ skillDocumentService,
+ sourceId,
+ userId: runnerUserId,
+ });
+ const maintenanceAgentRunner = createMaintenanceAgentRunner({
+ maxSteps: 10,
+ run: async ({ context, localDate, maxSteps, reviewScope, sourceId, tools, userId }) => {
+ const runtimeResult = await runMaintenanceToolFirstRuntime({
+ agentId: context.agentId,
+ context,
+ maxSteps,
+ model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,
+ modelRuntime,
+ sourceId,
+ tools,
+ userId,
+ });
+ const projected = projectMaintenanceToolRuntimeRun({
+ content: runtimeResult.content,
+ localDate,
+ outcomes: runtimeResult.writeOutcomes.map((outcome) => ({
+ ...outcome.result,
+ toolName: outcome.toolName,
+ })),
+ reviewScope,
+ sourceId,
+ toolCalls: runtimeResult.toolCalls,
+ userId,
+ });
+
+ return {
+ ...projected,
+ stepCount: runtimeResult.stepCount,
+ };
+ },
+ tools: maintenanceTools,
+ });
+
+ return 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/tools.ts b/src/server/services/agentSignal/services/maintenance/tools.ts
index ec4c645ff4e..d1e37eacec4 100644
--- a/src/server/services/agentSignal/services/maintenance/tools.ts
+++ b/src/server/services/agentSignal/services/maintenance/tools.ts
@@ -1,6 +1,9 @@
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
+import type { MaintenanceProposalBaseSnapshot } from './proposal';
+import type { EvidenceRef } from './types';
+
/** Terminal status emitted by safe maintenance write tools. */
export type MaintenanceToolWriteStatus =
| 'applied'
@@ -55,6 +58,8 @@ export interface MaintenanceToolWriteInput {
/** Input for replacing one managed skill using compare-and-swap safety checks. */
export interface ReplaceSkillContentCASInput extends MaintenanceToolWriteInput {
+ /** Complete target snapshot captured when the proposal was created. */
+ baseSnapshot?: MaintenanceProposalBaseSnapshot;
/** Replacement skill body. */
bodyMarkdown: string;
/** Optional replacement description. */
@@ -66,15 +71,59 @@ export interface ReplaceSkillContentCASInput extends MaintenanceToolWriteInput {
/** Input for creating one skill when no existing skill has been selected. */
export interface CreateSkillIfAbsentInput extends MaintenanceToolWriteInput {
/** Skill body or authoring payload. */
- bodyMarkdown?: string;
+ bodyMarkdown: string;
/** Optional skill description. */
description?: string;
/** Stable skill name. */
- name?: string;
+ name: string;
/** Optional skill title. */
title?: string;
}
+/** Input for writing one durable memory candidate from explicit nightly evidence. */
+export interface WriteMemoryInput extends MaintenanceToolWriteInput {
+ /** Candidate durable memory content. */
+ content: string;
+ /** Evidence supporting this memory write. */
+ evidenceRefs: EvidenceRef[];
+}
+
+/** Input for listing managed skills in one agent scope. */
+export interface ListManagedSkillsInput {
+ /** Agent whose managed skills are visible to the tool call. */
+ agentId: string;
+ /** User that owns the read operation. */
+ userId: string;
+}
+
+/** Input for reading one managed skill in one agent scope. */
+export interface GetManagedSkillInput extends ListManagedSkillsInput {
+ /** Existing managed skill document id. */
+ skillDocumentId: string;
+}
+
+/** Input for listing maintenance proposals in one agent scope. */
+export interface ListMaintenanceProposalsInput {
+ /** Agent whose proposals are visible to the tool call. */
+ agentId: string;
+ /** User that owns the read operation. */
+ userId: string;
+}
+
+/** Input for reading an evidence digest in one agent scope. */
+export interface GetEvidenceDigestInput {
+ /** Agent whose evidence is visible to the tool call. */
+ agentId: string;
+ /** Optional bounded evidence ids selected by the caller. */
+ evidenceIds?: string[];
+ /** Optional inclusive review window end timestamp. */
+ reviewWindowEnd?: string;
+ /** Optional inclusive review window start timestamp. */
+ reviewWindowStart?: string;
+ /** User that owns the read operation. */
+ userId: string;
+}
+
/** Input for creating one user-visible maintenance proposal. */
export interface CreateMaintenanceProposalInput extends MaintenanceToolWriteInput {
/** Proposal action payload retained by the injected proposal adapter. */
@@ -174,12 +223,24 @@ export interface MaintenanceToolsAdapters {
* mutation or leave reservations stuck in an in-progress state.
*/
completeOperation?: (input: MaintenanceToolOperationLifecycleInput) => Promise<void>;
+ /** Completes server-owned CAS metadata before validating an existing skill replacement. */
+ completeReplaceSkillInput?: (
+ input: ReplaceSkillContentCASInput,
+ ) => Promise<ReplaceSkillContentCASInput>;
/** Creates one user-visible maintenance proposal. */
createProposal?: (
input: CreateMaintenanceProposalInput,
) => Promise<MaintenanceToolMutationResult & { proposalId?: string }>;
/** Creates one managed skill. */
createSkill?: (input: CreateSkillIfAbsentInput) => Promise<MaintenanceToolMutationResult>;
+ /** Reads a bounded evidence digest for maintenance planning. */
+ getEvidenceDigest?: (input: GetEvidenceDigestInput) => Promise<unknown | undefined>;
+ /** Reads one managed skill in the requested agent scope. */
+ getManagedSkill?: (input: GetManagedSkillInput) => Promise<unknown | undefined>;
+ /** Lists maintenance proposals in the requested agent scope. */
+ listMaintenanceProposals?: (input: ListMaintenanceProposalsInput) => Promise<unknown[]>;
+ /** Lists managed skills in the requested agent scope. */
+ listManagedSkills?: (input: ListManagedSkillsInput) => Promise<unknown[]>;
/**
* Marks or releases a reserved operation when its terminal receipt cannot be persisted.
*
@@ -214,6 +275,8 @@ export interface MaintenanceToolsAdapters {
supersedeProposal?: (
input: SupersedeMaintenanceProposalInput,
) => Promise<MaintenanceToolMutationResult>;
+ /** Writes one durable memory candidate. */
+ writeMemory?: (input: WriteMemoryInput) => Promise<MaintenanceToolMutationResult>;
/** Writes the audit receipt for a terminal maintenance tool status. */
writeReceipt: (input: MaintenanceToolReceiptInput) => Promise<MaintenanceToolReceiptResult>;
}
@@ -245,6 +308,30 @@ const errorSummary = (error: unknown) =>
const getErrorMessage = (error: unknown) =>
error instanceof Error ? error.message : String(error);
+const hasNonBlankString = (value: unknown): value is string =>
+ typeof value === 'string' && value.trim().length > 0;
+
+const isCompleteRefineBaseSnapshot = (
+ snapshot: unknown,
+): snapshot is MaintenanceProposalBaseSnapshot & {
+ agentDocumentId: string;
+ contentHash: string;
+ documentId: string;
+} => {
+ if (!snapshot || typeof snapshot !== 'object') return false;
+
+ const record = snapshot as Record<string, unknown>;
+
+ return (
+ record.targetType === 'skill' &&
+ hasNonBlankString(record.agentDocumentId) &&
+ hasNonBlankString(record.documentId) &&
+ hasNonBlankString(record.contentHash) &&
+ record.managed === true &&
+ record.writable === true
+ );
+};
+
const getResultWithReceipt = async (
adapters: MaintenanceToolsAdapters,
input: MaintenanceToolWriteInput,
@@ -342,6 +429,7 @@ const runWriteTool = async <TInput extends MaintenanceToolWriteInput>({
successStatus,
toolName,
unsupportedSummary,
+ validate,
}: {
adapters: MaintenanceToolsAdapters;
input: TInput;
@@ -355,6 +443,7 @@ const runWriteTool = async <TInput extends MaintenanceToolWriteInput>({
>;
toolName: string;
unsupportedSummary: string;
+ validate?: () => MaintenanceToolWriteResult | undefined;
}) => {
return withWriteSpan(toolName, input, async (recordConvertedException) => {
let operationReserved = false;
@@ -372,6 +461,9 @@ const runWriteTool = async <TInput extends MaintenanceToolWriteInput>({
operationReserved = true;
+ const validationResult = validate?.();
+ if (validationResult) return validationResult;
+
if (!mutate) {
return {
resourceId,
@@ -502,6 +594,49 @@ export const createMaintenanceTools = (adapters: MaintenanceToolsAdapters) => ({
successStatus: 'applied',
toolName: 'createSkillIfAbsent',
unsupportedSummary: 'Skill creation is not supported.',
+ validate: () => {
+ if (hasNonBlankString(input.name) && hasNonBlankString(input.bodyMarkdown)) {
+ return undefined;
+ }
+
+ return {
+ status: 'skipped_unsupported',
+ summary: 'Skill creation requires a non-empty name and body.',
+ };
+ },
+ }),
+ writeMemory: async (input: WriteMemoryInput) =>
+ runWriteTool({
+ adapters,
+ input,
+ mutate: adapters.writeMemory ? () => adapters.writeMemory!(input) : undefined,
+ successStatus: 'applied',
+ toolName: 'writeMemory',
+ unsupportedSummary: 'Memory writing is not supported.',
+ }),
+ getEvidenceDigest: async (input: GetEvidenceDigestInput) =>
+ withReadSpan('getEvidenceDigest', undefined, async () => {
+ if (!adapters.getEvidenceDigest) return undefined;
+
+ return adapters.getEvidenceDigest(input);
+ }),
+ getManagedSkill: async (input: GetManagedSkillInput) =>
+ withReadSpan('getManagedSkill', undefined, async () => {
+ if (!adapters.getManagedSkill) return undefined;
+
+ return adapters.getManagedSkill(input);
+ }),
+ listMaintenanceProposals: async (input: ListMaintenanceProposalsInput) =>
+ withReadSpan('listMaintenanceProposals', undefined, async () => {
+ if (!adapters.listMaintenanceProposals) return [];
+
+ return adapters.listMaintenanceProposals(input);
+ }),
+ listManagedSkills: async (input: ListManagedSkillsInput) =>
+ withReadSpan('listManagedSkills', undefined, async () => {
+ if (!adapters.listManagedSkills) return [];
+
+ return adapters.listManagedSkills(input);
}),
readMaintenanceProposal: async (input: {
proposalId?: string;
@@ -525,18 +660,40 @@ export const createMaintenanceTools = (adapters: MaintenanceToolsAdapters) => ({
toolName: 'refreshMaintenanceProposal',
unsupportedSummary: 'Maintenance proposal refresh is not supported.',
}),
- replaceSkillContentCAS: async (input: ReplaceSkillContentCASInput) =>
- runWriteTool({
+ replaceSkillContentCAS: async (input: ReplaceSkillContentCASInput) => {
+ const enrichedInput = adapters.completeReplaceSkillInput
+ ? await adapters.completeReplaceSkillInput(input)
+ : input;
+
+ return runWriteTool({
adapters,
- input,
- mutate: adapters.replaceSkill ? () => adapters.replaceSkill!(input) : undefined,
- preflight: adapters.preflight ? () => adapters.preflight!(input) : undefined,
+ input: enrichedInput,
+ mutate: adapters.replaceSkill ? () => adapters.replaceSkill!(enrichedInput) : undefined,
+ preflight: adapters.preflight ? () => adapters.preflight!(enrichedInput) : undefined,
preflightRequired: true,
- resourceId: input.skillDocumentId,
+ resourceId: enrichedInput.skillDocumentId,
successStatus: 'applied',
toolName: 'replaceSkillContentCAS',
unsupportedSummary: 'Skill replacement is not supported.',
- }),
+ validate: () => {
+ if (!hasNonBlankString(enrichedInput.bodyMarkdown)) {
+ return {
+ resourceId: enrichedInput.skillDocumentId,
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a non-empty body.',
+ };
+ }
+
+ if (isCompleteRefineBaseSnapshot(enrichedInput.baseSnapshot)) return undefined;
+
+ return {
+ resourceId: enrichedInput.skillDocumentId,
+ status: 'skipped_unsupported',
+ summary: 'Skill replacement requires a complete base snapshot.',
+ };
+ },
+ });
+ },
supersedeMaintenanceProposal: async (input: SupersedeMaintenanceProposalInput) =>
runWriteTool({
adapters,
diff --git a/src/server/services/brief/index.test.ts b/src/server/services/brief/index.test.ts
index aad73e47903..491664288e4 100644
--- a/src/server/services/brief/index.test.ts
+++ b/src/server/services/brief/index.test.ts
@@ -5,7 +5,6 @@ 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';
@@ -395,107 +394,6 @@ 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.ts
index a73445d0438..b06b9ad53c2 100644
--- a/src/server/services/brief/index.ts
+++ b/src/server/services/brief/index.ts
@@ -5,9 +5,6 @@ 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;
@@ -25,198 +22,28 @@ 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 BriefResolveOptions {
+ /** User action selected from a Daily Brief card. */
+ action?: string;
+ /** Optional user comment attached to the resolution. */
+ comment?: string;
}
-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, options: BriefServiceOptions = {}) {
+ constructor(db: LobeChatDatabase, userId: string) {
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
@@ -367,20 +194,7 @@ export class BriefService {
* recurring task — which leaves the task in `scheduled` between runs — is
* handled the same way.
*/
- async resolve(
- 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,
- });
- }
-
+ async resolve(id: string, options?: BriefResolveOptions): Promise<BriefItem | null> {
const brief = await this.briefModel.resolve(id, options);
if (!brief) return null;