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(goal): complete generated plan feedback (#18615)

Arvin Xu7d461b9416f4
diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.ts
index a710a98705c..290baf82b12 100644
--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts
@@ -16,6 +16,7 @@ const modelMocks = vi.hoisted(() => ({
findResultById: vi.fn(),
generateCriteria: vi.fn(),
generateGoalCriteria: vi.fn(),
+ generateGoalPlan: vi.fn(),
getFullFileUrl: vi.fn(),
getServerDB: vi.fn(async () => ({})),
updateRun: vi.fn(),
@@ -63,6 +64,7 @@ vi.mock('@/server/services/verify', async (importOriginal) => ({
vi.mock('@/server/services/goal/criteriaGenerator', () => ({
GoalCriteriaGeneratorService: class GoalCriteriaGeneratorService {
generate = modelMocks.generateGoalCriteria;
+ generatePlan = modelMocks.generateGoalPlan;
},
}));
@@ -146,6 +148,19 @@ describe('verifyRouter', () => {
goal: 'Ship a responsive task board',
});
});
+
+ it('returns the generated plan from the versioned endpoint', async () => {
+ const plan = {
+ criteria: [{ title: 'Responsive task board is shipped' }],
+ instruction: 'Ship a responsive task board.',
+ title: 'Ship task board',
+ };
+ modelMocks.generateGoalPlan.mockResolvedValueOnce(plan);
+
+ await expect(
+ createCaller().generateGoalPlan({ goal: 'Ship a responsive task board' }),
+ ).resolves.toEqual(plan);
+ });
});
describe('ingestResult', () => {
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index 18eb5ae1ef5..a0ab5d72fb6 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -546,6 +546,34 @@ export const verifyRouter = router({
}
}),
+ /** Draft the generated goal title, instruction, and standing acceptance contract. */
+ generateGoalPlan: verifyWriteProcedure
+ .input(
+ z.object({
+ context: z.string().optional(),
+ goal: z.string().min(1),
+ maxCriteria: z.number().int().min(1).max(8).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.goalCriteriaGenerator.generatePlan(input);
+ } catch (error) {
+ const errorType = (error as { errorType?: unknown } | null)?.errorType;
+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
+ const trpcError = new TRPCError({
+ cause: error,
+ code: 'PRECONDITION_FAILED',
+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ });
+ markSilentTRPCErrorLog(trpcError.cause);
+ throw trpcError;
+ }
+
+ throw error;
+ }
+ }),
+
/** Persist (user-edited) drafts as standalone criteria; returns their ids in order. */
createCriteria: verifyWriteProcedure
.input(
diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.ts
index 31661dc1ffc..3ad34d49270 100644
--- a/apps/server/src/services/goal/criteriaGenerator.test.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts
@@ -17,7 +17,11 @@ describe('GoalCriteriaGeneratorService', () => {
beforeEach(() => {
vi.clearAllMocks();
resolveGoalModelConfig.mockResolvedValue({ model: 'goal-model', provider: 'goal-provider' });
- generateObject.mockResolvedValue({ criteria: [] });
+ generateObject.mockResolvedValue({
+ criteria: [],
+ instruction: 'Publish the benchmark paper.',
+ title: 'Publish benchmark paper',
+ });
});
it('uses the dedicated goal model, prompt version, schema, and tracing scenario', async () => {
@@ -34,7 +38,7 @@ describe('GoalCriteriaGeneratorService', () => {
}),
expect.objectContaining({
tracing: {
- promptVersion: 'v1',
+ promptVersion: 'v2',
scenario: 'goal_criteria_gen',
schemaName: 'goal_criteria_draft',
},
@@ -57,10 +61,30 @@ describe('GoalCriteriaGeneratorService', () => {
verifierType: 'agent',
},
],
+ instruction: 'Ship it.',
+ title: 'Ship it',
});
await expect(
new GoalCriteriaGeneratorService({} as any, 'user-1').generate({ goal: 'Ship it' }),
).resolves.toEqual([]);
});
+
+ it('keeps the array response for existing callers while exposing the full generated plan', async () => {
+ generateObject.mockResolvedValue({
+ criteria: [{ title: 'Benchmark is published', verifierType: 'agent' }],
+ instruction: 'Publish the benchmark paper.',
+ title: 'Publish benchmark paper',
+ });
+ const service = new GoalCriteriaGeneratorService({} as any, 'user-1');
+
+ await expect(service.generate({ goal: 'Publish a benchmark paper' })).resolves.toEqual([
+ { title: 'Benchmark is published', verifierType: 'agent' },
+ ]);
+ await expect(service.generatePlan({ goal: 'Publish a benchmark paper' })).resolves.toEqual({
+ criteria: [{ title: 'Benchmark is published', verifierType: 'agent' }],
+ instruction: 'Publish the benchmark paper.',
+ title: 'Publish benchmark paper',
+ });
+ });
});
diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.ts
index c52464868bb..0081f59e130 100644
--- a/apps/server/src/services/goal/criteriaGenerator.ts
+++ b/apps/server/src/services/goal/criteriaGenerator.ts
@@ -44,6 +44,8 @@ const generatedCriteriaSchema = z.object({
verifierType: z.enum(VERIFY_VERIFIER_TYPES),
}),
),
+ instruction: z.string().min(1),
+ title: z.string().min(1).max(80),
});
export interface GoalCriterionDraft {
@@ -56,6 +58,12 @@ export interface GoalCriterionDraft {
verifierType?: VerifyCheckItem['verifierType'];
}
+export interface GoalPlanDraft {
+ criteria: GoalCriterionDraft[];
+ instruction: string;
+ title: string;
+}
+
export class GoalCriteriaGeneratorService {
constructor(
private readonly db: LobeChatDatabase,
@@ -68,6 +76,16 @@ export class GoalCriteriaGeneratorService {
goal: string;
maxCriteria?: number;
}): Promise<GoalCriterionDraft[]> {
+ const plan = await this.generatePlan(params);
+
+ return plan?.criteria ?? [];
+ }
+
+ async generatePlan(params: {
+ context?: string;
+ goal: string;
+ maxCriteria?: number;
+ }): Promise<GoalPlanDraft | undefined> {
const maxCriteria = params.maxCriteria ?? DEFAULT_MAX_CRITERIA;
const modelConfig = await resolveGoalModelConfig(this.db, this.userId);
const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);
@@ -91,11 +109,13 @@ export class GoalCriteriaGeneratorService {
const parsed = generatedCriteriaSchema.safeParse(raw);
if (!parsed.success) {
log('goal criteria draft did not match schema: %O', parsed.error.flatten());
- return [];
+ return undefined;
}
- return parsed.data.criteria
+ const criteria = parsed.data.criteria
.slice(0, maxCriteria)
.filter((criterion) => !isProgrammaticTestCheck(criterion.title, criterion.description));
+
+ return { ...parsed.data, criteria };
}
}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 7098c866631..d6f1b8db6e6 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -248,6 +248,12 @@
"createGoal.describeHint": "Describe the outcome first, then complete its execution plan.",
"createGoal.describeTitle": "What goal do you expect to achieve?",
"createGoal.generateFailed": "Could not draft acceptance criteria, so your goal was used as the criterion.",
+ "createGoal.generating": "Understanding your goal…",
+ "createGoal.generatingAlmostDone": "Almost done…",
+ "createGoal.generatingCountdown": "About {{time}} remaining",
+ "createGoal.generatingCriteria": "Drafting acceptance criteria…",
+ "createGoal.generatingInstruction": "Writing the execution brief…",
+ "createGoal.generatingReview": "Checking the complete plan…",
"createGoal.instructionPlaceholder": "Add any context the agent needs — scope, constraints, where to look…",
"createGoal.next": "Next",
"createGoal.preparing": "Preparing plan…",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 7679759fbab..205e84e97fc 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -248,6 +248,12 @@
"createGoal.describeHint": "先描述想要的结果,下一步再完善完整执行计划。",
"createGoal.describeTitle": "你期望达到的目标",
"createGoal.generateFailed": "没能自动起草,已将目标内容作为验收标准。",
+ "createGoal.generating": "正在理解目标…",
+ "createGoal.generatingAlmostDone": "即将完成…",
+ "createGoal.generatingCountdown": "预计还需 {{time}}",
+ "createGoal.generatingCriteria": "正在起草验收标准…",
+ "createGoal.generatingInstruction": "正在完善执行说明…",
+ "createGoal.generatingReview": "正在检查完整计划…",
"createGoal.instructionPlaceholder": "补充 Agent 需要的背景 —— 范围、约束、从哪里入手……",
"createGoal.next": "下一步",
"createGoal.preparing": "正在准备计划…",
diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.ts
index d23395049c7..f1a9a773915 100644
--- a/packages/database/src/models/__tests__/messages/message.update.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts
@@ -1423,7 +1423,7 @@ describe('MessageModel Update Tests', () => {
expect(result.success).toBe(true);
// Query should complete within 100ms even with many messages
// (indexed lookup should be O(1), not O(n))
- expect(duration).toBeLessThan(30);
+ expect(duration).toBeLessThan(100);
// Verify the update was correct
const parentResult = await serverDB
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 54eebd4dcd6..954760b53b6 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1628,6 +1628,12 @@ export default {
'createGoal.describeHint': 'Describe the outcome first, then complete its execution plan.',
'createGoal.generateFailed':
'Could not draft acceptance criteria, so your goal was used as the criterion.',
+ 'createGoal.generating': 'Understanding your goal…',
+ 'createGoal.generatingAlmostDone': 'Almost done…',
+ 'createGoal.generatingCountdown': 'About {{time}} remaining',
+ 'createGoal.generatingCriteria': 'Drafting acceptance criteria…',
+ 'createGoal.generatingInstruction': 'Writing the execution brief…',
+ 'createGoal.generatingReview': 'Checking the complete plan…',
'createGoal.instructionPlaceholder':
'Add any context the agent needs — scope, constraints, where to look…',
'createGoal.next': 'Next',
diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.ts
index b3f44770d1a..ca531c9e923 100644
--- a/packages/prompts/src/chains/goal.test.ts
+++ b/packages/prompts/src/chains/goal.test.ts
@@ -14,10 +14,21 @@ describe('chainGoalCriteriaDraft', () => {
maxCriteria: 6,
});
- expect(GOAL_CRITERIA_DRAFT_PROMPT_VERSION).toBe('v1');
+ expect(GOAL_CRITERIA_DRAFT_PROMPT_VERSION).toBe('v2');
expect(GOAL_CRITERIA_DRAFT_JSON_SCHEMA.name).toBe('goal_criteria_draft');
expect(chain.messages[0].content).toContain('persistent autonomous goal');
expect(chain.messages[0].content).toContain('at most 6 criteria');
+ expect(chain.messages[0].content).toContain(
+ 'top-level instruction is a complete, actionable task brief',
+ );
+ expect(chain.messages[0].content).toContain(
+ 'criteria[].instruction is the exact, detailed judging rubric',
+ );
+ expect(GOAL_CRITERIA_DRAFT_JSON_SCHEMA.schema.required).toEqual([
+ 'title',
+ 'instruction',
+ 'criteria',
+ ]);
expect(chain.messages[1].content).toContain('Ship a polished v1');
});
});
diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.ts
index 9187d18e22a..624b659968a 100644
--- a/packages/prompts/src/chains/goal.ts
+++ b/packages/prompts/src/chains/goal.ts
@@ -9,7 +9,7 @@ import {
} from './verify';
/** Bump when the create-goal criteria drafting prompt meaningfully changes. */
-export const GOAL_CRITERIA_DRAFT_PROMPT_VERSION = 'v1';
+export const GOAL_CRITERIA_DRAFT_PROMPT_VERSION = 'v2';
export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {
name: 'goal_criteria_draft',
@@ -55,8 +55,10 @@ export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {
maxItems: 8,
type: 'array',
},
+ instruction: { minLength: 1, type: 'string' },
+ title: { maxLength: 80, minLength: 1, type: 'string' },
},
- required: ['criteria'],
+ required: ['title', 'instruction', 'criteria'],
type: 'object' as const,
},
strict: true,
@@ -80,6 +82,8 @@ export const chainGoalCriteriaDraft = ({
'You define the standing acceptance contract for a persistent autonomous goal.',
'Turn the goal into a concise set of durable, user-reviewable pass/fail criteria that can be applied after every iteration.',
'Guidelines:',
+ '- title is a concise goal name, not a copy of the full request.',
+ '- The top-level instruction is a complete, actionable task brief for the autonomous agent. Preserve every concrete URL, scope, constraint, and requested outcome from the user.',
`- Return at most ${maxCriteria} criteria. Prefer fewer independent criteria that together define success.`,
'- Describe outcomes and delivered artifacts, not implementation steps or one particular execution plan.',
'- Criteria must remain valid across multiple attempts. Do not mention the current round, temporary progress, or how the agent should work.',
@@ -88,7 +92,7 @@ export const chainGoalCriteriaDraft = ({
'- Use verifierType="agent" when judging requires active investigation, opening files, or multiple evidence types; use "llm" only for inline text or a directly inspectable image; use "program" only for deterministic command checks.',
'- Set required=true when failure means the goal has not been achieved.',
'- Set onFail="auto_repair" when another autonomous iteration can address the failure; otherwise use "manual".',
- '- description is a one-sentence summary. instruction is the exact, detailed judging rubric, including pass conditions, failure conditions, evidence, and important edge cases.',
+ '- Each criteria[].description is a one-sentence summary. Each criteria[].instruction is the exact, detailed judging rubric, including pass conditions, failure conditions, evidence, and important edge cases.',
'- Write all human-facing fields in the language used by the goal.',
].join('\n'),
role: 'system',
diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
index f0d3264f093..5a05f22e151 100644
--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx
@@ -21,10 +21,9 @@ import { type KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef, useS
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import TaskVisibilityChipLabel from '@/features/AgentTasks/features/TaskVisibilityChipLabel';
import TaskVisibilityTag from '@/features/AgentTasks/features/TaskVisibilityTag';
-import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
import { useAgentVisibility } from '@/features/AgentTasks/shared/useAgentVisibility';
import { EditorCanvas } from '@/features/EditorCanvas';
import { pickAndInsertAttachments } from '@/features/EditorCanvas/editorAttachments';
@@ -37,6 +36,7 @@ import {
import { usePermission } from '@/hooks/usePermission';
import { verifyService } from '@/services/verify';
import { useTaskStore } from '@/store/task';
+import { shinyTextStyles } from '@/styles';
import { buildGoalTaskConfig } from './goalConfig';
import { createFallbackGoalCriterion, generateGoalCriteria } from './goalCriteria';
@@ -78,6 +78,59 @@ const styles = createStaticStyles(({ css }) => ({
padding-inline: 16px;
border-block-start: 1px solid ${cssVar.colorBorderSecondary};
`,
+ generatingStatus: css`
+ min-height: 36px;
+ padding-block: 6px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ generatingTextItem: css`
+ display: flex;
+ align-items: center;
+
+ height: 22px;
+
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 22px;
+ white-space: nowrap;
+ `,
+ generatingTextTrack: css`
+ animation: goal-generation-roll 16s cubic-bezier(0.4, 0, 0.2, 1) infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+
+ @keyframes goal-generation-roll {
+ 0%,
+ 20% {
+ transform: translateY(0);
+ }
+
+ 25%,
+ 45% {
+ transform: translateY(-22px);
+ }
+
+ 50%,
+ 70% {
+ transform: translateY(-44px);
+ }
+
+ 75%,
+ 95% {
+ transform: translateY(-66px);
+ }
+
+ 100% {
+ transform: translateY(-88px);
+ }
+ }
+ `,
+ generatingTextViewport: css`
+ overflow: hidden;
+ height: 22px;
+ `,
head: css`
position: relative;
padding-block: 16px 8px;
@@ -201,6 +254,14 @@ const GoalBorderFlowStyle = createGlobalStyle`
}
`;
+const GENERATION_ESTIMATE_SECONDS = 90;
+
+export const formatGoalGenerationRemainingTime = (seconds: number) => {
+ const minutes = Math.floor(seconds / 60);
+ const rest = seconds % 60;
+ return `${minutes}:${rest.toString().padStart(2, '0')}`;
+};
+
const criterionRequirement = (drafts: GoalCriterionDraft[]) =>
drafts
.map((draft) => draft.title.trim())
@@ -250,6 +311,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
// Default to private in workspace mode so sharing is opt-in; personal mode
// ignores the field and hides the chip.
const [visibility, setVisibility] = useState<'private' | 'public'>('private');
+ const [remainingSeconds, setRemainingSeconds] = useState(GENERATION_ESTIMATE_SECONDS);
// A private agent can only run a private task, goals included.
const isPrivateAgent = useAgentVisibility(agentId) === 'private';
@@ -259,9 +321,18 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
const editor = useEditor();
const instructionRef = useRef(plan.instruction);
- const assigneeMeta = useAgentDisplayMeta(agentId);
const requirement = useMemo(() => criterionRequirement(plan.criteria), [plan.criteria]);
+ useEffect(() => {
+ if (step !== 'preparing') return;
+ setRemainingSeconds(GENERATION_ESTIMATE_SECONDS);
+ const timer = window.setInterval(
+ () => setRemainingSeconds((value) => Math.max(0, value - 1)),
+ 1000,
+ );
+ return () => window.clearInterval(timer);
+ }, [step]);
+
const handleContentChange = useCallback(() => {
if (!canCreate || !editor) return;
instructionRef.current = String(editor.getDocument('markdown') ?? '');
@@ -286,11 +357,14 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
try {
const generated = await generateGoalCriteria({
context: name ? `Goal: ${name}` : undefined,
- goal: initialRequirement?.trim() || instruction,
+ goal: instruction,
});
+ instructionRef.current = generated.instruction;
setPlan((current) => ({
...current,
- criteria: generated,
+ criteria: generated.criteria,
+ instruction: generated.instruction,
+ name: generated.title,
}));
setStep('review');
} catch (error) {
@@ -304,7 +378,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
setStep('review');
toast.warning(t('createGoal.generateFailed'));
}
- }, [canCreate, initialRequirement, plan.instruction, plan.name, t]);
+ }, [canCreate, plan.instruction, plan.name, t]);
const handleCreateBlank = useCallback(() => {
if (!canCreate) return;
@@ -419,6 +493,13 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
const handlePrimaryAction =
step === 'describe' ? handleNext : step === 'review' ? handleSubmit : undefined;
const handleSubmitRef = useRef(handlePrimaryAction);
+ const generatingMessages = [
+ t('createGoal.generating'),
+ t('createGoal.generatingInstruction'),
+ t('createGoal.generatingCriteria'),
+ t('createGoal.generatingReview'),
+ t('createGoal.generating'),
+ ];
useEffect(() => {
handleSubmitRef.current = handlePrimaryAction;
}, [handlePrimaryAction]);
@@ -476,7 +557,44 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
onContentChange={handleContentChange}
/>
</div>
- <Text type={'secondary'}>{t('createGoal.describeHint')}</Text>
+ {step === 'preparing' ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.generatingStatus}
+ gap={10}
+ justify={'space-between'}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <NeuralNetworkLoading size={18} />
+ <div
+ aria-label={t('createGoal.generating')}
+ className={styles.generatingTextViewport}
+ role={'status'}
+ >
+ <div aria-hidden className={styles.generatingTextTrack}>
+ {generatingMessages.map((message, index) => (
+ <div
+ className={`${styles.generatingTextItem} ${shinyTextStyles.shinyText}`}
+ key={index}
+ >
+ {message}
+ </div>
+ ))}
+ </div>
+ </div>
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {remainingSeconds > 0
+ ? t('createGoal.generatingCountdown', {
+ time: formatGoalGenerationRemainingTime(remainingSeconds),
+ })
+ : t('createGoal.generatingAlmostDone')}
+ </Text>
+ </Flexbox>
+ ) : (
+ <Text type={'secondary'}>{t('createGoal.describeHint')}</Text>
+ )}
</>
)}
</Flexbox>
@@ -619,10 +737,6 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {
<Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}>
<Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
- <Flexbox horizontal align={'center'} gap={6}>
- <AssigneeAvatar agentId={agentId} size={18} />
- <Text fontSize={12}>{assigneeMeta?.title}</Text>
- </Flexbox>
{activeWorkspaceId && (
<TaskVisibilityTag
visibility={visibility}
diff --git a/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts b/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts
index ca6f1e0e9b9..0d36dcd969a 100644
--- a/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts
+++ b/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts
@@ -10,12 +10,15 @@ describe('generateGoalCriteria', () => {
});
it('generates and normalizes acceptance criteria for the goal review step', async () => {
- const generateCriteria = vi
- .spyOn(verifyService, 'generateGoalCriteria')
- .mockResolvedValue([
+ const generateCriteria = vi.spyOn(verifyService, 'generateGoalPlan').mockResolvedValue({
+ criteria: [
{ title: 'Paper draft is complete' },
{ required: false, title: 'Results are reproducible', verifierType: 'llm' },
- ]);
+ ],
+ instruction:
+ 'Complete an RSI benchmark paper in three months. Write and publish the benchmark paper.',
+ title: 'Publish benchmark paper',
+ });
const result = await generateGoalCriteria({
context: 'Goal: Publish an ICLR paper',
@@ -27,30 +30,55 @@ describe('generateGoalCriteria', () => {
goal: 'Complete an RSI benchmark paper in three months',
maxCriteria: 8,
});
- expect(result).toEqual([
- {
- onFail: 'auto_repair',
- required: true,
- title: 'Paper draft is complete',
- verifierType: 'agent',
- },
- {
- onFail: 'auto_repair',
- required: false,
- title: 'Results are reproducible',
- verifierType: 'llm',
- },
- ]);
+ expect(result).toEqual({
+ criteria: [
+ {
+ onFail: 'auto_repair',
+ required: true,
+ title: 'Paper draft is complete',
+ verifierType: 'agent',
+ },
+ {
+ onFail: 'auto_repair',
+ required: false,
+ title: 'Results are reproducible',
+ verifierType: 'llm',
+ },
+ ],
+ instruction:
+ 'Complete an RSI benchmark paper in three months. Write and publish the benchmark paper.',
+ title: 'Publish benchmark paper',
+ });
});
it('rejects an empty AI response instead of advancing with no criteria', async () => {
- vi.spyOn(verifyService, 'generateGoalCriteria').mockResolvedValue([]);
+ vi.spyOn(verifyService, 'generateGoalPlan').mockResolvedValue({
+ criteria: [],
+ instruction: 'Ship the project.',
+ title: 'Ship the project',
+ });
await expect(
generateGoalCriteria({
goal: 'Ship the project',
}),
- ).rejects.toThrow('No acceptance criteria were generated.');
+ ).rejects.toThrow('No goal plan was generated.');
+ });
+
+ it('keeps the exact user goal when the generated instruction omits it', async () => {
+ vi.spyOn(verifyService, 'generateGoalPlan').mockResolvedValue({
+ criteria: [{ title: 'Training loop works' }],
+ instruction: 'Implement a reproducible self-improvement training loop.',
+ title: 'Reproduce self-improvement training',
+ });
+ const goal =
+ 'Reproduce https://ornith.ai/ornith_1_5.html with a three-round budget and export results.';
+
+ const result = await generateGoalCriteria({ goal });
+
+ expect(result.instruction).toBe(
+ `${goal}\n\nImplement a reproducible self-improvement training loop.`,
+ );
});
it('uses the original goal as a reviewable criterion when AI generation fails', () => {
diff --git a/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts b/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts
index c438acbb7f1..ee78701b891 100644
--- a/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts
+++ b/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts
@@ -8,6 +8,19 @@ interface GenerateGoalCriteriaParams {
goal: string;
}
+const preserveOriginalGoal = (goal: string, generatedInstruction: string) => {
+ const original = goal.trim();
+ const generated = generatedInstruction.trim();
+
+ return generated.includes(original) ? generated : `${original}\n\n${generated}`;
+};
+
+export interface GeneratedGoalPlan {
+ criteria: GoalCriterionDraft[];
+ instruction: string;
+ title: string;
+}
+
export const withGoalCriterionDefaults = (draft: VerifyCriterionDraft): GoalCriterionDraft => ({
...draft,
onFail: draft.onFail ?? 'auto_repair',
@@ -25,14 +38,18 @@ export const createFallbackGoalCriterion = (goal: string): GoalCriterionDraft =>
export const generateGoalCriteria = async ({
context,
goal,
-}: GenerateGoalCriteriaParams): Promise<GoalCriterionDraft[]> => {
- const generated = await verifyService.generateGoalCriteria({
+}: GenerateGoalCriteriaParams): Promise<GeneratedGoalPlan> => {
+ const generated = await verifyService.generateGoalPlan({
context,
goal,
maxCriteria: 8,
});
- if (generated.length === 0) throw new Error('No acceptance criteria were generated.');
+ if (!generated || generated.criteria.length === 0) throw new Error('No goal plan was generated.');
- return generated.map(withGoalCriterionDefaults);
+ return {
+ ...generated,
+ criteria: generated.criteria.map(withGoalCriterionDefaults),
+ instruction: preserveOriginalGoal(goal, generated.instruction),
+ };
};
diff --git a/src/services/verify.ts b/src/services/verify.ts
index 1a580574b94..511b45a949f 100644
--- a/src/services/verify.ts
+++ b/src/services/verify.ts
@@ -381,6 +381,18 @@ export class VerifyService {
}): Promise<VerifyCriterionDraft[]> =>
lambdaClient.verify.generateGoalCriteria.mutate(input) as Promise<VerifyCriterionDraft[]>;
+ /** Draft the title, instruction, and criteria used by the create-goal review step. */
+ generateGoalPlan = (input: {
+ context?: string;
+ goal: string;
+ maxCriteria?: number;
+ }): Promise<
+ { criteria: VerifyCriterionDraft[]; instruction: string; title: string } | undefined
+ > =>
+ lambdaClient.verify.generateGoalPlan.mutate(input) as Promise<
+ { criteria: VerifyCriterionDraft[]; instruction: string; title: string } | undefined
+ >;
+
/** Persist (user-edited) drafts as standalone criteria; returns ids in order. */
createCriteria = (drafts: VerifyCriterionDraft[]): Promise<string[]> =>
lambdaClient.verify.createCriteria.mutate({ drafts }) as Promise<string[]>;