{"version":3,"sources":["../src/tools/builtin/task-tools.ts","../src/tools/builtin/task-state-processor.ts"],"names":["z","createTool","isThreadStateStore","idx"],"mappings":";;;;;AAiCO,IAAM,yBAAA,GAA4B;AAGlC,IAAM,cAAA,GAAiB;AAGvB,IAAM,eAAA,GAAkB;AAE/B,IAAM,iBAAA,GACJ,uIAAA;AAEF,IAAM,YAAA,GAAeA,KAClB,MAAA,EAAO,CACP,IAAI,CAAC,CAAA,CACL,SAAS,qGAAqG,CAAA;AAEjH,IAAM,mBAAA,GAAsBA,KAAE,MAAA,CAAO;AAAA,EACnC,EAAA,EAAI,aAAa,QAAA,EAAS;AAAA,EAC1B,OAAA,EAASA,KAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA,CAAE,SAAS,sEAAsE,CAAA;AAAA,EAC1G,MAAA,EAAQA,IAAA,CAAE,IAAA,CAAK,CAAC,SAAA,EAAW,eAAe,WAAW,CAAC,CAAA,CAAE,QAAA,CAAS,qBAAqB,CAAA;AAAA,EACtF,UAAA,EAAYA,KACT,MAAA,EAAO,CACP,IAAI,CAAC,CAAA,CACL,SAAS,oFAAoF;AAClG,CAAC,CAAA;AAED,IAAM,cAAA,GAAiB,oBAAoB,MAAA,CAAO;AAAA,EAChD,EAAA,EAAI;AACN,CAAC,CAAA;AAMD,IAAM,oBAAA,GAAuBA,KAAE,MAAA,CAAO;AAAA,EACpC,OAAA,EAASA,KAAE,MAAA,EAAO;AAAA,EAClB,KAAA,EAAOA,IAAA,CAAE,KAAA,CAAM,cAAc,CAAA;AAAA,EAC7B,OAAA,EAASA,KAAE,OAAA;AACb,CAAC,CAAA;AAED,IAAM,sBAAA,GAAyBA,KAAE,MAAA,CAAO;AAAA,EACtC,OAAOA,IAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,WAAA,EAAY;AAAA,EACpC,WAAWA,IAAA,CAAE,MAAA,EAAO,CAAE,GAAA,GAAM,WAAA,EAAY;AAAA,EACxC,YAAYA,IAAA,CAAE,MAAA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EAAa;AAAA,QAC7B,UAAA,EAAY,EAAE,KAAA,EAAO,YAAA,CAAa,MAAA,EAAO;AAAA,QACzC,UAAU,EAAE,KAAA,EAAO,EAAE,KAAA,EAAO,cAAa;AAAE,OAC7C;AAAA,IACF;AAMA,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,cAAA;AAAA,MACJ,QAAA,EAAU,oBAAoB,YAAY,CAAA;AAAA,MAC1C,IAAA,EAAM,OAAA;AAAA,MACN,OAAA,EAAS,kBAAA;AAAA,MACT,QAAA,EAAU,YAAY,GAAG,CAAA;AAAA,MACzB,KAAA,EAAO,EAAE,KAAA,EAAO,YAAA,EAAa;AAAA,MAC7B,KAAA,EAAO,EAAE,GAAA,EAAI;AAAA,MACb,UAAA,EAAY,EAAE,OAAA,EAAS,GAAA,CAAI,MAAA,EAAO;AAAA,MAClC,QAAA,EAAU,EAAE,KAAA,EAAO,EAAE,KAAA,EAAO,cAAa,EAAG,KAAA,EAAO,EAAE,GAAA,EAAI;AAAE,KAC7D;AAAA,EACF;AACF","file":"chunk-AOQKFEGW.cjs","sourcesContent":["import { z } from 'zod/v4';\n\nimport type { MastraUnion } from '../../action';\nimport type { RequestContext } from '../../request-context';\nimport type { TaskRecord } from '../../storage/domains/thread-state/base';\nimport { createTool } from '../tool';\n\n// =============================================================================\n// Task Tools (agent-agnostic)\n// =============================================================================\n//\n// The four task tools (`task_write`, `task_update`, `task_complete`,\n// `task_check`) manage a structured task list for an agent run. They are\n// agent-agnostic: they do not depend on the Harness. The task list is persisted\n// through the agent **state-signal** lane (see `task-state-processor.ts`), which\n// is cache-aware (the snapshot supersedes by cacheKey instead of accumulating)\n// and OM-aware (re-emitted when observational-memory truncation drops it).\n//\n// The task list is held in the thread-scoped `threadState` storage domain under\n// the `'task'` type, which is the source of truth. The task tools read/write it\n// synchronously within a run, and the task state processor projects it onto the\n// state-signal lane so the model sees it. With a durable `threadState` backend\n// (e.g. `@mastra/libsql`), the list survives a process restart.\n//\n// State signals + the task store require a memory-backed thread. When the run is\n// not memory backed (no threadId/resourceId), the tools no-op and tell the model\n// that task tracking requires agent memory.\n//\n// Within a single turn each write also surfaces the new list on the shared\n// `RequestContext` under `TASKS_REQUEST_CONTEXT_KEY`, so the state processor can\n// build a snapshot that reflects the latest mutation in the same step.\n\n/** RequestContext key under which the current working task list is surfaced within a turn. */\nexport const TASKS_REQUEST_CONTEXT_KEY = 'mastra:tasks';\n\n/** State-signal lane id used for the task list. */\nexport const TASKS_STATE_ID = 'tasks';\n\n/** `threadState` storage `type` namespace under which the task list is stored. */\nexport const TASK_STATE_TYPE = 'task';\n\nconst NO_MEMORY_MESSAGE =\n  'Task tools require agent memory (a memory-backed thread). No task was recorded. Configure the agent with Memory to use the task list.';\n\nconst taskIdSchema = z\n  .string()\n  .min(1)\n  .describe(\"Stable task identifier (for example, 'task_investigate_tests'). Keep this unchanged across updates.\");\n\nconst taskItemInputSchema = z.object({\n  id: taskIdSchema.optional(),\n  content: z.string().min(1).describe(\"Task description in imperative form (e.g., 'Fix authentication bug')\"),\n  status: z.enum(['pending', 'in_progress', 'completed']).describe('Current task status'),\n  activeForm: z\n    .string()\n    .min(1)\n    .describe(\"Present continuous form shown during execution (e.g., 'Fixing authentication bug')\"),\n});\n\nconst taskItemSchema = taskItemInputSchema.extend({\n  id: taskIdSchema,\n});\n\nexport type TaskItemInput = z.infer<typeof taskItemInputSchema>;\nexport type TaskItem = z.infer<typeof taskItemSchema>;\nexport type TaskItemSnapshot = TaskItem;\n\nconst taskToolResultSchema = z.object({\n  content: z.string(),\n  tasks: z.array(taskItemSchema),\n  isError: z.boolean(),\n});\n\nconst taskCheckSummarySchema = z.object({\n  total: z.number().int().nonnegative(),\n  completed: z.number().int().nonnegative(),\n  inProgress: z.number().int().nonnegative(),\n  pending: z.number().int().nonnegative(),\n  incomplete: z.number().int().nonnegative(),\n  hasTasks: z.boolean(),\n  allCompleted: z.boolean(),\n});\n\nconst taskCheckResultSchema = taskToolResultSchema.extend({\n  summary: taskCheckSummarySchema,\n  incompleteTasks: z.array(taskItemSchema),\n});\n\nexport type TaskCheckSummary = z.infer<typeof taskCheckSummarySchema>;\nexport type TaskCheckResult = z.infer<typeof taskCheckResultSchema>;\ntype TaskToolResult = z.infer<typeof taskToolResultSchema>;\n\nconst TASK_ID_SLUG_MAX_LENGTH = 48;\n\nfunction slugifyTaskContent(content: string): string {\n  let slug = '';\n  let pendingSeparator = false;\n\n  for (const char of content.toLowerCase()) {\n    const code = char.charCodeAt(0);\n    const isAsciiLetter = code >= 97 && code <= 122;\n    const isDigit = code >= 48 && code <= 57;\n\n    if (isAsciiLetter || isDigit) {\n      if (pendingSeparator && slug.length > 0 && slug.length < TASK_ID_SLUG_MAX_LENGTH) {\n        slug += '_';\n      }\n      if (slug.length >= TASK_ID_SLUG_MAX_LENGTH) break;\n      slug += char;\n      pendingSeparator = false;\n      continue;\n    }\n\n    pendingSeparator = slug.length > 0;\n  }\n\n  return slug;\n}\n\nfunction createDeterministicTaskId(task: TaskItemInput, occurrence: number): string {\n  const slug = slugifyTaskContent(task.content);\n  const suffix = occurrence > 1 ? `_${occurrence}` : '';\n  return `task_${slug || 'item'}${suffix}`;\n}\n\nfunction makeUniqueTaskId(id: string, usedIds: Set<string>, reservedIds: Set<string> = new Set()): string {\n  if (!usedIds.has(id) && !reservedIds.has(id)) return id;\n\n  let suffix = 2;\n  let nextId = `${id}_${suffix}`;\n  while (usedIds.has(nextId) || reservedIds.has(nextId)) {\n    suffix += 1;\n    nextId = `${id}_${suffix}`;\n  }\n  return nextId;\n}\n\nexport function assignTaskIds(tasks: TaskItemInput[], previousTasks: TaskItemSnapshot[] = []): TaskItemSnapshot[] {\n  const usedIds = new Set<string>();\n  const contentOccurrences = new Map<string, number>();\n  const omittedContentCounts = new Map<string, number>();\n  const explicitTaskIds = new Set(tasks.map(task => task.id).filter((id): id is string => Boolean(id)));\n  const reusablePreviousIds = new Map<number, string>();\n\n  for (const task of tasks) {\n    if (!task.id) {\n      omittedContentCounts.set(task.content, (omittedContentCounts.get(task.content) ?? 0) + 1);\n    }\n  }\n\n  tasks.forEach((task, index) => {\n    if (task.id || omittedContentCounts.get(task.content) !== 1) return;\n\n    const previousMatches = previousTasks.filter(\n      previous => previous.content === task.content && !explicitTaskIds.has(previous.id),\n    );\n    if (previousMatches.length === 1) {\n      reusablePreviousIds.set(index, previousMatches[0]!.id);\n    }\n  });\n\n  const reservedIds = new Set([...explicitTaskIds, ...reusablePreviousIds.values()]);\n\n  return tasks.map((task, index) => {\n    const contentOccurrence = (contentOccurrences.get(task.content) ?? 0) + 1;\n    contentOccurrences.set(task.content, contentOccurrence);\n\n    const fallbackId = createDeterministicTaskId(task, contentOccurrence);\n    const reusablePreviousId = reusablePreviousIds.get(index);\n\n    // If the model repeats an explicit ID in the same write, keep the first one\n    // and mint/reuse a stable fallback for the duplicate instead of failing the whole list.\n    const requestedId = task.id && !usedIds.has(task.id) ? task.id : undefined;\n    const id =\n      requestedId ??\n      (reusablePreviousId && !usedIds.has(reusablePreviousId)\n        ? reusablePreviousId\n        : makeUniqueTaskId(fallbackId, usedIds, reservedIds));\n    usedIds.add(id);\n\n    return {\n      id,\n      content: task.content,\n      status: task.status,\n      activeForm: task.activeForm,\n    };\n  });\n}\n\nexport function formatTaskListResult(tasks: TaskItemSnapshot[]): string {\n  const completed = tasks.filter(t => t.status === 'completed').length;\n  const inProgress = tasks.find(t => t.status === 'in_progress');\n  const total = tasks.length;\n\n  let summary = `Tasks updated: [${completed}/${total} completed]`;\n  if (inProgress) {\n    summary += `\\nCurrently: ${inProgress.activeForm} (${inProgress.id})`;\n  }\n  if (tasks.length > 0) {\n    summary += `\\nTask IDs:\\n${tasks.map(t => `- ${t.id}: ${t.content} (${t.status})`).join('\\n')}`;\n  }\n\n  return summary;\n}\n\nexport function summarizeTaskCheck(tasks: TaskItemSnapshot[]): {\n  summary: TaskCheckSummary;\n  inProgressTasks: TaskItemSnapshot[];\n  pendingTasks: TaskItemSnapshot[];\n  incompleteTasks: TaskItemSnapshot[];\n} {\n  const completedTasks = tasks.filter(task => task.status === 'completed');\n  const inProgressTasks = tasks.filter(task => task.status === 'in_progress');\n  const pendingTasks = tasks.filter(task => task.status === 'pending');\n  const incompleteTasks = [...inProgressTasks, ...pendingTasks];\n\n  return {\n    summary: {\n      total: tasks.length,\n      completed: completedTasks.length,\n      inProgress: inProgressTasks.length,\n      pending: pendingTasks.length,\n      incomplete: incompleteTasks.length,\n      hasTasks: tasks.length > 0,\n      allCompleted: tasks.length > 0 && incompleteTasks.length === 0,\n    },\n    inProgressTasks,\n    pendingTasks,\n    incompleteTasks,\n  };\n}\n\nfunction formatTaskCheckResult(taskCheck: ReturnType<typeof summarizeTaskCheck>): string {\n  const { summary, inProgressTasks, pendingTasks } = taskCheck;\n\n  if (!summary.hasTasks) {\n    return 'No tasks found. Consider using task_write to create a task list for complex work.';\n  }\n\n  let response = `Task Status: [${summary.completed}/${summary.total} completed]\\n`;\n  response += `- Completed: ${summary.completed}\\n`;\n  response += `- In Progress: ${summary.inProgress}\\n`;\n  response += `- Pending: ${summary.pending}\\n`;\n  response += `\\nAll tasks completed: ${summary.allCompleted ? 'YES' : 'NO'}`;\n\n  if (!summary.allCompleted) {\n    response += '\\n\\nIncomplete tasks:';\n    if (inProgressTasks.length > 0) {\n      response += '\\n\\nIn Progress:';\n      inProgressTasks.forEach(t => {\n        response += `\\n- ${t.id}: ${t.content}`;\n      });\n    }\n    if (pendingTasks.length > 0) {\n      response += '\\n\\nPending:';\n      pendingTasks.forEach(t => {\n        response += `\\n- ${t.id}: ${t.content}`;\n      });\n    }\n    response += '\\n\\nContinue working on these tasks before ending.';\n  }\n\n  return response;\n}\n\nexport function hasMultipleInProgress(tasks: TaskItemSnapshot[]): boolean {\n  return tasks.filter(task => task.status === 'in_progress').length > 1;\n}\n\nfunction multipleInProgressError(tasks: TaskItemSnapshot[]): TaskToolResult {\n  return {\n    content: 'Only one task can be in_progress at a time.',\n    tasks,\n    isError: true,\n  };\n}\n\nexport function demoteExtraInProgress(tasks: TaskItemSnapshot[], preferredIndex?: number): TaskItemSnapshot[] {\n  const inProgressIndices = tasks.reduce<number[]>((acc, t, i) => {\n    if (t.status === 'in_progress') acc.push(i);\n    return acc;\n  }, []);\n  if (inProgressIndices.length <= 1) return tasks;\n  const keepIndex =\n    preferredIndex !== undefined && inProgressIndices.includes(preferredIndex)\n      ? preferredIndex\n      : inProgressIndices[inProgressIndices.length - 1]!;\n  return tasks.map((t, i) =>\n    t.status === 'in_progress' && i !== keepIndex ? { ...t, status: 'pending' as const } : t,\n  );\n}\n\nfunction formatAvailableTaskIds(tasks: TaskItemSnapshot[]): string {\n  if (tasks.length === 0) return 'No tasks are currently tracked.';\n  return `Available task IDs:\\n${tasks.map(t => `- ${t.id}: ${t.content} (${t.status})`).join('\\n')}`;\n}\n\n// -----------------------------------------------------------------------------\n// Task list read/write through the thread-scoped `threadState` store\n// -----------------------------------------------------------------------------\n//\n// The `tasks` storage domain is the source of truth for the task list. It is\n// thread-scoped and read/written synchronously within a run, so a `task_update`\n// observes exactly the tasks a prior `task_write` produced in the same turn\n// (the store survives the per-step serialization that drops RequestContext\n// mutations). The task state processor projects this list onto the state-signal\n// lane so the model sees it (cache-aware, OM-safe). The processor reads the\n// within-turn list from `RequestContext` (set on each write) so the snapshot\n// reflects the latest mutation in the same step it is computed.\n\n// Typed in terms of the storage domain's `TaskRecord` (the storage contract).\n// The `threadState` domain deliberately defines its own `TaskRecord` so the\n// storage layer does not depend on this tools package; the tools operate on\n// `TaskItemSnapshot`. The two must stay structurally identical — typing the\n// store methods with `TaskRecord` here means any drift between the shapes breaks\n// the build at the read/write call sites below, rather than silently passing\n// the duck-typed `isThreadStateStore` guard.\ntype ResolvedThreadStateStore = {\n  getState<T = unknown>(args: { threadId: string; type: string }): Promise<T | undefined>;\n  setState(args: { threadId: string; type: string; value: TaskRecord[] }): Promise<void>;\n};\n\ninterface TaskToolAgentContext {\n  threadId?: string;\n  resourceId?: string;\n}\n\ninterface TaskToolContext {\n  agent?: TaskToolAgentContext;\n  requestContext?: RequestContext;\n  // The agent's Mastra instance, used to resolve the thread-scoped state store.\n  mastra?: MastraUnion;\n}\n\n/** True when the run is memory-backed (state signals + the task store require a thread + resource). */\nfunction isMemoryBacked(agent: TaskToolAgentContext | undefined): boolean {\n  return Boolean(agent?.threadId && agent?.resourceId);\n}\n\nfunction isThreadStateStore(value: unknown): value is ResolvedThreadStateStore {\n  return (\n    !!value &&\n    typeof (value as ResolvedThreadStateStore).getState === 'function' &&\n    typeof (value as ResolvedThreadStateStore).setState === 'function'\n  );\n}\n\n/** Resolve the thread-scoped state store from the agent's Mastra storage, if available. */\nasync function resolveTaskStore(context: TaskToolContext): Promise<ResolvedThreadStateStore | undefined> {\n  const store = await context.mastra?.getStorage?.()?.getStore('threadState');\n  return isThreadStateStore(store) ? store : undefined;\n}\n\n/**\n * Optional Harness display bridge. When the run carries a Harness request\n * context, emit a `task_updated` event so the Harness can update its display\n * state and any pinned task UI. This is display-only — the task list itself\n * lives in the `threadState` store + state-signal lane, not in Harness state.\n */\ninterface HarnessDisplayBridge {\n  emitEvent?: (event: { type: 'task_updated'; tasks: TaskItemSnapshot[] }) => void;\n}\n\nfunction emitTaskDisplayUpdate(requestContext: RequestContext | undefined, tasks: TaskItemSnapshot[]): void {\n  const harnessCtx = requestContext?.get('harness') as HarnessDisplayBridge | undefined;\n  harnessCtx?.emitEvent?.({ type: 'task_updated', tasks });\n}\n\nfunction noMemoryResult(): TaskToolResult {\n  return { content: NO_MEMORY_MESSAGE, tasks: [], isError: true };\n}\n\nfunction noMemoryCheckResult(): TaskCheckResult {\n  const emptyCheck = summarizeTaskCheck([]);\n  return {\n    content: NO_MEMORY_MESSAGE,\n    tasks: [],\n    summary: emptyCheck.summary,\n    incompleteTasks: emptyCheck.incompleteTasks,\n    isError: true,\n  };\n}\n\n/** Read the current task list for the thread from the store. */\nasync function readTaskStore(context: TaskToolContext): Promise<TaskItemSnapshot[]> {\n  const store = await resolveTaskStore(context);\n  const threadId = context.agent?.threadId;\n  if (!store || !threadId) return [];\n  const tasks = await store.getState<TaskRecord[]>({ threadId, type: TASK_STATE_TYPE });\n  return Array.isArray(tasks) ? tasks : [];\n}\n\n/**\n * Apply a mutation to the current task list: read from the store, mutate,\n * persist back to the store, surface the list to the state processor via\n * `RequestContext`, and emit the Harness display update.\n */\nasync function applyTaskMutation(\n  context: TaskToolContext,\n  mutation: (currentTasks: TaskItemSnapshot[]) => TaskToolResult,\n): Promise<TaskToolResult> {\n  const store = await resolveTaskStore(context);\n  const threadId = context.agent?.threadId;\n  if (!store || !threadId) return noMemoryResult();\n\n  const currentTasks = await readTaskStore(context);\n  const result = mutation(currentTasks);\n  if (!result.isError) {\n    await store.setState({ threadId, type: TASK_STATE_TYPE, value: result.tasks });\n    // Surface the new list to the task state processor for this step's snapshot.\n    context.requestContext?.set(TASKS_REQUEST_CONTEXT_KEY, result.tasks);\n    emitTaskDisplayUpdate(context.requestContext, result.tasks);\n  }\n  return result;\n}\n\n/**\n * Built-in, agent-agnostic tool: manage a structured task list for the run.\n * Full-replacement semantics: each call replaces the entire task list.\n * Prefer task_update or task_complete for changing existing tasks by ID.\n */\nexport const taskWriteTool = createTool({\n  id: 'task_write',\n  description: `Create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.\n\nUsage:\n- Use this to create the initial task list or replace the whole list after replanning\n- Pass the FULL task list each time this tool is called (replaces the previous list)\n- Each task has: id (stable identifier), content (imperative), status (pending, in_progress, or completed), activeForm (present continuous)\n- IDs must be unique. If duplicate explicit IDs are provided, the duplicate task is returned with a generated fallback ID\n- Keep task IDs stable across updates. If omitted, IDs are generated and returned in the tool result\n- When an ID is omitted while rewriting an existing list, one unambiguous matching task may reuse an existing ID\n- Prefer single-task update tools when they are available\n- Mark tasks in_progress BEFORE starting work (only ONE at a time)\n- Mark tasks completed IMMEDIATELY after finishing\n- Use this for multi-step tasks requiring 3+ distinct actions\n\nStates:\n- pending: Not yet started\n- in_progress: Currently working on (limit to ONE)\n- completed: Finished successfully`,\n  inputSchema: z.object({\n    tasks: z.array(taskItemInputSchema).describe('The complete updated task list'),\n  }),\n  outputSchema: taskToolResultSchema,\n  execute: async ({ tasks }, context) => {\n    try {\n      if (!isMemoryBacked(context?.agent)) return noMemoryResult();\n\n      return applyTaskMutation(context, currentTasks => {\n        const normalizedTasks = assignTaskIds(tasks, currentTasks);\n        if (hasMultipleInProgress(normalizedTasks)) {\n          return multipleInProgressError(currentTasks);\n        }\n\n        return {\n          content: formatTaskListResult(normalizedTasks),\n          tasks: normalizedTasks,\n          isError: false,\n        };\n      });\n    } catch (error) {\n      const msg = error instanceof Error ? error.message : 'Unknown error';\n      return {\n        content: `Failed to update tasks: ${msg}`,\n        tasks: [],\n        isError: true,\n      };\n    }\n  },\n});\n\n/**\n * Built-in, agent-agnostic tool: update one tracked task by stable ID.\n */\nexport const taskUpdateTool = createTool({\n  id: 'task_update',\n  description: `Update one task in the current task list by stable ID. Use this for targeted changes to one existing task.\n\nUsage:\n- Provide the task ID returned by the task-list tools\n- Include only the fields that changed\n- Use status to move a task between pending, in_progress, and completed\n- Use task_complete when only marking a task completed\n- If the ID is unknown, the tool returns an error with available task IDs`,\n  inputSchema: z\n    .object({\n      id: taskIdSchema,\n      content: z.string().min(1).optional().describe('New task description in imperative form'),\n      status: z.enum(['pending', 'in_progress', 'completed']).optional().describe('New task status'),\n      activeForm: z.string().min(1).optional().describe('New present continuous form shown during execution'),\n    })\n    .refine(input => input.content !== undefined || input.status !== undefined || input.activeForm !== undefined, {\n      message: 'Provide at least one field to update.',\n    }),\n  outputSchema: taskToolResultSchema,\n  execute: async ({ id, content, status, activeForm }, context) => {\n    try {\n      if (!isMemoryBacked(context?.agent)) return noMemoryResult();\n\n      return applyTaskMutation(context, tasks => {\n        const taskIndex = tasks.findIndex(task => task.id === id);\n        if (taskIndex === -1) {\n          return {\n            content: `Task not found: ${id}\\n\\n${formatAvailableTaskIds(tasks)}`,\n            tasks,\n            isError: true,\n          };\n        }\n\n        const updatedTasks = demoteExtraInProgress(\n          tasks.map((task, index) =>\n            index === taskIndex\n              ? {\n                  ...task,\n                  ...(content !== undefined ? { content } : {}),\n                  ...(status !== undefined ? { status } : {}),\n                  ...(activeForm !== undefined ? { activeForm } : {}),\n                }\n              : task,\n          ),\n          taskIndex,\n        );\n\n        return {\n          content: formatTaskListResult(updatedTasks),\n          tasks: updatedTasks,\n          isError: false,\n        };\n      });\n    } catch (error) {\n      const msg = error instanceof Error ? error.message : 'Unknown error';\n      return {\n        content: `Failed to update task: ${msg}`,\n        tasks: [],\n        isError: true,\n      };\n    }\n  },\n});\n\n/**\n * Built-in, agent-agnostic tool: mark one tracked task completed by stable ID.\n */\nexport const taskCompleteTool = createTool({\n  id: 'task_complete',\n  description: `Mark one task completed by stable ID. Use this when one tracked task is finished.\n\nUsage:\n- Provide the task ID returned by the task-list tools\n- If the ID is unknown, the tool returns an error with available task IDs`,\n  inputSchema: z.object({\n    id: taskIdSchema,\n  }),\n  outputSchema: taskToolResultSchema,\n  execute: async ({ id }, context) => {\n    try {\n      if (!isMemoryBacked(context?.agent)) return noMemoryResult();\n\n      return applyTaskMutation(context, tasks => {\n        const taskIndex = tasks.findIndex(task => task.id === id);\n        if (taskIndex === -1) {\n          return {\n            content: `Task not found: ${id}\\n\\n${formatAvailableTaskIds(tasks)}`,\n            tasks,\n            isError: true,\n          };\n        }\n\n        const updatedTasks = tasks.map((task, index) =>\n          index === taskIndex\n            ? {\n                ...task,\n                status: 'completed' as const,\n              }\n            : task,\n        );\n\n        return {\n          content: formatTaskListResult(updatedTasks),\n          tasks: updatedTasks,\n          isError: false,\n        };\n      });\n    } catch (error) {\n      const msg = error instanceof Error ? error.message : 'Unknown error';\n      return {\n        content: `Failed to complete task: ${msg}`,\n        tasks: [],\n        isError: true,\n      };\n    }\n  },\n});\n\n/**\n * Built-in, agent-agnostic tool: check the completion status of the task list.\n * Helps the agent determine if all tasks are completed before ending work.\n */\nexport const taskCheckTool = createTool({\n  id: 'task_check',\n  description: `Check the completion status of your current task list. Use this before finishing tracked work to ensure all tasks are completed.\n\nReturns:\n- Human-readable content summary with task counts and incomplete task IDs\n- Structured task list snapshot with stable IDs\n- summary object with total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted\n- incompleteTasks array for tasks that still need work\n\nsummary.allCompleted is true only when at least one tracked task exists and every tracked task is completed. If no tasks exist, summary.hasTasks is false and summary.allCompleted is false.`,\n  inputSchema: z.object({}), // No input needed\n  outputSchema: taskCheckResultSchema,\n  execute: async ({}, context) => {\n    try {\n      if (!isMemoryBacked(context?.agent)) return noMemoryCheckResult();\n\n      const tasks = await readTaskStore(context);\n      const taskCheck = summarizeTaskCheck(tasks);\n\n      return {\n        content: formatTaskCheckResult(taskCheck),\n        tasks,\n        summary: taskCheck.summary,\n        incompleteTasks: taskCheck.incompleteTasks,\n        isError: false,\n      };\n    } catch (error) {\n      const msg = error instanceof Error ? error.message : 'Unknown error';\n      const emptyCheck = summarizeTaskCheck([]);\n      return {\n        content: `Failed to check tasks: ${msg}`,\n        tasks: [],\n        summary: emptyCheck.summary,\n        incompleteTasks: emptyCheck.incompleteTasks,\n        isError: true,\n      };\n    }\n  },\n});\n\nfunction isTaskItemArray(value: unknown): value is TaskItemSnapshot[] {\n  return (\n    Array.isArray(value) &&\n    value.every(\n      item =>\n        item &&\n        typeof item === 'object' &&\n        typeof (item as Record<string, unknown>).id === 'string' &&\n        typeof (item as Record<string, unknown>).content === 'string' &&\n        typeof (item as Record<string, unknown>).status === 'string' &&\n        typeof (item as Record<string, unknown>).activeForm === 'string',\n    )\n  );\n}\n\n/**\n * Read the within-turn task list carried on the `RequestContext` by the task\n * tools (used by the task state processor to build the snapshot for the current\n * step). Returns `undefined` when no task tool ran this turn, so the processor\n * can fall back to the durable task store.\n */\nexport function getTasksFromRequestContext(requestContext: RequestContext | undefined): TaskItemSnapshot[] | undefined {\n  const carried = requestContext?.get(TASKS_REQUEST_CONTEXT_KEY);\n  return isTaskItemArray(carried) ? carried : undefined;\n}\n","import type { Mastra } from '../../mastra';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult } from '../../processors/index';\nimport type { TaskRecord } from '../../storage/domains/thread-state/base';\nimport { getTasksFromRequestContext, TASKS_STATE_ID, TASK_STATE_TYPE } from './task-tools';\nimport type { TaskItemSnapshot } from './task-tools';\n\n// Typed in terms of the storage domain's `TaskRecord` (see the matching note in\n// task-tools.ts): the processor reads the durable list and projects it as\n// `TaskItemSnapshot`, so this assignment enforces that the two shapes stay\n// structurally identical.\ntype ResolvedThreadStateStore = {\n  getState<T = unknown>(args: { threadId: string; type: string }): Promise<T | undefined>;\n};\n\nfunction isThreadStateStore(value: unknown): value is ResolvedThreadStateStore {\n  return !!value && typeof (value as ResolvedThreadStateStore).getState === 'function';\n}\n\n// =============================================================================\n// Task state processor\n// =============================================================================\n//\n// Carries the agent's task list on the agent state-signal lane (`stateId:\n// 'tasks'`) using a **delta-first** projection (modelled on working memory):\n//\n//  - The first emission (and every compaction) is a full **snapshot**\n//    (`<current-task-list>`). Subsequent mutations emit a small **delta**\n//    (`<task-list-update>`) carrying only that turn's add/remove/update ops, so\n//    a large list is not re-sent in full on every change.\n//  - The base snapshot + each delta stay in the window as separate signal\n//    messages; the model reads the base list and folds the deltas onto it. To\n//    bound window growth we re-snapshot once `DELTA_SNAPSHOT_CAP` deltas have\n//    accumulated (compaction).\n//  - **cache-aware**: signals supersede by cacheKey rather than being appended\n//    to the cached system-prompt prefix, so task updates do not invalidate it.\n//  - **OM-aware**: when observational memory drops the base snapshot from the\n//    window (`contextWindow.hasSnapshot === false`), a fresh snapshot is emitted\n//    (deltas are meaningless without their base), so the agent never loses its\n//    tasks.\n//\n// The task list itself lives in the thread-scoped `tasks` storage domain (the\n// TaskStore); this processor projects it onto the model context. State signals\n// require a memory-backed thread; the runtime enforces this. The task tools\n// no-op when the run is not memory backed, so the processor only ever sees task\n// state on memory-backed runs.\n\n// Renders the inner lines of the task list. The state-signal framework wraps\n// (and XML-escapes) this string inside the signal's `tagName`\n// (`current-task-list`), so this returns only the body — wrapping it in the tag\n// here would double-wrap and escape the markup the model sees. An empty list\n// returns an empty string so the framework emits `<current-task-list count=\"0\" />`.\nfunction renderTaskList(tasks: TaskItemSnapshot[]): string {\n  if (tasks.length === 0) return '';\n  const lines = tasks.map(task => {\n    const icon = task.status === 'completed' ? '✓' : task.status === 'in_progress' ? '▸' : '○';\n    return `  ${icon} [${task.status}] {id: ${task.id}} ${task.content}`;\n  });\n  return `\\n${lines.join('\\n')}\\n`;\n}\n\n// Re-snapshot once this many deltas have accumulated since the last snapshot.\n// Pure-delta mode keeps each emission tiny, but the base snapshot + every delta\n// stay in the window as separate signal messages until the next snapshot, so we\n// periodically compact back to a fresh snapshot to bound window growth. Also\n// re-snapshot whenever observational memory drops the base from the window\n// (deltas are meaningless without their base).\nconst DELTA_SNAPSHOT_CAP = 10;\n\n// A single task-list change carried on a `delta`-mode signal.\ntype TaskDeltaOp =\n  | { op: 'add'; task: TaskItemSnapshot }\n  | { op: 'remove'; id: string }\n  | { op: 'update'; task: TaskItemSnapshot };\n\nfunction getTasksFromSnapshot(snapshot: ComputeStateSignalArgs['lastSnapshot']): TaskItemSnapshot[] {\n  const value = snapshot?.metadata?.value as { tasks?: unknown } | undefined;\n  const tasks = value?.tasks;\n  if (Array.isArray(tasks)) return tasks as TaskItemSnapshot[];\n  return [];\n}\n\nfunction getOpsFromDelta(signal: { metadata?: Record<string, unknown> } | undefined): TaskDeltaOp[] {\n  const delta = signal?.metadata?.delta as { ops?: unknown } | undefined;\n  const ops = delta?.ops;\n  return Array.isArray(ops) ? (ops as TaskDeltaOp[]) : [];\n}\n\n// Apply a delta's ops onto a working list to reconstruct the state the model\n// currently believes. Adds/updates that reference an existing id replace it in\n// place; new adds append; removes drop by id.\nfunction applyOps(tasks: TaskItemSnapshot[], ops: TaskDeltaOp[]): TaskItemSnapshot[] {\n  const next = tasks.slice();\n  for (const op of ops) {\n    if (op.op === 'remove') {\n      const idx = next.findIndex(t => t.id === op.id);\n      if (idx >= 0) next.splice(idx, 1);\n      continue;\n    }\n    const task = op.task;\n    const idx = next.findIndex(t => t.id === task.id);\n    if (idx >= 0) next[idx] = task;\n    else next.push(task);\n  }\n  return next;\n}\n\n// The state the model currently sees: the last snapshot with every\n// delta-since-snapshot applied in order.\nfunction effectivePriorTasks(args: ComputeStateSignalArgs): TaskItemSnapshot[] {\n  let tasks = getTasksFromSnapshot(args.lastSnapshot);\n  for (const delta of args.deltasSinceSnapshot ?? []) {\n    tasks = applyOps(tasks, getOpsFromDelta(delta));\n  }\n  return tasks;\n}\n\n// Length-prefix each field so a value containing the `:` / `|` delimiters cannot\n// shift a boundary and collide with a different task list (e.g. content \"a:b\"\n// vs id \"a\" + status \"b\"). Each field is encoded as `<byteLength>:<value>`.\nfunction lp(value: string): string {\n  return `${value.length}:${value}`;\n}\n\nfunction taskFingerprint(t: TaskItemSnapshot): string {\n  return `${lp(t.id)}${lp(t.status)}${lp(t.content)}${lp(t.activeForm)}`;\n}\n\nfunction stableTasksCacheKey(tasks: TaskItemSnapshot[]): string {\n  return `tasks:${tasks.map(taskFingerprint).join('|')}`;\n}\n\n// Diff the prior list against the current one into add/remove/update ops. An\n// `update` is emitted when a task with the same id has any field changed.\nfunction diffTasks(prior: TaskItemSnapshot[], current: TaskItemSnapshot[]): TaskDeltaOp[] {\n  const ops: TaskDeltaOp[] = [];\n  const priorById = new Map(prior.map(t => [t.id, t]));\n  const currentIds = new Set(current.map(t => t.id));\n\n  for (const task of current) {\n    const before = priorById.get(task.id);\n    if (!before) ops.push({ op: 'add', task });\n    else if (taskFingerprint(before) !== taskFingerprint(task)) ops.push({ op: 'update', task });\n  }\n  for (const task of prior) {\n    if (!currentIds.has(task.id)) ops.push({ op: 'remove', id: task.id });\n  }\n  return ops;\n}\n\n// Render the ops a `delta` signal carries into the lines the model reads. The\n// framework wraps this in the signal's `tagName` (`task-list-update`).\nfunction renderDelta(ops: TaskDeltaOp[]): string {\n  const lines = ops.map(op => {\n    if (op.op === 'remove') return `  − removed {id: ${op.id}}`;\n    const { task } = op;\n    const icon = task.status === 'completed' ? '✓' : task.status === 'in_progress' ? '▸' : '○';\n    const verb = op.op === 'add' ? '+' : icon;\n    return `  ${verb} {id: ${task.id}} [${task.status}] ${task.content}`;\n  });\n  return `\\n${lines.join('\\n')}\\n`;\n}\n\n/**\n * Input processor that publishes the agent's task list as a state signal.\n *\n * Add it to an agent's `inputProcessors` alongside the task tools so the task\n * list is carried across turns and survives observational-memory truncation.\n */\nexport class TaskStateProcessor {\n  readonly id = 'task-state';\n  readonly stateId = TASKS_STATE_ID;\n\n  /**\n   * The Mastra instance this processor is registered with, used to resolve the\n   * thread-scoped task store. Set by the agent/Mastra runtime via\n   * `__registerMastra`.\n   *\n   * We implement this hook inline rather than extending `BaseProcessor`: a\n   * *value* import of `BaseProcessor` from `processors/index` pulls that module's\n   * runtime graph, which forms an initialization cycle through this tools module.\n   * At the test entry point that surfaces as `TypeError: Class extends value\n   * undefined` (BaseProcessor is not yet initialized when this class evaluates).\n   * Implementing the (structurally trivial) hook here keeps all imports from\n   * `processors/index` type-only, so there is no runtime edge and no cycle.\n   */\n  protected mastra?: Mastra<any, any, any, any, any, any, any, any, any, any>;\n\n  __registerMastra(mastra: Mastra<any, any, any, any, any, any, any, any, any, any>): void {\n    this.mastra = mastra;\n  }\n\n  private async resolveTaskStore(): Promise<ResolvedThreadStateStore | undefined> {\n    const store = await this.mastra?.getStorage?.()?.getStore('threadState');\n    return isThreadStateStore(store) ? store : undefined;\n  }\n\n  async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n    // The state the model currently sees: the last snapshot with every\n    // delta-since-snapshot applied. We diff against this (not just the base\n    // snapshot) so an unchanged turn after several deltas emits nothing.\n    const priorTasks = effectivePriorTasks(args);\n\n    // Current task list for this turn: the working list a task tool surfaced on\n    // the shared RequestContext this step (reflects the latest mutation), else\n    // the durable TaskStore for the thread, else the prior state.\n    const carried = getTasksFromRequestContext(args.requestContext);\n    let currentTasks: TaskItemSnapshot[];\n    if (carried !== undefined) {\n      currentTasks = carried;\n    } else {\n      const store = await this.resolveTaskStore();\n      const stored = store\n        ? await store.getState<TaskRecord[]>({ threadId: args.threadId, type: TASK_STATE_TYPE })\n        : undefined;\n      currentTasks = Array.isArray(stored) ? stored : priorTasks;\n    }\n\n    // Nothing to track yet.\n    if (currentTasks.length === 0 && priorTasks.length === 0) return;\n\n    const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n    const deltaCount = args.deltasSinceSnapshot?.length ?? 0;\n    const ops = diffTasks(priorTasks, currentTasks);\n\n    // No change and the base snapshot is still in the window: emit nothing so\n    // the cached prefix and the active window stay stable.\n    if (ops.length === 0 && hasBase) return;\n\n    // Emit a fresh snapshot (compaction) when there is no usable base in the\n    // window (first emission, or OM dropped it — deltas are meaningless without\n    // their base), or when enough deltas have accumulated. Otherwise emit a\n    // small delta carrying only this turn's ops.\n    const mustSnapshot = !hasBase || deltaCount >= DELTA_SNAPSHOT_CAP;\n\n    if (mustSnapshot) {\n      return {\n        id: TASKS_STATE_ID,\n        cacheKey: stableTasksCacheKey(currentTasks),\n        mode: 'snapshot',\n        // `current-task-list` is the signal's own tag. The framework wraps and\n        // escapes `contents` inside it, so `renderTaskList` returns only the\n        // inner lines — no inline tag here, or the model would see\n        // double-wrapped, XML-escaped markup.\n        tagName: 'current-task-list',\n        contents: renderTaskList(currentTasks),\n        value: { tasks: currentTasks },\n        attributes: { count: currentTasks.length },\n        metadata: { value: { tasks: currentTasks } },\n      };\n    }\n\n    // Delta: the model reads the base `<current-task-list>` plus each\n    // `<task-list-update>` and folds them together. `value` carries the full\n    // resulting list for programmatic consumers / recovery; `delta.ops` carries\n    // the structured change so the next turn can reconstruct the effective state.\n    return {\n      id: TASKS_STATE_ID,\n      cacheKey: stableTasksCacheKey(currentTasks),\n      mode: 'delta',\n      tagName: 'task-list-update',\n      contents: renderDelta(ops),\n      value: { tasks: currentTasks },\n      delta: { ops },\n      attributes: { changes: ops.length },\n      metadata: { value: { tasks: currentTasks }, delta: { ops } },\n    };\n  }\n}\n"]}