π€― 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-schedule): enforce maxExecutions cap and block sub-10min heartbeat (#14865)
Arvin Xuf94e4f46a4bd
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.tsindex 9173b6f30cb..ce46cae485a 100644--- a/packages/builtin-tool-task/src/manifest.ts+++ b/packages/builtin-tool-task/src/manifest.ts@@ -313,7 +313,7 @@ export const TaskManifest: BuiltinToolManifest = {},heartbeatInterval: {description:- 'Periodic execution interval in seconds (heartbeat mode). Pass 0 to clear the interval. Recommend β₯600s.',+ 'Periodic execution interval in seconds (heartbeat mode). Pass 0 to clear the interval. Minimum 600s (10 minutes); the server rejects positive values below 600.',type: 'number',},identifier: {diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.tsindex 012f190e8b0..d7b0f814525 100644--- a/packages/database/src/models/__tests__/taskTopic.test.ts+++ b/packages/database/src/models/__tests__/taskTopic.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { topics, users } from '../../schemas';+import { taskTopics, topics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { TaskModel } from '../task';import { TaskTopicModel } from '../taskTopic';@@ -198,6 +198,81 @@ describe('TaskTopicModel', () => {});});+ describe('countByTask', () => {+ it('counts every topic for the task when no options are passed', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const topicModel = new TaskTopicModel(serverDB, userId);+ const task = await taskModel.create({ instruction: 'Test' });+ await createTopic('tpc_c1');+ await createTopic('tpc_c2');++ await topicModel.add(task.id, 'tpc_c1', { seq: 1 });+ await topicModel.add(task.id, 'tpc_c2', { seq: 2 });++ expect(await topicModel.countByTask(task.id)).toBe(2);+ });++ it('only counts topics created on/after `since` when provided', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const topicModel = new TaskTopicModel(serverDB, userId);+ const task = await taskModel.create({ instruction: 'Test' });+ await createTopic('tpc_old');+ await createTopic('tpc_new');++ // Age the first topic 10 minutes into the past so the `since` window+ // (5 minutes ago) excludes it but includes the just-inserted second one.+ await topicModel.add(task.id, 'tpc_old', { seq: 1 });+ const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);+ await serverDB+ .update(taskTopics)+ .set({ createdAt: tenMinutesAgo })+ .where(eq(taskTopics.topicId, 'tpc_old'));++ await topicModel.add(task.id, 'tpc_new', { seq: 2 });++ const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);+ expect(await topicModel.countByTask(task.id, { since: fiveMinutesAgo })).toBe(1);+ expect(await topicModel.countByTask(task.id)).toBe(2);+ });++ it('does not bleed across tasks', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const topicModel = new TaskTopicModel(serverDB, userId);+ const task1 = await taskModel.create({ instruction: 'A' });+ const task2 = await taskModel.create({ instruction: 'B' });+ await createTopic('tpc_a1');+ await createTopic('tpc_b1');++ await topicModel.add(task1.id, 'tpc_a1', { seq: 1 });+ await topicModel.add(task2.id, 'tpc_b1', { seq: 1 });++ expect(await topicModel.countByTask(task1.id)).toBe(1);+ expect(await topicModel.countByTask(task2.id)).toBe(1);+ });++ it('does not count topics owned by a different user', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const topicModel = new TaskTopicModel(serverDB, userId);+ const otherTopicModel = new TaskTopicModel(serverDB, userId2);+ const task = await taskModel.create({ instruction: 'Test' });+ await createTopic('tpc_mine');+ await createTopic('tpc_theirs', userId2);++ await topicModel.add(task.id, 'tpc_mine', { seq: 1 });+ // Directly insert a row attributed to userId2 on the same task to prove+ // the scope is `userId`, not just `taskId`.+ await serverDB.insert(taskTopics).values({+ seq: 2,+ taskId: task.id,+ topicId: 'tpc_theirs',+ userId: userId2,+ });++ expect(await topicModel.countByTask(task.id)).toBe(1);+ expect(await otherTopicModel.countByTask(task.id)).toBe(1);+ });+ });+describe('findWithHandoff', () => {it('should return completedAt joined from topics', async () => {const taskModel = new TaskModel(serverDB, userId);diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 31a8f4f44b0..4a90b7138d0 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -1,5 +1,5 @@import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';-import { and, desc, eq, sql } from 'drizzle-orm';+import { and, count, desc, eq, gte, sql } from 'drizzle-orm';import type { TaskTopicItem } from '../schemas/task';import { tasks, taskTopics } from '../schemas/task';@@ -200,6 +200,17 @@ export class TaskTopicModel {return result[0] || null;}+ async countByTask(taskId: string, options?: { since?: Date }): Promise<number> {+ const conditions = [eq(taskTopics.taskId, taskId), eq(taskTopics.userId, this.userId)];+ if (options?.since) conditions.push(gte(taskTopics.createdAt, options.since));++ const rows = await this.db+ .select({ value: count() })+ .from(taskTopics)+ .where(and(...conditions));+ return rows[0]?.value ?? 0;+ }+async findByTaskId(taskId: string): Promise<TaskTopicItem[]> {return this.db.select()diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.tsindex d87fec8861d..a8c74e00dc2 100644--- a/src/server/routers/lambda/task.ts+++ b/src/server/routers/lambda/task.ts@@ -54,7 +54,16 @@ const updateSchema = z.object({config: z.record(z.unknown()).optional(),context: z.record(z.unknown()).optional(),description: z.string().optional(),- heartbeatInterval: z.number().min(0).optional(),+ // 0 clears the interval (disables heartbeat); any positive value must be+ // β₯600s (10 min) to match the UI minimum and prevent sub-minute ticks if an+ // LLM calls setTaskSchedule with a tiny number.+ heartbeatInterval: z+ .number()+ .int()+ .refine((v) => v === 0 || v >= 600, {+ message: 'heartbeatInterval must be 0 (disabled) or at least 600 seconds (10 minutes)',+ })+ .optional(),heartbeatTimeout: z.number().min(1).nullable().optional(),instruction: z.string().optional(),name: z.string().optional(),diff --git a/src/server/services/task/index.test.ts b/src/server/services/task/index.test.tsindex aaf0dc46102..7a5dd970d08 100644--- a/src/server/services/task/index.test.ts+++ b/src/server/services/task/index.test.ts@@ -31,6 +31,14 @@ vi.mock('@/database/models/user', () => ({UserModel: { findByIds: vi.fn().mockResolvedValue([]) },}));+// AiAgentService pulls in ~14 sub-dependencies in its constructor; mock it so+// the running-status branch in updateStatus doesn't drag them in.+vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(() => ({+ interruptTask: vi.fn(),+ })),+}));+describe('TaskService', () => {const db = {} as LobeChatDatabase;const userId = 'user-1';@@ -52,10 +60,13 @@ describe('TaskService', () => {getTreePinnedDocuments: vi.fn(),resolve: vi.fn(),update: vi.fn(),+ updateContext: vi.fn(),updateStatus: vi.fn(),};const mockTaskTopicModel = {+ cancelIfRunning: vi.fn(),+ findByTaskId: vi.fn(),findWithHandoff: vi.fn(),timeoutRunning: vi.fn(),};@@ -1256,4 +1267,87 @@ describe('TaskService', () => {expect(result?.activities?.[1].type).toBe('brief');});});++ describe('updateStatus / scheduleStartedAt', () => {+ const baseTask = (overrides: Partial<Record<string, unknown>> = {}) => ({+ automationMode: 'schedule',+ context: {},+ id: 'task-1',+ identifier: 'T-1',+ parentTaskId: null,+ status: 'backlog',+ ...overrides,+ });++ it('stamps scheduleStartedAt when a user starts a schedule (backlog β scheduled)', async () => {+ const prev = baseTask({ status: 'backlog', automationMode: 'schedule' });+ const next = baseTask({ status: 'scheduled', automationMode: 'schedule' });+ mockTaskModel.resolve.mockResolvedValue(prev);+ mockTaskModel.updateStatus.mockResolvedValue(next);++ const service = new TaskService(db, userId);+ await service.updateStatus({ id: 'T-1', status: 'scheduled' as any });++ expect(mockTaskModel.updateContext).toHaveBeenCalledTimes(1);+ expect(mockTaskModel.updateContext).toHaveBeenCalledWith('task-1', {+ scheduler: { scheduleStartedAt: expect.any(String) },+ });+ const stamped = (mockTaskModel.updateContext.mock.calls[0]![1] as any).scheduler+ .scheduleStartedAt as string;+ expect(() => new Date(stamped).toISOString()).not.toThrow();+ });++ it('does NOT stamp on the cron loop natural cycle (running β scheduled)', async () => {+ // taskLifecycle parks finished ticks at 'scheduled' via taskModel.updateStatus,+ // bypassing the service layer; the only way it reaches the service is when a+ // user explicitly transitions. Either way, prev='running' must NOT reset the+ // counter window β otherwise every successful tick would zero out the cap.+ const prev = baseTask({ status: 'running', automationMode: 'schedule' });+ const next = baseTask({ status: 'scheduled', automationMode: 'schedule' });+ mockTaskModel.resolve.mockResolvedValue(prev);+ mockTaskModel.updateStatus.mockResolvedValue(next);+ mockTaskTopicModel.findByTaskId.mockResolvedValue([]);++ const service = new TaskService(db, userId);+ await service.updateStatus({ id: 'T-1', status: 'scheduled' as any });++ expect(mockTaskModel.updateContext).not.toHaveBeenCalled();+ });++ it('does NOT stamp for heartbeat-mode tasks', async () => {+ const prev = baseTask({ status: 'backlog', automationMode: 'heartbeat' });+ const next = baseTask({ status: 'scheduled', automationMode: 'heartbeat' });+ mockTaskModel.resolve.mockResolvedValue(prev);+ mockTaskModel.updateStatus.mockResolvedValue(next);++ const service = new TaskService(db, userId);+ await service.updateStatus({ id: 'T-1', status: 'scheduled' as any });++ expect(mockTaskModel.updateContext).not.toHaveBeenCalled();+ });++ it('does NOT stamp when the new status is not scheduled', async () => {+ const prev = baseTask({ status: 'backlog' });+ const next = baseTask({ status: 'paused' });+ mockTaskModel.resolve.mockResolvedValue(prev);+ mockTaskModel.updateStatus.mockResolvedValue(next);++ const service = new TaskService(db, userId);+ await service.updateStatus({ id: 'T-1', status: 'paused' as any });++ expect(mockTaskModel.updateContext).not.toHaveBeenCalled();+ });++ it('stamps on user-initiated restart (paused β scheduled)', async () => {+ const prev = baseTask({ status: 'paused', automationMode: 'schedule' });+ const next = baseTask({ status: 'scheduled', automationMode: 'schedule' });+ mockTaskModel.resolve.mockResolvedValue(prev);+ mockTaskModel.updateStatus.mockResolvedValue(next);++ const service = new TaskService(db, userId);+ await service.updateStatus({ id: 'T-1', status: 'scheduled' as any });++ expect(mockTaskModel.updateContext).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/src/server/services/task/index.ts b/src/server/services/task/index.tsindex 6a22895adc4..325be52f60b 100644--- a/src/server/services/task/index.ts+++ b/src/server/services/task/index.ts@@ -260,6 +260,22 @@ export class TaskService {const task = await this.taskModel.updateStatus(resolved.id, status, extra);if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ // Stamp the schedule run-count window each time the user (re)starts a+ // scheduled task. The cron dispatcher itself flips a task running β+ // scheduled on every tick, so we exclude that natural cycle by only+ // resetting when the previous status was NOT 'running'. This lets+ // `runScheduleTick` enforce `config.schedule.maxExecutions` by counting+ // task_topics created since this timestamp.+ if (+ status === 'scheduled' &&+ task.automationMode === 'schedule' &&+ resolved.status !== 'running'+ ) {+ await this.taskModel.updateContext(task.id, {+ scheduler: { scheduleStartedAt: new Date().toISOString() },+ });+ }+const unlocked: string[] = [];const paused: string[] = [];let allSubtasksDone = false;diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.tsindex 3582a538c6c..eb561760783 100644--- a/src/server/services/taskLifecycle/index.ts+++ b/src/server/services/taskLifecycle/index.ts@@ -148,17 +148,30 @@ export class TaskLifecycleService {}// 5. Default post-tick transition.- // - Automation tasks (heartbeat / schedule) loop running β scheduled, so- // a successful tick parks the task at 'scheduled' to wait for the next- // tick. They never auto-pause on success β only `reason === 'error'`- // below puts them in 'paused' for human attention.- // - Non-automation tasks fall back to the legacy "pause for user review"- // behavior: a 'result' brief from the agent is a *proposal* of- // completion, and the user must explicitly approve via the brief action- // to transition to 'completed'. Auto-complete only happens via the- // Judge path above.+ // - 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+ // maxExecutions=1 would advertise itself as 'scheduled' for+ // another 24h before the pre-tick check in runScheduleTick+ // noticed.+ // - Other automation tasks (heartbeat, schedule under cap) loop+ // running β scheduled, so a successful tick parks them at+ // 'scheduled' to wait for the next tick. They never auto-pause+ // on success β only `reason === 'error'` below puts them in+ // 'paused' for human attention.+ // - Non-automation tasks fall back to the legacy "pause for user+ // review" behavior: a 'result' brief from the agent is a+ // *proposal* of completion, and the user must explicitly approve+ // via the brief action to transition to 'completed'. Auto-complete+ // only happens via the Judge path above.if (currentTask) {- if (currentTask.automationMode) {+ if (+ currentTask.automationMode === 'schedule' &&+ (await this.scheduleCapReached(currentTask))+ ) {+ log('cap reached for task=%s β marking completed post-tick', taskIdentifier);+ await this.taskModel.updateStatus(taskId, 'completed', { completedAt: new Date() });+ } else if (currentTask.automationMode) {await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });} else if (this.taskModel.shouldPauseOnTopicComplete(currentTask)) {await this.taskModel.updateStatus(taskId, 'paused', { error: null });@@ -191,6 +204,41 @@ export class TaskLifecycleService {if (finalTask) await this.maybeRearmHeartbeat(finalTask, reason);}+ /**+ * Has the task already consumed every allowed scheduled execution?+ *+ * Counts `task_topics` rows created since `context.scheduler.scheduleStartedAt`+ * (stamped by `TaskService.updateStatus` on user-initiated start/restart) and+ * compares against `config.schedule.maxExecutions`. Returns false when:+ * - the task isn't in schedule mode+ * - no cap is configured (null / 0)+ * - no `scheduleStartedAt` is stamped (pre-PR tasks fall through; enforcement+ * begins only after the user pauses + restarts)+ *+ * Mirrors the pre-tick check in `runScheduleTick` so a daily cron with+ * `maxExecutions=1` doesn't sit in `scheduled` for 24h after consuming+ * its single allowed run.+ */+ private async scheduleCapReached(task: TaskItem): Promise<boolean> {+ if (task.automationMode !== 'schedule') return false;+ const scheduleConfig =+ ((task.config as { schedule?: { maxExecutions?: number | null } } | null) ?? {}).schedule ??+ {};+ const maxExecutions = scheduleConfig.maxExecutions ?? null;+ if (maxExecutions == null || maxExecutions <= 0) return false;++ const scheduler =+ ((task.context as { scheduler?: { scheduleStartedAt?: string } } | null) ?? {}).scheduler ??+ {};+ const startedAtIso = scheduler.scheduleStartedAt;+ if (!startedAtIso) return false;++ const runCount = await this.taskTopicModel.countByTask(task.id, {+ since: new Date(startedAtIso),+ });+ return runCount >= maxExecutions;+ }+/*** Re-arm the next heartbeat tick after `onTopicComplete`.*diff --git a/src/server/services/taskLifecycle/onTopicComplete.test.ts b/src/server/services/taskLifecycle/onTopicComplete.test.tsindex 7b5629d820c..133b1b8df3e 100644--- a/src/server/services/taskLifecycle/onTopicComplete.test.ts+++ b/src/server/services/taskLifecycle/onTopicComplete.test.ts@@ -99,6 +99,81 @@ describe('TaskLifecycleService.onTopicComplete', () => {expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });});+ it('schedule-mode task under maxExecutions still parks at "scheduled"', async () => {+ const task = baseTask({+ automationMode: 'schedule',+ config: { schedule: { maxExecutions: 10 } } as any,+ context: {+ scheduler: { scheduleStartedAt: new Date('2026-05-01T00:00:00Z').toISOString() },+ } as any,+ });+ findById.mockResolvedValue(task);+ (service as any).taskTopicModel.countByTask = vi.fn().mockResolvedValue(3);++ await service.onTopicComplete({+ operationId: 'op-1',+ reason: 'done',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'completed', expect.anything());+ });++ it('schedule-mode task at maxExecutions parks at "completed" instead of "scheduled"', async () => {+ // The reviewer-flagged P2 case: a daily cron with maxExecutions=1+ // would otherwise sit in `scheduled` for 24h after the only allowed+ // tick before the next pre-tick check noticed the cap.+ const task = baseTask({+ automationMode: 'schedule',+ config: { schedule: { maxExecutions: 1 } } as any,+ context: {+ scheduler: { scheduleStartedAt: new Date('2026-05-01T00:00:00Z').toISOString() },+ } as any,+ });+ findById.mockResolvedValue(task);+ (service as any).taskTopicModel.countByTask = vi.fn().mockResolvedValue(1);++ await service.onTopicComplete({+ operationId: 'op-1',+ reason: 'done',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(updateStatus).toHaveBeenCalledWith('task-1', 'completed', {+ completedAt: expect.any(Date),+ });+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'scheduled', expect.anything());+ });++ it('schedule-mode task with no scheduleStartedAt (pre-PR) still parks at "scheduled"', async () => {+ const task = baseTask({+ automationMode: 'schedule',+ config: { schedule: { maxExecutions: 1 } } as any,+ context: {} as any,+ });+ findById.mockResolvedValue(task);+ const countByTask = vi.fn().mockResolvedValue(99);+ (service as any).taskTopicModel.countByTask = countByTask;++ await service.onTopicComplete({+ operationId: 'op-1',+ reason: 'done',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ // Without scheduleStartedAt the helper short-circuits before querying,+ // and the task falls through to the normal scheduled-park branch.+ expect(countByTask).not.toHaveBeenCalled();+ expect(updateStatus).toHaveBeenCalledWith('task-1', 'scheduled', { error: null });+ });+it('non-automation task with default checkpoint β status="paused" (legacy behavior)', async () => {const task = baseTask({ automationMode: null });findById.mockResolvedValue(task);diff --git a/src/server/services/taskRunner/scheduleTick.test.ts b/src/server/services/taskRunner/scheduleTick.test.tsnew file mode 100644index 00000000000..445bb33c2e9--- /dev/null+++ b/src/server/services/taskRunner/scheduleTick.test.ts@@ -0,0 +1,174 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { BriefModel } from '@/database/models/brief';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';++import { TaskRunnerService } from './index';+import { runScheduleTick } from './scheduleTick';++vi.mock('@/database/server', () => ({+ getServerDB: vi.fn().mockResolvedValue({}),+}));++vi.mock('@/database/models/task', () => ({+ TaskModel: vi.fn(),+}));++vi.mock('@/database/models/taskTopic', () => ({+ TaskTopicModel: vi.fn(),+}));++vi.mock('@/database/models/brief', () => ({+ BriefModel: vi.fn(),+}));++vi.mock('./index', () => ({+ TaskRunnerService: vi.fn(),+}));++describe('runScheduleTick', () => {+ const taskId = 'task-1';+ const userId = 'user-1';++ const mockTaskModel = {+ findById: vi.fn(),+ updateStatus: vi.fn(),+ };+ const mockTaskTopicModel = {+ countByTask: vi.fn(),+ };+ const mockBriefModel = {+ hasUnresolvedUrgentByTask: vi.fn().mockResolvedValue(false),+ };+ const mockRunner = {+ runTask: vi.fn(),+ };++ const baseTask = (overrides: Partial<Record<string, unknown>> = {}) => ({+ automationMode: 'schedule',+ config: {},+ context: { scheduler: { scheduleStartedAt: new Date('2026-05-01T00:00:00Z').toISOString() } },+ id: taskId,+ identifier: 'T-1',+ schedulePattern: '*/5 * * * *',+ status: 'scheduled',+ ...overrides,+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(false);+ (TaskModel as any).mockImplementation(() => mockTaskModel);+ (TaskTopicModel as any).mockImplementation(() => mockTaskTopicModel);+ (BriefModel as any).mockImplementation(() => mockBriefModel);+ (TaskRunnerService as any).mockImplementation(() => mockRunner);+ });++ it('skips not-found tasks', async () => {+ mockTaskModel.findById.mockResolvedValue(null);++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: false, reason: 'not-found' });+ expect(mockRunner.runTask).not.toHaveBeenCalled();+ });++ it('skips when automationMode has been changed away from schedule', async () => {+ mockTaskModel.findById.mockResolvedValue(baseTask({ automationMode: 'heartbeat' }));++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: false, reason: 'mode-changed' });+ expect(mockRunner.runTask).not.toHaveBeenCalled();+ });++ it('skips terminal / paused tasks before checking maxExecutions', async () => {+ mockTaskModel.findById.mockResolvedValue(baseTask({ status: 'paused' }));++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: false, reason: 'paused' });+ expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();+ });++ it('runs the task when no maxExecutions is configured', async () => {+ mockTaskModel.findById.mockResolvedValue(baseTask({ config: {} }));+ mockRunner.runTask.mockResolvedValue(undefined);++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });+ expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();+ expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId });+ });++ it('runs the task when the run count is still under maxExecutions', async () => {+ mockTaskModel.findById.mockResolvedValue(+ baseTask({ config: { schedule: { maxExecutions: 10 } } }),+ );+ mockTaskTopicModel.countByTask.mockResolvedValue(7);+ mockRunner.runTask.mockResolvedValue(undefined);++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });+ expect(mockTaskTopicModel.countByTask).toHaveBeenCalledWith(taskId, {+ since: new Date('2026-05-01T00:00:00Z'),+ });+ expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId });+ expect(mockTaskModel.updateStatus).not.toHaveBeenCalled();+ });++ it('marks the task completed and skips when the run count has reached maxExecutions', async () => {+ mockTaskModel.findById.mockResolvedValue(+ baseTask({ config: { schedule: { maxExecutions: 10 } } }),+ );+ mockTaskTopicModel.countByTask.mockResolvedValue(10);++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: false, reason: 'max-executions-reached' });+ expect(mockRunner.runTask).not.toHaveBeenCalled();+ expect(mockTaskModel.updateStatus).toHaveBeenCalledWith(taskId, 'completed', {+ completedAt: expect.any(Date),+ });+ });++ it('falls back to running when maxExecutions is set but scheduleStartedAt is missing', async () => {+ // Pre-existing scheduled tasks (created before this PR) won't have a+ // scheduleStartedAt stamp. They should still tick normally; the cap will+ // start enforcing once the user pauses + restarts.+ mockTaskModel.findById.mockResolvedValue(+ baseTask({ config: { schedule: { maxExecutions: 10 } }, context: {} }),+ );+ mockRunner.runTask.mockResolvedValue(undefined);++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: true, taskIdentifier: 'T-1' });+ expect(mockTaskTopicModel.countByTask).not.toHaveBeenCalled();+ expect(mockRunner.runTask).toHaveBeenCalled();+ });++ it('returns in-flight when runTask raises a CONFLICT', async () => {+ mockTaskModel.findById.mockResolvedValue(baseTask({ config: {} }));+ mockRunner.runTask.mockRejectedValue(new TRPCError({ code: 'CONFLICT', message: 'busy' }));++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: false, reason: 'in-flight' });+ });++ it('skips when a human is waiting on an urgent brief', async () => {+ mockTaskModel.findById.mockResolvedValue(baseTask({ config: {} }));+ mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(true);++ const outcome = await runScheduleTick(taskId, userId);++ expect(outcome).toEqual({ ran: false, reason: 'human-waiting' });+ expect(mockRunner.runTask).not.toHaveBeenCalled();+ });+});diff --git a/src/server/services/taskRunner/scheduleTick.ts b/src/server/services/taskRunner/scheduleTick.tsindex 9f1fd7c6126..a49e00aa175 100644--- a/src/server/services/taskRunner/scheduleTick.ts+++ b/src/server/services/taskRunner/scheduleTick.ts@@ -3,6 +3,7 @@ import debug from 'debug';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';import { getServerDB } from '@/database/server';import { TaskRunnerService } from './index';@@ -19,6 +20,7 @@ export type ScheduleTickOutcome =export type ScheduleTickSkipReason =| 'human-waiting'| 'in-flight'+ | 'max-executions-reached'| 'mode-changed'| 'no-pattern'| 'not-found'@@ -67,6 +69,42 @@ export async function runScheduleTick(return { ran: false, reason: 'human-waiting' };}+ // Defense-in-depth cap check.+ //+ // `TaskLifecycleService.onTopicComplete` is the primary stopper β it parks+ // a schedule-mode task at `completed` (instead of `scheduled`) the instant+ // it consumes its final allowed run, so the UI reflects the cap immediately+ // even on low-frequency crons (e.g. daily, maxExecutions=1).+ //+ // This pre-tick recheck catches the residual edge cases the lifecycle+ // hook can miss: a crashed tick that never reached onTopicComplete; a+ // user editing maxExecutions downward after the cap is already exceeded;+ // or stale `scheduled` rows from older code paths.+ const scheduleConfig =+ ((task.config as { schedule?: { maxExecutions?: number | null } } | null) ?? {}).schedule ?? {};+ const maxExecutions = scheduleConfig.maxExecutions ?? null;+ if (maxExecutions != null && maxExecutions > 0) {+ const scheduler =+ ((task.context as { scheduler?: { scheduleStartedAt?: string } } | null) ?? {}).scheduler ??+ {};+ const startedAtIso = scheduler.scheduleStartedAt;+ if (startedAtIso) {+ const startedAt = new Date(startedAtIso);+ const topicModel = new TaskTopicModel(db, userId);+ const runCount = await topicModel.countByTask(taskId, { since: startedAt });+ if (runCount >= maxExecutions) {+ log(+ 'skip task=%s reason=max-executions-reached (%d/%d) β marking completed',+ taskId,+ runCount,+ maxExecutions,+ );+ await taskModel.updateStatus(taskId, 'completed', { completedAt: new Date() });+ return { ran: false, reason: 'max-executions-reached' };+ }+ }+ }+const runner = new TaskRunnerService(db, userId);try {await runner.runTask({ taskId });