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.

🐛 fix(agent-signal): say what a malformed createSelfReviewProposal actions item holds (#23285)

Lobehub Coder6f7929e7a1a1
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalInput.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalInput.test.ts
new file mode 100644
index 00000000000..529ad6f833e
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/proposalInput.test.ts
@@ -0,0 +1,172 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import type { CreateSelfReviewProposalInput } from '../../tools/shared';
+import { normalizeSelfReviewProposalInput } from '../proposalInput';
+
+const createSkillAction = (name: string) => ({
+ actionType: 'create_skill',
+ operation: {
+ domain: 'skill',
+ input: { bodyMarkdown: `# ${name}`, name, title: name },
+ operation: 'create',
+ },
+ rationale: `Reusable ${name} workflow.`,
+ target: { skillName: name },
+});
+
+const proposalInput = (actions: unknown): CreateSelfReviewProposalInput =>
+ ({
+ actions,
+ idempotencyKey: 'proposal-1',
+ proposalKey: 'skill:proposal-1',
+ summary: 'Proposal summary.',
+ userId: 'user-1',
+ }) as CreateSelfReviewProposalInput;
+
+const errorOf = (run: () => unknown) => {
+ try {
+ run();
+ } catch (error) {
+ return (error as Error).message;
+ }
+
+ throw new Error('expected normalizeSelfReviewProposalInput to throw');
+};
+
+describe('normalizeSelfReviewProposalInput', () => {
+ it.each([1, 2, 3])('keeps all %i valid actions in order', (count) => {
+ const actions = Array.from({ length: count }, (_, index) =>
+ createSkillAction(`skill-${index}`),
+ );
+
+ const result = normalizeSelfReviewProposalInput(proposalInput(actions));
+
+ expect(result.actions).toHaveLength(count);
+ expect(result.actions).toEqual(actions);
+ });
+
+ it('maps `type` and the legacy `record_idea` kind onto actionType', () => {
+ const result = normalizeSelfReviewProposalInput(
+ proposalInput([
+ { target: { skillName: 'a' }, type: 'create_skill' },
+ { rationale: 'Just an idea.', type: 'record_idea' },
+ ]),
+ );
+
+ expect(result.actions).toEqual([
+ { actionType: 'create_skill', target: { skillName: 'a' }, type: 'create_skill' },
+ { actionType: 'proposal_only', rationale: 'Just an idea.', type: 'record_idea' },
+ ]);
+ });
+
+ it('wraps a single action object sent instead of a one-element array', () => {
+ const action = createSkillAction('solo');
+
+ const result = normalizeSelfReviewProposalInput(proposalInput(action));
+
+ expect(result.actions).toEqual([action]);
+ });
+
+ it('decodes actions sent as a JSON-encoded string', () => {
+ const actions = [createSkillAction('a'), createSkillAction('b')];
+
+ expect(
+ normalizeSelfReviewProposalInput(proposalInput(JSON.stringify(actions))).actions,
+ ).toEqual(actions);
+ expect(
+ normalizeSelfReviewProposalInput(proposalInput(JSON.stringify(actions[0]))).actions,
+ ).toEqual([actions[0]]);
+ });
+
+ it('leaves a missing actions field to the at-least-one-action check', () => {
+ const input = proposalInput(undefined);
+
+ expect(normalizeSelfReviewProposalInput(input)).toBe(input);
+ });
+
+ /**
+ * @example
+ * Production shape behind the "phantom actions[1]" vents: the model closed its
+ * one action object early, so the remaining keys spilled into the array as bare
+ * strings and the top-level fields went missing.
+ */
+ it('names the stray value and the missing top-level fields for a spilled single action', () => {
+ const message = errorOf(() =>
+ normalizeSelfReviewProposalInput({
+ actions: [
+ createSkillAction('testing'),
+ 'rationalearization?',
+ 'rationale?',
+ 'evidenceRefs?',
+ 'summary?',
+ 'proposalKey?',
+ 'idempotencyKey?',
+ 'metadata?',
+ ],
+ userId: 'user-1',
+ } as CreateSelfReviewProposalInput),
+ );
+
+ expect(message).toContain('Received actions with 8 item(s) (1 object(s))');
+ expect(message).toContain(
+ 'actions[1] is the string "rationalearization?", not an action object',
+ );
+ expect(message).toContain('actions[5] is the string "proposalKey?"');
+ expect(message).toContain('and 2 more');
+ expect(message).not.toContain('actions[6]');
+ expect(message).toContain('stray values after an action object');
+ expect(message).toContain(
+ 'Top-level fields idempotencyKey, proposalKey, summary are missing; they belong beside actions',
+ );
+ expect(message).not.toContain('actions[0]');
+ });
+
+ it.each([
+ {
+ actions: [{ target: { skillName: 'x' } }],
+ expected: 'actions[0] has no actionType (keys: target)',
+ },
+ {
+ actions: [createSkillAction('a'), { operation: { domain: 'skill' }, rationale: 'r' }],
+ expected: 'actions[1] has no actionType (keys: operation, rationale)',
+ },
+ {
+ actions: [createSkillAction('a'), createSkillAction('b'), { actionType: 'rewrite_skill' }],
+ expected: 'actions[2] has unsupported actionType "rewrite_skill"',
+ },
+ {
+ actions: [createSkillAction('a'), null, createSkillAction('c')],
+ expected: 'actions[1] is null, not an action object',
+ },
+ ])('points at the real index and field: $expected', ({ actions, expected }) => {
+ const message = errorOf(() => normalizeSelfReviewProposalInput(proposalInput(actions)));
+
+ expect(message).toContain(`Received actions with ${actions.length} item(s)`);
+ expect(message).toContain(expected);
+ expect(message).toContain('expected one of: create_skill, refine_skill');
+ expect(message).not.toContain('Top-level fields');
+ });
+
+ it('lists every invalid index, not only the first', () => {
+ const message = errorOf(() =>
+ normalizeSelfReviewProposalInput(
+ proposalInput([{ rationale: 'a' }, createSkillAction('b'), { actionType: 'nope' }]),
+ ),
+ );
+
+ expect(message).toContain('actions[0] has no actionType (keys: rationale)');
+ expect(message).toContain('actions[2] has unsupported actionType "nope"');
+ expect(message).not.toContain('actions[1]');
+ });
+
+ it.each([
+ { actions: 'refine the testing skill', expected: 'the string "refine the testing skill"' },
+ { actions: { skillName: 'x' }, expected: 'an object with keys skillName' },
+ { actions: 3, expected: 'the number 3' },
+ ])('rejects a non-array actions value: $expected', ({ actions, expected }) => {
+ expect(() => normalizeSelfReviewProposalInput(proposalInput(actions))).toThrow(
+ `actions must be an array of action objects, but received ${expected}.`,
+ );
+ });
+});
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
index 6a593a98709..af0878c661a 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
@@ -239,4 +239,138 @@ describe('createReviewRuntimePrimitives', () => {
),
).rejects.toThrow('actions[0] has no actionType');
});
+
+ describe('createSelfReviewProposal action counts', () => {
+ const createProposalService = () => {
+ const writeDailyBrief = vi.fn().mockResolvedValue({ id: 'brief-1' });
+ const service = createReviewRuntimePrimitives({
+ agentId: 'agent-1',
+ briefModel: {} as never,
+ db: {} as unknown as LobeChatDatabase,
+ localDate: '2026-11-17',
+ proposalBriefWriter: { writeDailyBrief } as never,
+ reviewWindowEnd: '2026-11-17T14:00:00.000Z',
+ reviewWindowStart: '2026-11-16T14:00:00.000Z',
+ skillDocumentService: {
+ listSkills: vi.fn().mockResolvedValue([]),
+ readSkillTargetSnapshot: vi.fn().mockResolvedValue({
+ agentDocumentId: 'agd-testing',
+ contentHash: 'hash-1',
+ documentId: 'doc-testing',
+ managed: true,
+ targetType: 'skill',
+ writable: true,
+ }),
+ } as unknown as SkillManagementDocumentService,
+ sourceId: 'nightly-review:user-1:agent-1:2026-11-17',
+ userId: 'user-1',
+ });
+
+ return { service, writeDailyBrief };
+ };
+
+ const createSkillAction = (name: string) => ({
+ actionType: 'create_skill',
+ operation: {
+ domain: 'skill',
+ input: { bodyMarkdown: `# ${name}\n\nSteps...`, description: name, name, title: name },
+ operation: 'create',
+ },
+ rationale: `Repeated ${name} workflow across topics.`,
+ target: { skillName: name },
+ });
+
+ const refineSkillAction = {
+ actionType: 'refine_skill',
+ operation: {
+ domain: 'skill',
+ input: { bodyMarkdown: '# Testing\n\nRun one file.', skillDocumentId: 'agd-testing' },
+ operation: 'refine',
+ },
+ rationale: 'The user corrected the full-suite command twice.',
+ target: { skillDocumentId: 'agd-testing' },
+ };
+
+ const getStoredProposalActions = (writeDailyBrief: ReturnType<typeof vi.fn>) =>
+ writeDailyBrief.mock.calls[0][0].metadata.agentSignal.nightlySelfReview.selfReviewProposal
+ .actions;
+
+ it.each([
+ { actions: [refineSkillAction], label: '1 refine_skill' },
+ { actions: [createSkillAction('release-notes')], label: '1 create_skill' },
+ {
+ actions: [createSkillAction('release-notes'), refineSkillAction],
+ label: '2',
+ },
+ {
+ actions: [createSkillAction('a-skill'), createSkillAction('b-skill'), refineSkillAction],
+ label: '3',
+ },
+ ])('stores a proposal with $label action(s) on the first call', async ({ actions }) => {
+ const { service, writeDailyBrief } = createProposalService();
+
+ const result = await service.createSelfReviewProposal?.(
+ {
+ actions,
+ idempotencyKey: 'proposal-n',
+ proposalKey: 'skill:proposal-n',
+ summary: 'Proposal with several actions.',
+ userId: 'user-1',
+ },
+ {},
+ );
+
+ expect(result).toMatchObject({ proposalId: 'brief-1' });
+ expect(writeDailyBrief).toHaveBeenCalledTimes(1);
+ expect(
+ getStoredProposalActions(writeDailyBrief).map(
+ (action: { actionType: string }) => action.actionType,
+ ),
+ ).toEqual(actions.map((action) => action.actionType));
+ });
+
+ it('stores a single action sent as an object instead of an array', async () => {
+ const { service, writeDailyBrief } = createProposalService();
+
+ await expect(
+ service.createSelfReviewProposal?.(
+ {
+ actions: refineSkillAction as unknown as unknown[],
+ idempotencyKey: 'proposal-object',
+ proposalKey: 'skill:testing',
+ summary: 'Refine the testing skill.',
+ userId: 'user-1',
+ },
+ {},
+ ),
+ ).resolves.toMatchObject({ proposalId: 'brief-1' });
+ expect(getStoredProposalActions(writeDailyBrief)).toHaveLength(1);
+ });
+
+ /**
+ * @example
+ * The vent shape: one action object, then the rest of the call spilled into
+ * the array as bare strings. The error must name that stray string instead
+ * of a bare "actions[1] has no actionType", and nothing is written.
+ */
+ it('rejects a spilled single action with the stray value and missing fields', async () => {
+ const { service, writeDailyBrief } = createProposalService();
+
+ const call = service.createSelfReviewProposal?.(
+ {
+ actions: [refineSkillAction, 'rationale?', 'summary?', 'idempotencyKey?'],
+ userId: 'user-1',
+ } as never,
+ {},
+ );
+
+ await expect(call).rejects.toThrow(
+ 'actions[1] is the string "rationale?", not an action object',
+ );
+ await expect(call).rejects.toThrow(
+ 'Top-level fields idempotencyKey, proposalKey, summary are missing',
+ );
+ expect(writeDailyBrief).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/proposalInput.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalInput.ts
new file mode 100644
index 00000000000..9adb1c30405
--- /dev/null
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/proposalInput.ts
@@ -0,0 +1,170 @@
+import { isRecord, pickTrimmedString, safeParseJSON } from '@lobechat/utils';
+
+import type { CreateSelfReviewProposalInput } from '../tools/shared';
+
+/** Action types a `createSelfReviewProposal` action may carry. */
+export const SELF_REVIEW_PROPOSAL_ACTION_TYPES = [
+ 'create_skill',
+ 'refine_skill',
+ 'consolidate_skill',
+ 'refine_prompt',
+ 'write_memory',
+ 'proposal_only',
+] as const;
+
+const SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES: Record<string, string> = {
+ record_idea: 'proposal_only',
+};
+
+/** Required tool-schema fields that sit beside `actions`, not inside it. */
+const TOP_LEVEL_PROPOSAL_FIELDS = ['idempotencyKey', 'proposalKey', 'summary'] as const;
+
+/** Problems listed per error; the rest are counted so the message stays readable. */
+const MAX_LISTED_PROBLEMS = 5;
+
+const EXPECTED_ACTION_TYPES = `expected one of: ${SELF_REVIEW_PROPOSAL_ACTION_TYPES.join(', ')}`;
+
+const getRawActionType = (action: Record<PropertyKey, unknown>) =>
+ pickTrimmedString(action.actionType) ?? pickTrimmedString(action.type);
+
+const describeValue = (value: unknown): string => {
+ if (value === null) return 'null';
+ if (Array.isArray(value)) return `an array of ${value.length} item(s)`;
+ if (typeof value === 'string') {
+ const preview = value.length > 40 ? `${value.slice(0, 40)}…` : value;
+
+ return `the string ${JSON.stringify(preview)}`;
+ }
+ if (isRecord(value)) {
+ const keys = Object.keys(value);
+
+ return keys.length > 0 ? `an object with keys ${keys.join(', ')}` : 'an empty object';
+ }
+
+ return `the ${typeof value} ${String(value)}`;
+};
+
+/**
+ * Coerces the unambiguous non-array shapes models send for `actions`.
+ *
+ * - A JSON string holding the array (or one action): some models double-encode nested arrays.
+ * - One action object instead of a one-element array.
+ *
+ * Anything else is returned as-is for the validator to reject with a precise reason.
+ */
+const coerceActions = (value: unknown): unknown => {
+ const decoded = typeof value === 'string' ? (safeParseJSON<unknown>(value) ?? value) : value;
+
+ if (isRecord(decoded) && getRawActionType(decoded)) return [decoded];
+
+ return decoded;
+};
+
+const describeActionProblem = (rawAction: unknown, index: number): string | undefined => {
+ if (!isRecord(rawAction)) {
+ return `actions[${index}] is ${describeValue(rawAction)}, not an action object`;
+ }
+
+ const rawType = getRawActionType(rawAction);
+ if (!rawType) {
+ const keys = Object.keys(rawAction);
+
+ return `actions[${index}] has no actionType (${keys.length > 0 ? `keys: ${keys.join(', ')}` : 'empty object'})`;
+ }
+
+ const actionType = SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES[rawType] ?? rawType;
+ if (!(SELF_REVIEW_PROPOSAL_ACTION_TYPES as readonly string[]).includes(actionType)) {
+ return `actions[${index}] has unsupported actionType "${rawType}"`;
+ }
+};
+
+const buildInvalidActionsMessage = ({
+ actions,
+ input,
+ problems,
+}: {
+ actions: unknown[];
+ input: Record<PropertyKey, unknown>;
+ problems: string[];
+}) => {
+ const objectCount = actions.filter(isRecord).length;
+ const listed = problems.slice(0, MAX_LISTED_PROBLEMS);
+ const remaining = problems.length - listed.length;
+ const missingTopLevelFields = TOP_LEVEL_PROPOSAL_FIELDS.filter(
+ (field) => !pickTrimmedString(input[field]),
+ );
+
+ return [
+ `Received actions with ${actions.length} item(s) (${objectCount} object(s)): ${listed.join('; ')}${remaining > 0 ? `; and ${remaining} more` : ''}.`,
+ // NOTICE:
+ // Production calls arrived as one complete action object followed by bare strings, e.g.
+ // `[{ actionType, target, operation }, "rationale?", "summary?", "idempotencyKey?"]`: the
+ // model closed the object early and the rest of the call spilled into the array. Saying only
+ // "actions[1] has no actionType" made models report a phantom second action and resend the
+ // same shape, so the message names the stray value and the fields that went missing.
+ ...(objectCount > 0 && objectCount < actions.length
+ ? [
+ 'Every actions item must be one complete action object; stray values after an action object usually mean the object was closed too early.',
+ ]
+ : []),
+ ...(missingTopLevelFields.length > 0
+ ? [
+ `Top-level fields ${missingTopLevelFields.join(', ')} are missing; they belong beside actions, not inside it.`,
+ ]
+ : []),
+ `Each action needs actionType (${EXPECTED_ACTION_TYPES}). Resend the whole call with corrected arguments.`,
+ ].join(' ');
+};
+
+/**
+ * Normalizes model-authored proposal actions before projection.
+ *
+ * Models routinely send the action kind as `type` (and the legacy prompt named
+ * ideas `record_idea`); the projection only reads `actionType`, so those
+ * proposals silently projected to nothing and every nightly review ended
+ * without a brief. Unambiguous shape slips (one action object, a JSON-encoded
+ * array) are coerced; anything else fails loudly with every offending index and
+ * what it holds, so the model can repair the call in one retry.
+ */
+export const normalizeSelfReviewProposalInput = (
+ input: CreateSelfReviewProposalInput,
+): CreateSelfReviewProposalInput => {
+ if (input.actions === undefined || input.actions === null) return input;
+
+ const actions = coerceActions(input.actions);
+
+ if (!Array.isArray(actions)) {
+ throw new TypeError(
+ `actions must be an array of action objects, but received ${describeValue(actions)}. Each action needs actionType (${EXPECTED_ACTION_TYPES}).`,
+ );
+ }
+
+ const problems = actions.flatMap((rawAction, index) => {
+ const problem = describeActionProblem(rawAction, index);
+
+ return problem ? [problem] : [];
+ });
+
+ if (problems.length > 0) {
+ throw new Error(
+ buildInvalidActionsMessage({
+ actions,
+ input: input as unknown as Record<PropertyKey, unknown>,
+ problems,
+ }),
+ );
+ }
+
+ return {
+ ...input,
+ actions: actions.map((rawAction) => {
+ const action = rawAction as Record<PropertyKey, unknown>;
+ const rawType = getRawActionType(action) as string;
+
+ return {
+ ...action,
+ actionType: SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES[rawType] ?? rawType,
+ };
+ }),
+ };
+};
diff --git a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts b/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts
index 81dbfc9d476..cf83dccae6c 100644
--- a/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts
+++ b/apps/server/src/services/agentSignal/services/selfIteration/review/server.ts
@@ -52,6 +52,10 @@ import {
refreshSelfReviewProposal,
supersedeSelfReviewProposal,
} from './proposal';
+import {
+ normalizeSelfReviewProposalInput,
+ SELF_REVIEW_PROPOSAL_ACTION_TYPES,
+} from './proposalInput';
import { createSelfReviewProposalPreflightService } from './proposalPreflight';
import { createSelfReviewProposalSnapshotService } from './proposalSnapshot';
import {
@@ -189,55 +193,6 @@ const getProposalActionSnapshotInput = (action: Record<string, unknown>) => {
};
};
-/** Action types a `createSelfReviewProposal` action may carry. */
-export const SELF_REVIEW_PROPOSAL_ACTION_TYPES = [
- 'create_skill',
- 'refine_skill',
- 'consolidate_skill',
- 'refine_prompt',
- 'write_memory',
- 'proposal_only',
-] as const;
-
-const SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES: Record<string, string> = {
- record_idea: 'proposal_only',
-};
-
-/**
- * Normalizes model-authored proposal actions before projection.
- *
- * Models routinely send the action kind as `type` (and the legacy prompt named
- * ideas `record_idea`); the projection only reads `actionType`, so those
- * proposals silently projected to nothing and every nightly review ended
- * without a brief. Unknown action types fail loudly so the model can retry.
- */
-export const normalizeSelfReviewProposalInput = (
- input: CreateSelfReviewProposalInput,
-): CreateSelfReviewProposalInput => {
- if (!Array.isArray(input.actions)) return input;
-
- const actions = input.actions.map((rawAction, index) => {
- const action = toRecordOrEmpty(rawAction);
- const rawType = pickTrimmedString(action.actionType) ?? pickTrimmedString(action.type);
- const actionType = rawType
- ? (SELF_REVIEW_PROPOSAL_ACTION_TYPE_ALIASES[rawType] ?? rawType)
- : undefined;
-
- if (
- !actionType ||
- !(SELF_REVIEW_PROPOSAL_ACTION_TYPES as readonly string[]).includes(actionType)
- ) {
- throw new Error(
- `actions[${index}] has ${rawType ? `unsupported actionType "${rawType}"` : 'no actionType'}; expected one of: ${SELF_REVIEW_PROPOSAL_ACTION_TYPES.join(', ')}.`,
- );
- }
-
- return { ...action, actionType };
- });
-
- return { ...input, actions } as CreateSelfReviewProposalInput;
-};
-
const withCompleteProposalSnapshots = async ({
agentId,
input,
diff --git a/packages/builtin-tool-agent-signal/src/shared/schemas.ts b/packages/builtin-tool-agent-signal/src/shared/schemas.ts
index c6390fa6c6c..3f271bdfd9f 100644
--- a/packages/builtin-tool-agent-signal/src/shared/schemas.ts
+++ b/packages/builtin-tool-agent-signal/src/shared/schemas.ts
@@ -23,6 +23,8 @@ const obj = (
): Record<string, unknown> => ({ properties, required: [...required], type: 'object' });
const selfReviewProposalActionsSchema = {
+ description:
+ 'One complete object per action. Keep idempotencyKey, proposalKey and summary at the top level, beside actions.',
items: {
additionalProperties: true,
properties: {