π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(task): retire recurring tasks when their end condition is met (#20692)
AmAzing-50a302fbd48a
diff --git a/apps/cli/src/commands/task/lifecycle.test.ts b/apps/cli/src/commands/task/lifecycle.test.tsindex aa12ca56a5b..23512f1376a 100644--- a/apps/cli/src/commands/task/lifecycle.test.ts+++ b/apps/cli/src/commands/task/lifecycle.test.ts@@ -113,6 +113,45 @@ describe('task comment attribution', () => {});});+describe('task complete', () => {+ beforeEach(() => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');+ client.task.updateStatus.mutate.mockReset();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('passes the current run so completing its own task is deferred', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op_tick');+ client.task.updateStatus.mutate.mockResolvedValue({+ completionDeferred: true,+ data: { identifier: 'T-1' },+ });++ await createProgram().parseAsync(['node', 'test', 'task', 'complete', 'T-1']);++ expect(client.task.updateStatus.mutate).toHaveBeenCalledWith({+ id: 'T-1',+ operationId: 'op_tick',+ status: 'completed',+ });+ });++ it('omits the operation outside an agent run', async () => {+ client.task.updateStatus.mutate.mockResolvedValue({ data: { identifier: 'T-1' } });++ await createProgram().parseAsync(['node', 'test', 'task', 'complete', 'T-1']);++ expect(client.task.updateStatus.mutate).toHaveBeenCalledWith({+ id: 'T-1',+ operationId: undefined,+ status: 'completed',+ });+ });+});+describe('task lifecycle β following the agent stream', () => {let exitSpy: ReturnType<typeof vi.spyOn>;diff --git a/apps/cli/src/commands/task/lifecycle.ts b/apps/cli/src/commands/task/lifecycle.tsindex ab16878c497..5872fffc869 100644--- a/apps/cli/src/commands/task/lifecycle.ts+++ b/apps/cli/src/commands/task/lifecycle.ts@@ -279,7 +279,20 @@ export function registerLifecycleCommands(task: Command) {.description('Mark a task as completed').action(async (id: string) => {const client = await getTrpcClient();- const result = (await client.task.updateStatus.mutate({ id, status: 'completed' })) as any;+ // Inside an agent run, completing the task being executed is deferred to+ // the end of the run instead of interrupting it.+ const operationId = process.env.LOBEHUB_OPERATION_ID?.trim() || undefined;+ const result = (await client.task.updateStatus.mutate({+ id,+ operationId,+ status: 'completed',+ })) as any;+ if (result.completionDeferred) {+ log.info(+ `Task ${pc.bold(result.data.identifier)} completion requested. It will be finalized when the current run finishes.`,+ );+ return;+ }log.info(`Task ${pc.bold(result.data.identifier)} completed.`);if (result.unlocked?.length > 0) {log.info(`Unlocked: ${result.unlocked.map((id: string) => pc.bold(id)).join(', ')}`);diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 09d65315a01..db6bbf3c320 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -1647,6 +1647,7 @@ export const taskRouter = router({actorAgentId: z.string().optional(),error: z.string().optional(),id: z.string(),+ operationId: z.string().optional(),status: z.enum(TASK_STATUSES),}),)@@ -1657,12 +1658,20 @@ export const taskRouter = router({// transitions call the service without an actor and stay silent.const actor = await resolveActivityActor(ctx, actorAgentId);const result = await ctx.taskService.updateStatus(statusInput, actor);- const { task, unlocked, paused, checkpointTriggered, allSubtasksDone, parentTaskId } =- result;+ const {+ task,+ unlocked,+ paused,+ checkpointTriggered,+ allSubtasksDone,+ parentTaskId,+ completionDeferred,+ } = result;return {data: task,message: `Task ${input.status}`,success: true,+ ...(completionDeferred && { completionDeferred: true }),...(unlocked.length > 0 && { unlocked }),...(paused.length > 0 && { paused }),...(checkpointTriggered && { checkpointTriggered: true }),diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex ec98ac168bc..c9e78d85170 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -1483,6 +1483,48 @@ describe('TaskService', () => {});});+ describe('completion requested by the task own run', () => {+ it('defers instead of interrupting the calling operation', async () => {+ const task = { automationMode: 'schedule', id: 'task-self', status: 'running' };+ mockTaskModel.resolve.mockResolvedValue(task);+ mockTaskTopicModel.findByTaskId.mockResolvedValue([+ { topicId: 'topic-self', operationId: 'op-self', status: 'running' },+ ]);++ const result = await new TaskService(db, userId).updateStatus({+ id: 'task-self',+ operationId: 'op-self',+ status: 'completed',+ });++ expect(result).toMatchObject({ completionDeferred: true, task });+ expect(mockTaskModel.updateContext).toHaveBeenCalledWith('task-self', {+ completion: { requestedByOperationId: 'op-self' },+ });+ expect(interruptTaskMock).not.toHaveBeenCalled();+ expect(mockTaskTopicModel.cancelIfRunning).not.toHaveBeenCalled();+ expect(mockTaskModel.updateStatus).not.toHaveBeenCalled();+ });++ it('still interrupts when the operation is not one of the task runs', async () => {+ mockTaskModel.resolve.mockResolvedValue({ id: 'task-live', status: 'running' });+ mockTaskTopicModel.findByTaskId.mockResolvedValue([+ { topicId: 'topic-live', operationId: 'op-live', status: 'running' },+ ]);+ interruptTaskMock.mockResolvedValueOnce({ success: false });++ await expect(+ new TaskService(db, userId).updateStatus({+ id: 'task-live',+ operationId: 'op-other',+ status: 'completed',+ }),+ ).rejects.toThrow('Task interruption was not confirmed');+ expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-live' });+ expect(mockTaskModel.updateContext).not.toHaveBeenCalled();+ });+ });+describe('confirmed execution stop', () => {it.each([{ success: true, deviceCancellationConfirmed: false }, { success: false }])('keeps a live Task and topic unchanged when cancellation is unconfirmed: %j',diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex 210ca6b0ca1..fbdc5a18a5a 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -100,6 +100,8 @@ export interface CreateTaskInput {export interface UpdateStatusResult {allSubtasksDone?: boolean;checkpointTriggered?: boolean;+ /** Completion was requested by the task's own run and lands when it ends. */+ completionDeferred?: boolean;parentTaskId?: string | null;paused: string[];task: TaskItem;@@ -489,6 +491,13 @@ export class TaskService {input: {error?: string;id: string;+ /**+ * The caller's own run, when an agent changes the task it is executing.+ * Completing that task is a delivery request: it is recorded and+ * finalized by onTopicComplete once the run ends, instead of+ * interrupting the run mid-tool-call.+ */+ operationId?: string;status: TaskStatus;},/**@@ -498,7 +507,7 @@ export class TaskService {*/actor?: { agentId?: string | null; userId?: string | null },): Promise<UpdateStatusResult> {- const { id, status, error: errorMsg } = input;+ const { id, operationId, status, error: errorMsg } = input;if (errorMsg && status !== 'failed') {throw new TRPCError({@@ -511,6 +520,18 @@ export class TaskService {if (resolved.status === 'running' && status !== 'running') {const topics = await this.taskTopicModel.findByTaskId(resolved.id);++ if (+ status === 'completed' &&+ operationId &&+ topics.some((t) => t.status === 'running' && t.operationId === operationId)+ ) {+ await this.taskModel.updateContext(resolved.id, {+ completion: { requestedByOperationId: operationId },+ });+ return { completionDeferred: true, paused: [], task: resolved, unlocked: [] };+ }+const aiAgentService = new AiAgentService(this.db, this.userId, {workspaceId: this.workspaceId,});diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.tsindex 318c7ab3849..0c14fb5c48b 100644--- a/apps/server/src/services/taskLifecycle/index.ts+++ b/apps/server/src/services/taskLifecycle/index.ts@@ -228,6 +228,9 @@ export class TaskLifecycleService {}// 5. Default post-tick transition.+ // - Automation task whose own tick requested completion (the+ // instruction's end condition was verified as met) β 'completed',+ // retiring the loop now that the run has finished cleanly.// - Schedule-mode task that just consumed its final allowed run// (count β₯ maxExecutions) β park at 'completed' so the UI reflects// the cap immediately. Without this, a daily cron with@@ -272,7 +275,10 @@ export class TaskLifecycleService {} | null)?.completion?.requestedByOperationId === params.operationId;- if (+ if (currentTask.automationMode && completionRequestedByCurrentOperation) {+ log('automation task=%s retired by its own tick β end condition met', taskIdentifier);+ await this.completeTask(currentTask);+ } else if (currentTask.automationMode === 'schedule' &&(await this.scheduleCapReached(currentTask))) {@@ -287,14 +293,7 @@ export class TaskLifecycleService {await this.recordAutomationRecovery(currentTask);await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });} else if (!verifyBound && completionRequestedByCurrentOperation) {- if (currentTask.parentTaskId) {- await this.completeSubtask(currentTask);- } else {- await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'completed', {- completedAt: new Date(),- error: null,- });- }+ await this.completeTask(currentTask);} else if (!verifyBound && params.runTrigger === 'goal' && !currentTask.parentTaskId) {await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'completed', {completedAt: new Date(),@@ -307,7 +306,7 @@ export class TaskLifecycleService {error: null,});} else {- await this.completeSubtask(currentTask);+ await this.completeTask(currentTask);}} else if (!verifyBound && this.taskModel.shouldPauseOnTopicComplete(currentTask)) {await this.taskModel.updateStatus(taskId, 'paused', { error: null });@@ -550,14 +549,14 @@ export class TaskLifecycleService {}/**- * Settle a successful child task and advance its sibling dependency graph.+ * Settle a successful task and advance its dependency graph.** This mirrors the completion side effects of TaskService.updateStatus* without importing TaskService here (TaskRunner already depends on this* lifecycle service). The dynamic import keeps that module cycle out of* initialization while preserving the runner's single cascade implementation.*/- private async completeSubtask(task: TaskItem): Promise<void> {+ private async completeTask(task: TaskItem): Promise<void> {const completedTask = await this.taskModel.updateStatusIfCurrent(task.id,'running',@@ -568,13 +567,15 @@ export class TaskLifecycleService {},);if (!completedTask) {- log('subtask=%s no longer running β skipping completion cascade', task.identifier);+ log('task=%s no longer running β skipping completion cascade', task.identifier);return;}- const parentTask = await this.taskModel.findById(completedTask.parentTaskId!);- if (parentTask && this.taskModel.shouldPauseAfterComplete(parentTask, task.identifier)) {- await this.taskModel.updateStatus(parentTask.id, 'paused');+ if (completedTask.parentTaskId) {+ const parentTask = await this.taskModel.findById(completedTask.parentTaskId);+ if (parentTask && this.taskModel.shouldPauseAfterComplete(parentTask, task.identifier)) {+ await this.taskModel.updateStatus(parentTask.id, 'paused');+ }}const { TaskRunnerService } = await import('@/server/services/taskRunner');diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.tsindex 76c1754040b..693af5d577a 100644--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts@@ -282,6 +282,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {automationMode: null,context: { completion: { requestedByOperationId: 'op-1' } },});+ updateStatusIfCurrent.mockResolvedValue({ ...task, status: 'completed' });findById.mockResolvedValue(task);await service.onTopicComplete({@@ -297,35 +298,59 @@ describe('TaskLifecycleService.onTopicComplete', () => {error: null,});expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());+ expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');});- it('successful subtask β completes and unlocks downstream tasks instead of pausing', async () => {- const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });- const parentTask = baseTask({ id: 'parent-task', identifier: 'TASK-0' });- updateStatusIfCurrent.mockResolvedValue(task);- findById- .mockResolvedValueOnce(task)- .mockResolvedValueOnce(parentTask)- .mockResolvedValue(task);- (service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(false);+ it.each(['schedule', 'heartbeat'] as const)(+ '%s task whose own tick met the end condition β completed instead of re-armed',+ async (automationMode) => {+ const task = baseTask({+ automationMode,+ context: { completion: { requestedByOperationId: 'op-1' } },+ });+ updateStatusIfCurrent.mockResolvedValue({ ...task, status: 'completed' });+ findById.mockResolvedValueOnce(task).mockResolvedValue({ ...task, status: 'completed' });++ await service.onTopicComplete({+ operationId: 'op-1',+ reason: 'done',+ runTrigger: automationMode,+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {+ completedAt: expect.any(Date),+ error: null,+ });+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'scheduled', expect.anything());+ expect(fakeScheduler.scheduleNextTopic).not.toHaveBeenCalled();+ expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');+ },+ );++ it('automation task ignores a completion request left by an earlier tick', async () => {+ const task = baseTask({+ automationMode: 'schedule',+ context: { completion: { requestedByOperationId: 'op-old' } },+ });+ findById.mockResolvedValue(task);await service.onTopicComplete({operationId: 'op-1',reason: 'done',+ runTrigger: 'schedule',taskId: 'task-1',taskIdentifier: 'TASK-1',topicId: 'topic-1',});- expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {- completedAt: expect.any(Date),- error: null,- });- expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());- expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });+ expect(updateStatusIfCurrent).not.toHaveBeenCalled();});- it('successful subtask still honors an explicit parent after-completion checkpoint', async () => {+ it('successful subtask β completes and unlocks downstream tasks instead of pausing', async () => {const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });const parentTask = baseTask({ id: 'parent-task', identifier: 'TASK-0' });updateStatusIfCurrent.mockResolvedValue(task);@@ -333,7 +358,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {.mockResolvedValueOnce(task).mockResolvedValueOnce(parentTask).mockResolvedValue(task);- (service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(true);+ (service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(false);await service.onTopicComplete({operationId: 'op-1',@@ -347,10 +372,43 @@ describe('TaskLifecycleService.onTopicComplete', () => {completedAt: expect.any(Date),error: null,});- expect(updateStatus).toHaveBeenCalledWith('parent-task', 'paused');+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');});+ it.each([null, 'schedule', 'heartbeat'] as const)(+ 'successful %s subtask still honors an explicit parent after-completion checkpoint',+ async (automationMode) => {+ const task = baseTask({+ automationMode,+ context: automationMode ? { completion: { requestedByOperationId: 'op-1' } } : {},+ parentTaskId: 'parent-task',+ });+ const parentTask = baseTask({ id: 'parent-task', identifier: 'TASK-0' });+ updateStatusIfCurrent.mockResolvedValue(task);+ findById+ .mockResolvedValueOnce(task)+ .mockResolvedValueOnce(parentTask)+ .mockResolvedValue(task);+ (service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(true);++ await service.onTopicComplete({+ operationId: 'op-1',+ reason: 'done',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {+ completedAt: expect.any(Date),+ error: null,+ });+ expect(updateStatus).toHaveBeenCalledWith('parent-task', 'paused');+ expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');+ },+ );+it('successful subtask with an explicit topic-after checkpoint β pauses for review', async () => {const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });findById.mockResolvedValue(task);@@ -372,25 +430,32 @@ describe('TaskLifecycleService.onTopicComplete', () => {expect(cascadeOnCompletion).not.toHaveBeenCalled();});- it('late successful callback does not overwrite a child that is no longer running', async () => {- const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });- findById.mockResolvedValue(task);- updateStatusIfCurrent.mockResolvedValue(null);-- await service.onTopicComplete({- operationId: 'op-1',- reason: 'done',- taskId: 'task-1',- taskIdentifier: 'TASK-1',- topicId: 'topic-1',- });-- expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {- completedAt: expect.any(Date),- error: null,- });- expect(cascadeOnCompletion).not.toHaveBeenCalled();- });+ it.each([null, 'schedule', 'heartbeat'] as const)(+ 'late successful callback does not overwrite a %s child that is no longer running',+ async (automationMode) => {+ const task = baseTask({+ automationMode,+ context: automationMode ? { completion: { requestedByOperationId: 'op-1' } } : {},+ parentTaskId: 'parent-task',+ });+ findById.mockResolvedValue(task);+ updateStatusIfCurrent.mockResolvedValue(null);++ await service.onTopicComplete({+ operationId: 'op-1',+ reason: 'done',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {+ completedAt: expect.any(Date),+ error: null,+ });+ expect(cascadeOnCompletion).not.toHaveBeenCalled();+ },+ );it('non-automation task with shouldPauseOnTopicComplete=false β no status update', async () => {const task = baseTask({ automationMode: null });diff --git a/apps/server/src/services/taskRunner/taskSkill.test.ts b/apps/server/src/services/taskRunner/taskSkill.test.tsindex 3831adce3ff..3ec3e017c45 100644--- a/apps/server/src/services/taskRunner/taskSkill.test.ts+++ b/apps/server/src/services/taskRunner/taskSkill.test.ts@@ -39,4 +39,10 @@ describe('task skill instructions', () => {content.indexOf('Complete when done'),);});++ it('lets a tick retire the loop once the instruction end condition is met', () => {+ expect(content).toContain('**End conditions**');+ expect(content).toContain('Then run `lh task complete <id>` as your final step');+ expect(content).toContain('Do not ask the user to stop it instead');+ });});diff --git a/packages/builtin-skills/src/task/SKILL.md b/packages/builtin-skills/src/task/SKILL.mdindex ad03c1e2faa..18531716953 100644--- a/packages/builtin-skills/src/task/SKILL.md+++ b/packages/builtin-skills/src/task/SKILL.md@@ -1,4 +1,4 @@-\<task\_skill\_guides>+\<task_skill_guides>You are executing a task within the LobeHub task system. Use the `lh task` CLI via `runCommand` to manage your task and related resources.# Task Lifecycle@@ -50,5 +50,6 @@ You are executing a task within the LobeHub task system. Use the `lh task` CLI v- **Report progress**: Use `lh task comment` to log key milestones- **Respect dependencies**: Check `lh task tree` to understand task ordering- **Complete when done**: Use `lh task complete` when all deliverables are ready-- **Automation tasks are the exception β NEVER complete them**: a task with automation (heartbeat or schedule β shown as an `Automation:` line in the task context) is a recurring loop, and this run is one tick of it. NEVER run `lh task complete` (or set a terminal status via `lh task edit --status`) on that task: a terminal status cancels the in-flight run and permanently disarms the loop β no future tick will fire and nothing recovers it. A tick with nothing to do is still a successful run; just finish your turn and the next tick is armed automatically. Only the user retires a recurring task.- \</task\_skill\_guides>+- **Automation tasks are the exception β NEVER complete them**: a task with automation (heartbeat or schedule β shown as an `Automation:` line in the task context) is a recurring loop, and this run is one tick of it. NEVER run `lh task complete` (or set a terminal status via `lh task edit --status`) on that task: a terminal status permanently disarms the loop β no future tick will fire and nothing recovers it. A tick with nothing to do, or whose condition is not met yet, is still a successful run; just finish your turn and the next tick is armed automatically. Only the user retires a recurring task.+- **End conditions**: the one exception is when the instruction itself defines when the loop ends ("until X", "stop once Y", "after Z is merged") and this tick has verified it is now met. Then run `lh task complete <id>` as your final step: it is finalized after this run finishes and retires the loop. Do not ask the user to stop it instead β nobody reads a tick's reply in real time.+ \</task_skill_guides>diff --git a/packages/builtin-tool-task/src/systemRole.test.ts b/packages/builtin-tool-task/src/systemRole.test.tsindex d8c49a13dee..7247ada8c4d 100644--- a/packages/builtin-tool-task/src/systemRole.test.ts+++ b/packages/builtin-tool-task/src/systemRole.test.ts@@ -35,4 +35,11 @@ describe('systemPrompt', () => {// including 'backlog', so merely leaving the task unstarted is not enough.expect(systemPrompt).toContain('call updateTaskStatus(identifier, "paused") instead');});++ it('lets an automation tick complete its task only when the instruction end condition is met', () => {+ expect(systemPrompt).toContain('NEVER set it to canceled or failed');+ expect(systemPrompt).toContain('an end condition the instruction itself defines');+ expect(systemPrompt).toContain('Do not ask the user to stop the loop instead');+ expect(systemPrompt).not.toContain('NEVER call updateTaskStatus with "completed"');+ });});diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.tsindex 4d669209801..7611937f147 100644--- a/packages/builtin-tool-task/src/systemRole.ts+++ b/packages/builtin-tool-task/src/systemRole.ts@@ -22,7 +22,7 @@ Schedule fields (setTaskSchedule):After configuring a cron-based schedule (automationMode="schedule") on a task that is neither currently running nor already scheduled, start its schedule by default with updateTaskStatus(identifier, "scheduled") so it waits for the next scheduled run. When the user explicitly asks to keep it paused or as a draft, call updateTaskStatus(identifier, "paused") instead β a schedule-mode task left in any other non-terminal status is still picked up by the cron dispatcher. Never call updateTaskStatus on a currently running task just to arm the schedule β that interrupts the in-flight run, and the task returns to "scheduled" automatically once the run completes. A task already in "scheduled" stays armed after schedule edits β re-calling updateTaskStatus would reset its execution-count window. Do NOT call runTask just to start the schedule β runTask executes the task immediately.-An automation task (automationMode 'heartbeat' or 'schedule') is a recurring loop: each triggered run is one tick, and a tick with nothing to do is still a SUCCESSFUL tick β not a reason to close the task. When the task you are currently executing is an automation task, NEVER call updateTaskStatus with "completed" (or any other terminal status) on it: a terminal status cancels the in-flight run and permanently disarms the loop β no future tick will ever fire, and nothing recovers it automatically. Simply finish your turn; the scheduler parks the task back at 'scheduled' and arms the next tick on its own. Instructions like "end this run normally" or "treat as completed" refer to the current tick, not the task. Only the user retires a recurring task β either by doing it themselves or by explicitly asking you to stop the recurring task for good.+An automation task (automationMode 'heartbeat' or 'schedule') is a recurring loop: each triggered run is one tick, and a tick with nothing to do is still a SUCCESSFUL tick β not a reason to close the task. When the task you are currently executing is an automation task, do NOT complete it just because this tick is done, found nothing to do, or its condition is not met yet, and NEVER set it to canceled or failed: a terminal status permanently disarms the loop β no future tick will ever fire, and nothing recovers it automatically. Simply finish your turn; the scheduler parks the task back at 'scheduled' and arms the next tick on its own. Instructions like "end this run normally" or "treat as completed" refer to the current tick, not the task. The one exception is an end condition the instruction itself defines ("until X", "stop once Y", "after Z is merged"): when this tick has verified it is now met, call updateTaskStatus(identifier, "completed") on the current task as your final step β it is finalized after the run finishes and retires the loop. Do not ask the user to stop the loop instead; nobody reads a tick's reply in real time. Otherwise only the user retires a recurring task β either by doing it themselves or by explicitly asking you to stop the recurring task for good.Verify fields (setTaskVerify):- **enabled**: true to require a verify gate when the task completes, false to disable, null to clear@@ -47,4 +47,4 @@ When planning work:1. Create tasks for each major piece of work (use parentIdentifier to organize as subtasks)2. Use editTask with addDependencies to control execution order3. For executable tasks dispatched to an agent, use setTaskVerify to attach acceptance criteria before running them-4. Use updateTaskStatus to mark the current task as completed when you finish all work β unless it is an automation (heartbeat/schedule) task, which must stay non-terminal so its loop keeps running`;+4. Use updateTaskStatus to mark the current task as completed when you finish all work β unless it is an automation (heartbeat/schedule) task, which must stay non-terminal so its loop keeps running until the end condition in its instruction is met`;diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.tsindex 9d4d430e7ea..8a5c5591415 100644--- a/packages/prompts/src/prompts/task/index.test.ts+++ b/packages/prompts/src/prompts/task/index.test.ts@@ -130,7 +130,10 @@ describe('buildTaskRunPrompt', () => {);expect(result).toContain('Automation: heartbeat, every 4h');- expect(result).toContain('NEVER set this task to completed');+ expect(result).toContain('NEVER end the loop for that, and never set it to canceled or failed');+ // A tick may retire the loop only when the instruction's own end condition is met.+ expect(result).toContain('when the Instruction defines an end condition');+ expect(result).toContain('Do not ask the user to stop it instead');});it('should render a schedule automation line with the cron pattern and timezone', () => {@@ -150,7 +153,7 @@ describe('buildTaskRunPrompt', () => {);expect(result).toContain('Automation: cron "0 9 * * *" (Asia/Shanghai)');- expect(result).toContain('NEVER set this task to completed');+ expect(result).toContain('NEVER end the loop for that, and never set it to canceled or failed');});it('should not render an automation line for non-automation tasks', () => {diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.tsindex 164a233e3dc..04c95a75796 100644--- a/packages/prompts/src/prompts/task/index.ts+++ b/packages/prompts/src/prompts/task/index.ts@@ -703,7 +703,7 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin? `cron "${task.schedulePattern}" (${task.scheduleTimezone || 'UTC'})`: task.automationMode;taskLines.push(- `Automation: ${cadence} β this task is a recurring loop and this run is one tick of it. When the run ends, the next tick is armed automatically; a tick with nothing to do is still a successful run. NEVER set this task to completed (or any terminal status) β that permanently stops the loop.`,+ `Automation: ${cadence} β this task is a recurring loop and this run is one tick of it. When the run ends, the next tick is armed automatically; a tick with nothing to do, or whose condition is not met yet, is still a successful run β NEVER end the loop for that, and never set it to canceled or failed. The only exception: when the Instruction defines an end condition (e.g. "until X", "stop once Y", "after Z is done") and this tick has verified that it is now met, mark this task completed as your final step β that retires the loop once this run finishes. Do not ask the user to stop it instead.`,);}taskLines.push(`Instruction: ${task.instruction}`);