Skip to content

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

✨ feat(agent-signal,server,prompts): consolidate in self-review implemented (#14657)

Neko79ed4b5faf97
diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts
index e77616248ef..1ec58e2cf4e 100644
--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts
+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.test.ts
@@ -24,7 +24,7 @@ describe('agent signal nightly review prompt', () => {
'A durable_user_preference signal means',
);
expect(AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE).toContain(
- 'Consolidation should stay proposal_only',
+ 'Consolidation must be proposed with a frozen consolidate_skill operation',
);
});
diff --git a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts
index 0e0f2b692f3..9fc4d653a84 100644
--- a/packages/prompts/src/prompts/agentSignal/nightlyReview.ts
+++ b/packages/prompts/src/prompts/agentSignal/nightlyReview.ts
@@ -5,7 +5,7 @@ const TOOL_FIRST_MAINTENANCE_RULES = [
'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.',
+ 'Proposal only: structural/destructive changes, active proposal refresh/supersede/close, deletion, move, rebind, split, merge, path/namespace/file-structure/activation changes. Use proposal_only only for non-actionable ideas or questions that should be retained, not applied.',
].join(' ');
export const AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE = [
@@ -29,7 +29,7 @@ export const AGENT_SIGNAL_NIGHTLY_REVIEW_SYSTEM_ROLE = [
'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.',
+ '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 must be proposed with a frozen consolidate_skill operation and must not be auto-applied.',
].join(' ');
/**
diff --git a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts
index 0ccd4a418f5..7954132da1b 100644
--- a/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts
+++ b/src/server/services/agentSignal/policies/reviewNightly/nightlyReview.ts
@@ -517,6 +517,7 @@ export const createNightlyReviewSourceHandler = (
const brief = createBriefMaintenanceService().projectNightlyReviewBrief({
agentId: payload.agentId,
evidenceRefs: collectPlanEvidenceRefs(plan),
+ ideas: agentResult.ideas,
localDate: payload.localDate,
...(proposalPlan ? { plan: proposalPlan } : {}),
result: executionWithReceipts,
diff --git a/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts b/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts
index 9c79e26098a..7b8a852c79e 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/briefProjection.test.ts
@@ -65,9 +65,9 @@ describe('projectMaintenanceToolOutcomes', () => {
/**
* @example
- * Created, refreshed, or superseded proposal tool outcomes ask Daily Brief for a decision.
+ * Proposal lifecycle tool outcomes stay silent because they mutate proposal state, not resources.
*/
- it('projects proposal lifecycle outcomes to decision metadata with proposal count', () => {
+ it('keeps proposal lifecycle outcomes out of resource decision metadata', () => {
const projection = projectMaintenanceToolOutcomes({
outcomes: [
{
@@ -94,12 +94,12 @@ describe('projectMaintenanceToolOutcomes', () => {
],
});
- expect(projection.briefKind).toBe('decision');
- expect(projection.proposalCount).toBe(3);
+ expect(projection.briefKind).toBe('none');
+ expect(projection.proposalCount).toBe(0);
expect(projection.actionCounts).toEqual({
applied: 0,
failed: 0,
- proposed: 3,
+ proposed: 0,
skipped: 0,
});
expect(projection.receiptIds).toEqual([
@@ -180,6 +180,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {
it('preserves proposed create skill actions from proposal lifecycle tool arguments', () => {
const projection = projectMaintenanceToolRuntimeRun({
content: 'Created a proposal.',
+ includeProposalLifecycleActions: true,
localDate: '2026-05-09',
outcomes: [
{
@@ -366,15 +367,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {
});
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.actions).toEqual([]);
expect(projection.execution.status).toBe(ReviewRunStatus.Skipped);
});
@@ -393,6 +386,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {
toolName: 'createMaintenanceProposal',
},
],
+ includeProposalLifecycleActions: true,
reviewScope: MaintenanceReviewScope.Nightly,
sourceId: 'source-1',
toolCalls: [
@@ -413,15 +407,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {
});
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.actions).toEqual([]);
expect(projection.execution.status).toBe(ReviewRunStatus.Skipped);
});
@@ -440,6 +426,7 @@ describe('projectMaintenanceToolRuntimeRun', () => {
toolName: 'createMaintenanceProposal',
},
],
+ includeProposalLifecycleActions: true,
reviewScope: MaintenanceReviewScope.Nightly,
sourceId: 'source-1',
toolCalls: [
@@ -503,4 +490,163 @@ describe('projectMaintenanceToolRuntimeRun', () => {
target: { skillDocumentId: 'skill-doc-1' },
});
});
+
+ /**
+ * @example
+ * proposal_only actions are retained as ideas, not approve-time proposal actions.
+ */
+ it('extracts proposal-only actions as self-review ideas', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ outcomes: [
+ {
+ receiptId: 'receipt-create-proposal',
+ resourceId: 'brief-proposal-1',
+ status: 'proposed',
+ summary: 'Saved maintenance ideas.',
+ toolName: 'createMaintenanceProposal',
+ },
+ ],
+ includeProposalLifecycleActions: true,
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify({
+ actions: [
+ {
+ actionType: 'proposal_only',
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'idea-1',
+ rationale: 'The skill layout may need a future split.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'skill-doc-1' },
+ title: 'Consider splitting review skill',
+ },
+ ],
+ idempotencyKey: 'proposal-op-1',
+ proposalKey: 'agent-1:proposal_only:agent_document:skill-doc-1',
+ summary: 'Saved maintenance ideas.',
+ }),
+ id: 'call-create-proposal-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.projectionPlan.actions).toEqual([]);
+ expect(projection.ideas).toEqual([
+ {
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ idempotencyKey: 'idea-1',
+ rationale: 'The skill layout may need a future split.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'skill-doc-1' },
+ title: 'Consider splitting review skill',
+ },
+ ]);
+ });
+
+ /**
+ * @example
+ * consolidate_skill proposal actions keep their frozen skill operation payload.
+ */
+ it('preserves consolidate skill proposal operations for approve-time apply', () => {
+ const projection = projectMaintenanceToolRuntimeRun({
+ outcomes: [
+ {
+ receiptId: 'receipt-create-proposal',
+ resourceId: 'brief-proposal-1',
+ status: 'proposed',
+ summary: 'Review consolidated skill.',
+ toolName: 'createMaintenanceProposal',
+ },
+ ],
+ includeProposalLifecycleActions: true,
+ reviewScope: MaintenanceReviewScope.Nightly,
+ sourceId: 'source-1',
+ toolCalls: [
+ {
+ apiName: 'createMaintenanceProposal',
+ arguments: JSON.stringify({
+ actions: [
+ {
+ actionType: 'consolidate_skill',
+ applyMode: MaintenanceApplyMode.ProposalOnly,
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'hash-canonical',
+ documentId: 'doc-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ evidenceRefs: [{ id: 'topic-1', type: 'topic' }],
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: '# Review Skill\n\nUse one consolidated checklist.',
+ canonicalSkillDocumentId: 'skill-doc-1',
+ sourceSkillIds: ['skill-doc-1', 'skill-doc-2'],
+ sourceSnapshots: [
+ {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'hash-canonical',
+ documentId: 'doc-1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ {
+ agentDocumentId: 'skill-doc-2',
+ contentHash: 'hash-source',
+ documentId: 'doc-2',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
+ ],
+ userId: 'user-1',
+ },
+ operation: 'consolidate',
+ },
+ rationale: 'Two review skills overlap.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'skill-doc-1' },
+ },
+ ],
+ idempotencyKey: 'proposal-op-1',
+ proposalKey: 'agent-1:consolidate_skill:agent_document:skill-doc-1',
+ summary: 'Review consolidated skill.',
+ }),
+ id: 'call-create-proposal-1',
+ identifier: 'agent-signal-maintenance',
+ type: 'builtin',
+ },
+ ],
+ userId: 'user-1',
+ });
+
+ expect(projection.projectionPlan.actions[0]).toMatchObject({
+ actionType: 'consolidate_skill',
+ baseSnapshot: {
+ agentDocumentId: 'skill-doc-1',
+ contentHash: 'hash-canonical',
+ },
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: '# Review Skill\n\nUse one consolidated checklist.',
+ canonicalSkillDocumentId: 'skill-doc-1',
+ sourceSkillIds: ['skill-doc-1', 'skill-doc-2'],
+ },
+ operation: 'consolidate',
+ },
+ });
+ expect(projection.execution.actions[0]).toMatchObject({
+ status: MaintenanceActionStatus.Proposed,
+ });
+ });
});
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 0dcc00170f4..1d20527828d 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalApply.test.ts
@@ -287,13 +287,17 @@ describe('maintenance proposal apply service', () => {
/**
* @example
- * expect(result.proposal.applyAttempts?.[0].actionResults[0].status).toBe('skipped_unsupported');
+ * expect(tools.replaceSkillContentCAS).toHaveBeenCalledWith(expect.objectContaining({ skillDocumentId: 'adoc_1' }));
*/
- it('records unsupported actions without applying them', async () => {
+ it('applies fresh consolidate_skill proposal actions through canonical skill replacement', async () => {
const createSkillIfAbsent = vi.fn();
- const replaceSkillContentCAS = vi.fn();
+ const replaceSkillContentCAS = vi.fn().mockResolvedValue({
+ resourceId: 'adoc_1',
+ status: 'applied',
+ summary: 'Consolidated managed skill.',
+ });
const service = createMaintenanceProposalApplyService({
- checkAction: vi.fn().mockResolvedValue({ allowed: false, reason: 'unsupported' }),
+ checkAction: vi.fn().mockResolvedValue({ allowed: true }),
checkGates: vi.fn().mockResolvedValue({ allowed: true }),
now: () => '2026-05-09T01:00:00.000Z',
tools: {
@@ -310,13 +314,32 @@ describe('maintenance proposal apply service', () => {
actions: [
{
actionType: 'consolidate_skill',
+ baseSnapshot: {
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ },
evidenceRefs: [],
idempotencyKey: 'nightly:consolidate_skill:adoc_1',
+ operation: {
+ domain: 'skill',
+ input: {
+ bodyMarkdown: 'merged body',
+ canonicalSkillDocumentId: 'adoc_1',
+ sourceSkillIds: ['adoc_1', 'adoc_2'],
+ userId: 'user_1',
+ },
+ operation: 'consolidate',
+ },
rationale: 'Merge overlapping skills.',
risk: MaintenanceRisk.High,
target: { skillDocumentId: 'adoc_1' },
},
],
+ proposalKey: 'agt_1:consolidate_skill:agent_document:adoc_1',
}),
sourceId: 'nightly-review:user_1:agt_1:2026-05-09',
sourceType: 'agent.nightly_review.requested',
@@ -324,13 +347,23 @@ describe('maintenance proposal apply service', () => {
});
expect(createSkillIfAbsent).not.toHaveBeenCalled();
- expect(replaceSkillContentCAS).not.toHaveBeenCalled();
- expect(result.proposal.status).toBe('failed');
+ expect(replaceSkillContentCAS).toHaveBeenCalledWith(
+ expect.objectContaining({
+ bodyMarkdown: 'merged body',
+ idempotencyKey: 'nightly:consolidate_skill:adoc_1',
+ proposalKey: 'agt_1:consolidate_skill:agent_document:adoc_1',
+ skillDocumentId: 'adoc_1',
+ summary: 'Merge overlapping skills.',
+ userId: 'user_1',
+ }),
+ );
+ expect(result.proposal.status).toBe('applied');
expect(result.proposal.applyAttempts?.[0].actionResults).toEqual([
{
idempotencyKey: 'nightly:consolidate_skill:adoc_1',
- status: 'skipped_unsupported',
- summary: 'Proposal action is not supported by approve-time apply.',
+ resourceId: 'adoc_1',
+ status: 'applied',
+ summary: 'Consolidated managed skill.',
},
]);
});
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 fd82e2d408a..4da4df574bf 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/proposalPreflight.test.ts
@@ -52,6 +52,73 @@ const createCreateAction = () => ({
target: { skillName: 'code-review' },
});
+const createConsolidateAction = () => ({
+ actionType: 'consolidate_skill' as const,
+ baseSnapshot: {
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetTitle: 'Review Skill',
+ targetType: 'skill' as const,
+ writable: true,
+ },
+ evidenceRefs: [],
+ idempotencyKey: 'key-consolidate',
+ operation: {
+ domain: 'skill' as const,
+ input: {
+ bodyMarkdown: '# Review Skill\n\nUse one consolidated checklist.',
+ canonicalSkillDocumentId: 'adoc_1',
+ sourceSkillIds: ['adoc_1', 'adoc_2'],
+ sourceSnapshots: [
+ {
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetType: 'skill' as const,
+ writable: true,
+ },
+ {
+ agentDocumentId: 'adoc_2',
+ contentHash: 'sha256:source',
+ documentId: 'doc_2',
+ managed: true,
+ targetType: 'skill' as const,
+ writable: true,
+ },
+ ],
+ userId: 'user_1',
+ },
+ operation: 'consolidate' as const,
+ },
+ rationale: 'Merge overlapping review skills.',
+ risk: MaintenanceRisk.Medium,
+ target: { skillDocumentId: 'adoc_1' },
+});
+
+const createSnapshotReader = () =>
+ vi.fn(async (skillDocumentId: string) =>
+ skillDocumentId === 'adoc_2'
+ ? {
+ agentDocumentId: 'adoc_2',
+ contentHash: 'sha256:source',
+ documentId: 'doc_2',
+ managed: true,
+ targetTitle: 'Review Checklist',
+ writable: true,
+ }
+ : {
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ targetTitle: 'Review Skill',
+ writable: true,
+ },
+ );
+
const createAdapters = (
overrides: Partial<MaintenanceProposalPreflightAdapters> = {},
): MaintenanceProposalPreflightAdapters => ({
@@ -314,6 +381,55 @@ describe('maintenance proposal preflight', () => {
});
});
+ /**
+ * @example
+ * expect(result.allowed).toBe(true);
+ */
+ it('allows consolidate_skill proposals when canonical and source snapshots are fresh', async () => {
+ const readSkillTargetSnapshot = createSnapshotReader();
+ const service = createMaintenanceProposalPreflightService(
+ createAdapters({ readSkillTargetSnapshot }),
+ );
+
+ await expect(service.checkAction(createConsolidateAction())).resolves.toEqual({
+ allowed: true,
+ });
+ expect(readSkillTargetSnapshot).toHaveBeenCalledWith('adoc_1');
+ expect(readSkillTargetSnapshot).toHaveBeenCalledWith('adoc_2');
+ });
+
+ /**
+ * @example
+ * expect(result.reason).toBe('content_changed');
+ */
+ it('rejects consolidate_skill proposals when a source snapshot changed', async () => {
+ const service = createMaintenanceProposalPreflightService(
+ createAdapters({
+ readSkillTargetSnapshot: async (skillDocumentId) =>
+ skillDocumentId === 'adoc_2'
+ ? {
+ agentDocumentId: 'adoc_2',
+ contentHash: 'sha256:changed',
+ documentId: 'doc_2',
+ managed: true,
+ writable: true,
+ }
+ : {
+ agentDocumentId: 'adoc_1',
+ contentHash: 'sha256:base',
+ documentId: 'doc_1',
+ managed: true,
+ writable: true,
+ },
+ }),
+ );
+
+ await expect(service.checkAction(createConsolidateAction())).resolves.toEqual({
+ allowed: false,
+ reason: 'content_changed',
+ });
+ });
+
/**
* @example
* expect(result.reason).toBe('unsupported');
@@ -322,9 +438,7 @@ describe('maintenance proposal preflight', () => {
const service = createMaintenanceProposalPreflightService(createAdapters());
const action = createRefineAction();
- await expect(
- service.checkAction({ ...action, actionType: 'consolidate_skill' }),
- ).resolves.toEqual({
+ await expect(service.checkAction({ ...action, actionType: 'proposal_only' })).resolves.toEqual({
allowed: false,
reason: 'unsupported',
});
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 fd4b374047e..1721695301f 100644
--- a/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts
+++ b/src/server/services/agentSignal/services/maintenance/__tests__/serverRuntime.test.ts
@@ -613,18 +613,8 @@ describe('createServerNightlyReviewPolicyOptions', () => {
},
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',
- },
- });
+ expect(result.execution.actions).toEqual([]);
+ expect(result.projectionPlan.actions).toEqual([]);
});
/**
@@ -748,11 +738,8 @@ describe('createServerNightlyReviewPolicyOptions', () => {
},
type: 'decision',
});
- expect(result.execution.actions[0]).toMatchObject({
- idempotencyKey: 'proposal-op-refine-1',
- resourceId: 'brief-created',
- status: MaintenanceActionStatus.Skipped,
- });
+ expect(result.execution.actions).toEqual([]);
+ expect(result.projectionPlan.actions).toEqual([]);
});
/**
diff --git a/src/server/services/agentSignal/services/maintenance/agent.ts b/src/server/services/agentSignal/services/maintenance/agent.ts
index 629d580f914..3ffd70808b4 100644
--- a/src/server/services/agentSignal/services/maintenance/agent.ts
+++ b/src/server/services/agentSignal/services/maintenance/agent.ts
@@ -301,7 +301,7 @@ const MAINTENANCE_TOOL_FIRST_SYSTEM_ROLE = [
'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 } }.',
+ '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 } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }.',
'Stop after the useful maintenance work is complete and summarize the confirmed outcome.',
].join('\n');
diff --git a/src/server/services/agentSignal/services/maintenance/agentRunner.ts b/src/server/services/agentSignal/services/maintenance/agentRunner.ts
index 9ec4ea89904..11768b49820 100644
--- a/src/server/services/agentSignal/services/maintenance/agentRunner.ts
+++ b/src/server/services/agentSignal/services/maintenance/agentRunner.ts
@@ -2,6 +2,7 @@ import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
import type { NightlyReviewContext } from './nightlyCollector';
+import type { MaintenanceReviewIdea } from './proposal';
import type { MaintenanceTools } from './tools';
import type { MaintenancePlan, MaintenanceReviewRunResult } from './types';
import { MaintenanceReviewScope, ReviewRunStatus } from './types';
@@ -15,6 +16,8 @@ const DEFAULT_MAX_MAINTENANCE_AGENT_STEPS = 10;
export interface MaintenanceAgentRunResult {
/** Executed tool or legacy executor result to persist as receipts. */
execution: MaintenanceReviewRunResult;
+ /** Non-actionable ideas collected during the run. */
+ ideas?: MaintenanceReviewIdea[];
/** Frozen deterministic plan used for Daily Brief proposal projection. */
projectionPlan: MaintenancePlan;
/** Optional number of agent/tool steps consumed by the backend runner. */
diff --git a/src/server/services/agentSignal/services/maintenance/brief.ts b/src/server/services/agentSignal/services/maintenance/brief.ts
index 372f9f43c09..4dd8e5b4bda 100644
--- a/src/server/services/agentSignal/services/maintenance/brief.ts
+++ b/src/server/services/agentSignal/services/maintenance/brief.ts
@@ -1,12 +1,16 @@
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
-import type { BriefMetadata } from '@lobechat/types';
+import type { BriefArtifactDocument, 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, MaintenanceProposalPlan } from './proposal';
+import type {
+ MaintenanceProposalMetadata,
+ MaintenanceProposalPlan,
+ MaintenanceReviewIdea,
+} from './proposal';
import {
AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS,
buildMaintenanceProposalFromPlan,
@@ -38,12 +42,14 @@ export interface MaintenanceBriefMetadata {
actionCounts: MaintenanceBriefActionCounts;
/** Evidence refs retained from reviewer/planner context for audit drilldown. */
evidenceRefs: EvidenceRef[];
+ /** Non-actionable self-review ideas retained without entering approve-time apply. */
+ ideas?: MaintenanceReviewIdea[];
/** 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';
+ outcome: 'applied' | 'error' | 'ideas' | 'proposal';
/** Durable receipt ids linked to this brief. */
receiptIds: string[];
/** Review source id that produced this brief. */
@@ -128,6 +134,7 @@ const createNightlySelfReviewBriefMetadata = ({
nightlySelfReview: {
actionCounts,
evidenceRefs,
+ ...(input.ideas?.length ? { ideas: input.ideas } : {}),
localDate: input.localDate,
outcome,
...(proposal ? { maintenanceProposal: proposal } : {}),
@@ -241,6 +248,8 @@ export interface ProjectNightlyReviewBriefInput {
agentId: string;
/** Evidence refs retained from the review or source handler. */
evidenceRefs?: EvidenceRef[];
+ /** Non-actionable self-review ideas collected during the run. */
+ ideas?: MaintenanceReviewIdea[];
/** User-local date reviewed by the nightly run. */
localDate: string;
/** Frozen maintenance plan used to preserve proposal actions. */
@@ -337,10 +346,12 @@ const getReceiptIds = (result: MaintenanceReviewRunResult) => [
const getOutcome = (
result: MaintenanceReviewRunResult,
counts: MaintenanceBriefActionCounts,
+ ideas: MaintenanceReviewIdea[] = [],
): MaintenanceBriefMetadata['outcome'] | undefined => {
if (counts.proposed > 0) return 'proposal';
if (counts.applied > 0) return 'applied';
if (counts.failed > 0 || result.status === ReviewRunStatus.Failed) return 'error';
+ if (ideas.length > 0) return 'ideas';
return;
};
@@ -378,6 +389,49 @@ const createDetailedSummary = (
return details ? `${summary}\n\n${details}` : summary;
};
+const collectBriefArtifactDocuments = ({
+ ideas = [],
+ proposal,
+}: {
+ ideas?: MaintenanceReviewIdea[];
+ proposal?: MaintenanceProposalMetadata;
+}): BriefArtifactDocument[] => {
+ const documents = new Map<string, BriefArtifactDocument>();
+
+ for (const action of proposal?.actions ?? []) {
+ const id = action.target?.skillDocumentId ?? action.baseSnapshot?.agentDocumentId;
+ if (!id) continue;
+
+ documents.set(id, {
+ id,
+ kind: 'skill',
+ title: action.baseSnapshot?.targetTitle ?? action.target?.skillName ?? action.rationale,
+ });
+ }
+
+ for (const idea of ideas) {
+ const id = idea.target?.skillDocumentId;
+ if (!id) continue;
+
+ documents.set(id, {
+ id,
+ kind: 'skill',
+ title: idea.title ?? idea.target?.skillName ?? idea.rationale,
+ });
+ }
+
+ return [...documents.values()];
+};
+
+const createBriefArtifacts = (input: {
+ ideas?: MaintenanceReviewIdea[];
+ proposal?: MaintenanceProposalMetadata;
+}) => {
+ const documents = collectBriefArtifactDocuments(input);
+
+ return documents.length > 0 ? { documents } : undefined;
+};
+
const createBriefCopy = (
outcome: MaintenanceBriefMetadata['outcome'],
counts: MaintenanceBriefActionCounts,
@@ -412,6 +466,15 @@ const createBriefCopy = (
};
}
+ if (outcome === 'ideas') {
+ return {
+ priority: 'info' as const,
+ summary: 'Agent self-review saved maintenance ideas for future review.',
+ title: 'Agent self-review ideas',
+ type: 'insight' as const,
+ };
+ }
+
const summary = `${counts.applied} maintenance update${counts.applied === 1 ? '' : 's'} applied.`;
return {
@@ -494,7 +557,7 @@ export const createBriefMaintenanceService = () => ({
input: ProjectNightlyReviewBriefInput,
): MaintenanceBriefProjection | undefined => {
const actionCounts = countActions(input.result, input.plan);
- const outcome = getOutcome(input.result, actionCounts);
+ const outcome = getOutcome(input.result, actionCounts, input.ideas);
if (!outcome) return;
@@ -510,10 +573,12 @@ export const createBriefMaintenanceService = () => ({
results: input.result.actions,
})
: undefined;
+ const artifacts = createBriefArtifacts({ ideas: input.ideas, proposal });
return {
...(proposal ? { actions: AGENT_SIGNAL_PROPOSAL_BRIEF_ACTIONS } : {}),
agentId: input.agentId,
+ ...(artifacts ? { artifacts } : {}),
metadata: createNightlySelfReviewBriefMetadata({
actionCounts,
evidenceRefs: input.evidenceRefs ?? [],
diff --git a/src/server/services/agentSignal/services/maintenance/briefProjection.ts b/src/server/services/agentSignal/services/maintenance/briefProjection.ts
index 8bd7aaf26a3..2af98048875 100644
--- a/src/server/services/agentSignal/services/maintenance/briefProjection.ts
+++ b/src/server/services/agentSignal/services/maintenance/briefProjection.ts
@@ -1,6 +1,10 @@
import type { ChatToolPayload } from '@lobechat/types';
-import type { MaintenanceProposalBaseSnapshot, MaintenanceProposalPlan } from './proposal';
+import type {
+ MaintenanceProposalBaseSnapshot,
+ MaintenanceProposalPlan,
+ MaintenanceReviewIdea,
+} from './proposal';
import type { MaintenanceToolWriteResult } from './tools';
import type {
MaintenanceActionPlan,
@@ -35,6 +39,8 @@ export interface ProjectMaintenanceToolOutcomesInput {
export interface ProjectMaintenanceToolRuntimeRunInput extends ProjectMaintenanceToolOutcomesInput {
/** Assistant summary emitted by the tool-first runtime. */
content?: string;
+ /** Whether proposal lifecycle tool calls should project embedded resource actions. */
+ includeProposalLifecycleActions?: boolean;
/** User-local nightly date used in the projected maintenance plan. */
localDate?: string;
/** Review scope attached to the projected maintenance plan. */
@@ -51,6 +57,8 @@ export interface ProjectMaintenanceToolRuntimeRunInput extends ProjectMaintenanc
export interface ProjectedMaintenanceToolRuntimeRun {
/** Executor-shaped result consumed by receipt and brief projection. */
execution: MaintenanceReviewRunResult;
+ /** Non-actionable ideas extracted from proposal-only actions. */
+ ideas: MaintenanceReviewIdea[];
/** Plan-shaped projection consumed by Daily Brief proposal metadata. */
projectionPlan: MaintenanceProposalPlan;
}
@@ -81,6 +89,15 @@ export interface ProjectedMaintenanceToolOutcomes {
receiptIds: string[];
}
+const PROPOSAL_LIFECYCLE_TOOL_NAMES = new Set([
+ 'closeMaintenanceProposal',
+ 'createMaintenanceProposal',
+ 'refreshMaintenanceProposal',
+ 'supersedeMaintenanceProposal',
+]);
+
+const isProposalLifecycleTool = (toolName: string) => PROPOSAL_LIFECYCLE_TOOL_NAMES.has(toolName);
+
/**
* Normalizes one write-tool outcome to bounded brief action metadata.
*
@@ -107,7 +124,7 @@ const projectAction = (outcome: MaintenanceToolOutcome): MaintenanceToolOutcome
*
* Expects:
* - Outcomes are already bounded by write-tool result contracts
- * - Proposal create, refresh, and supersede tools use `proposed` status for visible decisions
+ * - Proposal lifecycle tools are silent resource-wise unless their embedded action payload is projected elsewhere
*
* Returns:
* - Counts, receipt ids, bounded actions, and the selected brief kind
@@ -126,9 +143,11 @@ export const projectMaintenanceToolOutcomes = (
for (const outcome of input.outcomes) {
if (outcome.receiptId !== undefined) receiptIds.push(outcome.receiptId);
+ const isLifecycleOutcome = isProposalLifecycleTool(outcome.toolName);
+
if (outcome.status === 'applied') actionCounts.applied += 1;
if (outcome.status === 'failed') actionCounts.failed += 1;
- if (outcome.status === 'proposed') actionCounts.proposed += 1;
+ if (outcome.status === 'proposed' && !isLifecycleOutcome) actionCounts.proposed += 1;
if (
outcome.status === 'deduped' ||
outcome.status === 'skipped_stale' ||
@@ -138,13 +157,7 @@ export const projectMaintenanceToolOutcomes = (
}
}
- const proposalCount = input.outcomes.filter(
- (outcome) =>
- outcome.status === 'proposed' &&
- (outcome.toolName === 'createMaintenanceProposal' ||
- outcome.toolName === 'refreshMaintenanceProposal' ||
- outcome.toolName === 'supersedeMaintenanceProposal'),
- ).length;
+ const proposalCount = 0;
const hasVisibleRiskOutcome = input.outcomes.some(
(outcome) => outcome.status === 'failed' || outcome.status === 'skipped_stale',
);
@@ -192,6 +205,9 @@ const getString = (value: unknown) =>
const getBoolean = (value: unknown) => (typeof value === 'boolean' ? value : undefined);
+const getStringArray = (value: unknown) =>
+ Array.isArray(value) ? value.flatMap((item) => (getString(item) ? [getString(item)!] : [])) : [];
+
const getRecord = (value: unknown): Record<string, unknown> =>
value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
@@ -215,6 +231,9 @@ const getBaseSnapshot = (value: unknown): MaintenanceProposalBaseSnapshot | unde
};
};
+const getBaseSnapshots = (value: unknown): MaintenanceProposalBaseSnapshot[] =>
+ Array.isArray(value) ? value.flatMap((item) => getBaseSnapshot(item) ?? []) : [];
+
const toActionStatus = (
status: MaintenanceToolWriteResult['status'],
): MaintenanceActionStatusValue => {
@@ -413,6 +432,26 @@ const toSkillOperation = (value: unknown, userId: string): MaintenanceActionPlan
operation: 'refine',
};
}
+
+ if (record.operation === 'consolidate') {
+ const canonicalSkillDocumentId = getString(input.canonicalSkillDocumentId);
+ const sourceSkillIds = getStringArray(input.sourceSkillIds);
+ if (!canonicalSkillDocumentId || sourceSkillIds.length === 0) return;
+
+ return {
+ domain: 'skill',
+ input: {
+ approval: { source: 'proposal' },
+ bodyMarkdown: getString(input.bodyMarkdown),
+ canonicalSkillDocumentId,
+ description: getString(input.description),
+ sourceSkillIds,
+ sourceSnapshots: getBaseSnapshots(input.sourceSnapshots),
+ userId: getString(input.userId) ?? userId,
+ },
+ operation: 'consolidate',
+ };
+ }
};
const getRawActionType = (value: unknown): MaintenanceActionPlan['actionType'] | undefined => {
@@ -487,7 +526,7 @@ const getProjectionActionFromRaw = ({
const idempotencyKey =
getString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:action:${index + 1}`;
- if (!actionType) return;
+ if (!actionType || actionType === 'proposal_only') return;
const operation = toSkillOperation(record.operation, userId);
const target = toTarget(record.target);
@@ -534,32 +573,72 @@ const getProjectionActionFromRaw = ({
};
};
-const getProjectionActionsFromProposalArgs = ({
+const getIdeaFromRaw = ({
+ fallbackIdempotencyKey,
+ index,
+ rawAction,
+}: {
+ fallbackIdempotencyKey: string;
+ index: number;
+ rawAction: unknown;
+}): MaintenanceReviewIdea | undefined => {
+ const record = getRecord(rawAction);
+ if (getRawActionType(record.actionType) !== 'proposal_only') return;
+
+ const target = toTarget(record.target);
+
+ return {
+ evidenceRefs: toEvidenceRefs(record.evidenceRefs),
+ idempotencyKey:
+ getString(record.idempotencyKey) ?? `${fallbackIdempotencyKey}:idea:${index + 1}`,
+ rationale: getString(record.rationale) ?? 'Maintenance self-review idea.',
+ risk: toRisk(record.risk),
+ ...(target ? { target } : {}),
+ ...(getString(record.title) ? { title: getString(record.title) } : {}),
+ };
+};
+
+const getProjectionPayloadFromProposalArgs = ({
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,
- });
+}): { actions: MaintenanceProposalPlan['actions']; ideas: MaintenanceReviewIdea[] } => {
+ const actions: MaintenanceProposalPlan['actions'] = [];
+ const ideas: MaintenanceReviewIdea[] = [];
+
+ if (Array.isArray(args.actions)) {
+ for (const [index, rawAction] of args.actions.entries()) {
+ const idea = getIdeaFromRaw({
+ fallbackIdempotencyKey: idempotencyKey,
+ index,
+ rawAction,
+ });
- return action ? [action] : [];
- })
- : [];
+ if (idea) {
+ ideas.push(idea);
+ continue;
+ }
+
+ const action = getProjectionActionFromRaw({
+ fallbackIdempotencyKey: idempotencyKey,
+ index,
+ outcome,
+ rawAction,
+ userId,
+ });
+
+ if (action) actions.push(action);
+ }
+ }
+
+ return { actions, ideas };
+};
const getProjectionAction = ({
args,
@@ -653,6 +732,7 @@ export const projectMaintenanceToolRuntimeRun = (
input: ProjectMaintenanceToolRuntimeRunInput,
): ProjectedMaintenanceToolRuntimeRun => {
const writeToolCalls = getWriteToolCalls(input.toolCalls);
+ const ideas: MaintenanceReviewIdea[] = [];
const projectionActions: MaintenanceProposalPlan['actions'] = [];
const executionActions: MaintenanceReviewRunResult['actions'] = [];
const toolCallCursors = new Map<string, number>();
@@ -666,28 +746,25 @@ export const projectMaintenanceToolRuntimeRun = (
toolCall,
toolName: outcome.toolName,
});
- const proposalActions =
- outcome.toolName === 'createMaintenanceProposal' ||
- outcome.toolName === 'refreshMaintenanceProposal' ||
- outcome.toolName === 'supersedeMaintenanceProposal'
- ? getProjectionActionsFromProposalArgs({
+ const proposalPayload =
+ input.includeProposalLifecycleActions && isProposalLifecycleTool(outcome.toolName)
+ ? getProjectionPayloadFromProposalArgs({
args,
idempotencyKey,
outcome,
- sourceId: input.sourceId,
userId: input.userId,
})
- : [];
+ : { actions: [], ideas: [] };
- if (
- outcome.toolName === 'createMaintenanceProposal' ||
- outcome.toolName === 'refreshMaintenanceProposal' ||
- outcome.toolName === 'supersedeMaintenanceProposal'
- ) {
- if (proposalActions.length > 0) {
- projectionActions.push(...proposalActions);
+ if (isProposalLifecycleTool(outcome.toolName)) {
+ if (proposalPayload.ideas.length > 0) {
+ ideas.push(...proposalPayload.ideas);
+ }
+
+ if (proposalPayload.actions.length > 0) {
+ projectionActions.push(...proposalPayload.actions);
executionActions.push(
- ...proposalActions.map((action) => ({
+ ...proposalPayload.actions.map((action) => ({
idempotencyKey: action.idempotencyKey,
...(outcome.receiptId ? { receiptId: outcome.receiptId } : {}),
...(outcome.resourceId ? { resourceId: outcome.resourceId } : {}),
@@ -698,15 +775,15 @@ export const projectMaintenanceToolRuntimeRun = (
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.',
- });
+ if (input.includeProposalLifecycleActions && proposalPayload.ideas.length > 0) {
+ executionActions.push({
+ idempotencyKey,
+ ...(outcome.receiptId ? { receiptId: outcome.receiptId } : {}),
+ ...(outcome.resourceId ? { resourceId: outcome.resourceId } : {}),
+ status: MaintenanceActionStatus.Skipped,
+ summary: outcome.summary ?? 'Maintenance proposal created self-review ideas.',
+ });
+ }
continue;
}
@@ -741,5 +818,5 @@ export const projectMaintenanceToolRuntimeRun = (
status: getRunStatus(executionActions),
};
- return { execution, projectionPlan };
+ return { execution, ideas, projectionPlan };
};
diff --git a/src/server/services/agentSignal/services/maintenance/proposal.ts b/src/server/services/agentSignal/services/maintenance/proposal.ts
index 0c5a6a31939..42116673cdd 100644
--- a/src/server/services/agentSignal/services/maintenance/proposal.ts
+++ b/src/server/services/agentSignal/services/maintenance/proposal.ts
@@ -120,6 +120,22 @@ export interface MaintenanceProposalAction {
target?: MaintenanceActionTarget;
}
+/** Non-actionable self-review thought retained for future review without approve-time mutation. */
+export interface MaintenanceReviewIdea {
+ /** Bounded evidence references retained for audit and future review context. */
+ evidenceRefs: EvidenceRef[];
+ /** Stable idempotency key from the proposal-only action. */
+ idempotencyKey: string;
+ /** Reviewer rationale explaining why this is an idea instead of an executable action. */
+ rationale: string;
+ /** Risk assigned by the maintenance reviewer. */
+ risk: MaintenanceRisk;
+ /** Optional target identity the idea is about. */
+ target?: MaintenanceActionTarget;
+ /** Optional short title for UI or digest presentation. */
+ title?: string;
+}
+
/**
* Proposal projection action for mergeable skill mutations.
*
@@ -495,7 +511,10 @@ export const buildMaintenanceProposalFromPlan = ({
.map((result) => result.idempotencyKey),
);
const proposedActions = plan.actions.filter(
- (action) => action.actionType !== 'noop' && proposedResultKeys.has(action.idempotencyKey),
+ (action) =>
+ action.actionType !== 'noop' &&
+ action.actionType !== 'proposal_only' &&
+ proposedResultKeys.has(action.idempotencyKey),
);
if (proposedActions.length === 0) return;
diff --git a/src/server/services/agentSignal/services/maintenance/proposalApply.ts b/src/server/services/agentSignal/services/maintenance/proposalApply.ts
index 6c6cf8f106e..08cda1f2b2f 100644
--- a/src/server/services/agentSignal/services/maintenance/proposalApply.ts
+++ b/src/server/services/agentSignal/services/maintenance/proposalApply.ts
@@ -155,7 +155,47 @@ const prepareToolAction = (
input: ApplyMaintenanceProposalInput,
adapters: MaintenanceProposalApplyAdapters,
): MaintenanceProposalActionApplyResult | PreparedToolAction => {
- if (action.actionType === 'consolidate_skill') return buildUnsupportedResult(action);
+ if (action.actionType === 'consolidate_skill') {
+ if (
+ action.operation?.domain !== 'skill' ||
+ action.operation.operation !== 'consolidate' ||
+ !action.baseSnapshot
+ ) {
+ return toApplyResult(
+ action,
+ 'skipped_unsupported',
+ 'Proposal action is missing an executable operation.',
+ );
+ }
+
+ const operationInput = action.operation.input as unknown as Record<string, unknown>;
+ const bodyMarkdown = getRequiredString(operationInput.bodyMarkdown);
+ const canonicalSkillDocumentId = getRequiredString(operationInput.canonicalSkillDocumentId);
+ const description = getOptionalString(operationInput.description);
+
+ if (!bodyMarkdown || !canonicalSkillDocumentId) {
+ 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: canonicalSkillDocumentId,
+ summary: action.rationale,
+ userId: input.userId,
+ }),
+ };
+ }
if (action.actionType === 'refine_skill') {
if (
diff --git a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts b/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts
index e7cada95b54..5d82bcecfa7 100644
--- a/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts
+++ b/src/server/services/agentSignal/services/maintenance/proposalPreflight.ts
@@ -69,6 +69,10 @@ export const createMaintenanceProposalPreflightService = (
return checkCreateSkillAction(action, adapters);
}
+ if (action.actionType === 'consolidate_skill') {
+ return checkConsolidateSkillAction(action, adapters);
+ }
+
return { allowed: false, reason: 'unsupported' };
},
});
@@ -87,6 +91,34 @@ const getOperationInputString = (action: MaintenanceProposalAction, key: string)
return hasRequiredString(value) ? value.trim() : undefined;
};
+const getOperationInputStringArray = (action: MaintenanceProposalAction, key: string) => {
+ const input = action.operation?.input;
+ if (!input || typeof input !== 'object' || !(key in input)) return [];
+
+ const record = input as unknown as Record<string, unknown>;
+ const value = record[key];
+
+ return Array.isArray(value)
+ ? value.flatMap((item) => (hasRequiredString(item) ? [item.trim()] : []))
+ : [];
+};
+
+const getOperationInputSnapshots = (action: MaintenanceProposalAction, key: string) => {
+ const input = action.operation?.input;
+ if (!input || typeof input !== 'object' || !(key in input)) return [];
+
+ const record = input as unknown as Record<string, unknown>;
+ const value = record[key];
+
+ return Array.isArray(value)
+ ? value.flatMap((item) =>
+ item && typeof item === 'object' && !Array.isArray(item)
+ ? [item as MaintenanceProposalBaseSnapshot]
+ : [],
+ )
+ : [];
+};
+
const isCompleteRefineSnapshot = (
snapshot: MaintenanceProposalBaseSnapshot,
): snapshot is MaintenanceProposalBaseSnapshot & {
@@ -177,3 +209,72 @@ const checkCreateSkillAction = async (
return available ? { allowed: true } : { allowed: false, reason: 'target_conflict' };
};
+
+const checkSnapshotFresh = async (
+ baseSnapshot: MaintenanceProposalBaseSnapshot,
+ adapters: MaintenanceProposalPreflightAdapters,
+): Promise<MaintenanceProposalPreflightResult> => {
+ if (!isCompleteRefineSnapshot(baseSnapshot)) {
+ return { allowed: false, reason: 'snapshot_incomplete' };
+ }
+
+ 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 checkConsolidateSkillAction = async (
+ action: MaintenanceProposalAction,
+ adapters: MaintenanceProposalPreflightAdapters,
+): Promise<MaintenanceProposalPreflightResult> => {
+ if (action.operation?.domain !== 'skill' || action.operation.operation !== 'consolidate') {
+ return { allowed: false, reason: 'unsupported' };
+ }
+
+ const canonicalSkillDocumentId = getOperationInputString(action, 'canonicalSkillDocumentId');
+ const sourceSkillIds = getOperationInputStringArray(action, 'sourceSkillIds');
+ const sourceSnapshots = getOperationInputSnapshots(action, 'sourceSnapshots');
+ const bodyMarkdown = getOperationInputString(action, 'bodyMarkdown');
+
+ if (!canonicalSkillDocumentId || sourceSkillIds.length < 2 || !bodyMarkdown) {
+ return { allowed: false, reason: 'snapshot_incomplete' };
+ }
+
+ if (!action.baseSnapshot) return { allowed: false, reason: 'snapshot_missing' };
+ if (action.baseSnapshot.agentDocumentId !== canonicalSkillDocumentId) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ const canonicalResult = await checkSnapshotFresh(action.baseSnapshot, adapters);
+ if (!canonicalResult.allowed) return canonicalResult;
+
+ if (sourceSnapshots.length !== sourceSkillIds.length) {
+ return { allowed: false, reason: 'snapshot_incomplete' };
+ }
+
+ for (const sourceSnapshot of sourceSnapshots) {
+ if (
+ !sourceSnapshot.agentDocumentId ||
+ !sourceSkillIds.includes(sourceSnapshot.agentDocumentId)
+ ) {
+ return { allowed: false, reason: 'target_type_changed' };
+ }
+
+ const sourceResult = await checkSnapshotFresh(sourceSnapshot, adapters);
+ if (!sourceResult.allowed) return sourceResult;
+ }
+
+ return { allowed: true };
+};
diff --git a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts b/src/server/services/agentSignal/services/maintenance/serverRuntime.ts
index 353dcdba705..59a7bb2796f 100644
--- a/src/server/services/agentSignal/services/maintenance/serverRuntime.ts
+++ b/src/server/services/agentSignal/services/maintenance/serverRuntime.ts
@@ -997,6 +997,9 @@ const getRecord = (value: unknown): Record<string, unknown> =>
const getString = (value: unknown) =>
typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
+const getStringArray = (value: unknown) =>
+ Array.isArray(value) ? value.flatMap((item) => (getString(item) ? [getString(item)!] : [])) : [];
+
const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {
const operation = getRecord(action.operation);
const operationInput = getRecord(operation.input);
@@ -1030,6 +1033,44 @@ const withCompleteProposalSnapshots = async ({
const action = getRecord(rawAction);
const actionType = action.actionType;
+ if (actionType === 'consolidate_skill') {
+ const operation = getRecord(action.operation);
+ const operationInput = getRecord(operation.input);
+ const canonicalSkillDocumentId = getString(operationInput.canonicalSkillDocumentId);
+ const sourceSkillIds = getStringArray(operationInput.sourceSkillIds);
+ const sourceSnapshots = await Promise.all(
+ sourceSkillIds.map((skillDocumentId) =>
+ snapshotService.captureActionSnapshot({
+ actionType: 'refine_skill',
+ agentId,
+ input: { skillDocumentId },
+ userId,
+ }),
+ ),
+ );
+
+ return {
+ ...action,
+ ...(canonicalSkillDocumentId
+ ? {
+ baseSnapshot: await snapshotService.captureActionSnapshot({
+ actionType: 'refine_skill',
+ agentId,
+ input: { skillDocumentId: canonicalSkillDocumentId },
+ userId,
+ }),
+ }
+ : {}),
+ operation: {
+ ...operation,
+ input: {
+ ...operationInput,
+ sourceSnapshots,
+ },
+ },
+ };
+ }
+
if (actionType !== 'create_skill' && actionType !== 'refine_skill') return rawAction;
return {
@@ -1115,6 +1156,7 @@ const createProposalProjectionFromToolInput = ({
}) =>
projectMaintenanceToolRuntimeRun({
content: input.summary,
+ includeProposalLifecycleActions: true,
localDate,
outcomes: [
{
@@ -1277,6 +1319,7 @@ const createServerMaintenanceToolset = ({
const brief = createBriefMaintenanceService().projectNightlyReviewBrief({
agentId,
evidenceRefs: collectPlanEvidenceRefs(projection.projectionPlan),
+ ideas: projection.ideas,
localDate,
plan: projection.projectionPlan,
result: projection.execution,
diff --git a/src/server/services/agentSignal/services/maintenance/skill.ts b/src/server/services/agentSignal/services/maintenance/skill.ts
index 2f32314594f..7c377d931fa 100644
--- a/src/server/services/agentSignal/services/maintenance/skill.ts
+++ b/src/server/services/agentSignal/services/maintenance/skill.ts
@@ -37,10 +37,32 @@ export interface ConsolidateMaintenanceSkillInput extends SkillMaintenanceBaseIn
/** Source of the approval decision. */
source: 'proposal' | 'same_turn_feedback';
};
+ /** Full replacement Markdown body for the canonical skill. */
+ bodyMarkdown?: string;
/** Canonical writable managed skill agent document id. */
canonicalSkillDocumentId: string;
+ /** Optional description to persist with the canonical skill index. */
+ description?: string;
/** Source managed skill ids used to build the canonical skill. */
sourceSkillIds: string[];
+ /** Frozen source snapshots captured when the consolidation was proposed. */
+ sourceSnapshots?: SkillMaintenanceTargetSnapshot[];
+}
+
+/** Frozen managed-skill target state used by approve-time consolidation preflight. */
+export interface SkillMaintenanceTargetSnapshot {
+ /** Managed skill bundle agent document id. */
+ agentDocumentId?: string;
+ /** Content hash observed when the proposal was created. */
+ contentHash?: string;
+ /** Canonical document id observed when the proposal was created. */
+ documentId?: string;
+ /** Whether the target was managed by Agent Signal. */
+ managed?: boolean;
+ /** Target domain captured by the proposal snapshot. */
+ targetType?: 'skill';
+ /** Whether the target was writable at proposal time. */
+ writable?: boolean;
}
/** Request envelope for creating one skill. */