{"version":3,"file":"validate-DCK3zDet.cjs","names":["inputSchemaOf","collectTemplateStepIds","z"],"sources":["../src/workflows/dynamic/graph.ts","../src/workflows/dynamic/validate/refs.ts","../src/workflows/dynamic/validate/schema-utils.ts","../src/workflows/dynamic/validate/types.ts","../src/workflows/dynamic/validate/repair-actions.ts","../src/workflows/dynamic/mapping-config.ts","../src/workflows/dynamic/validate/schema-flow.ts","../src/workflows/dynamic/json-schema-to-zod.ts","../src/workflows/dynamic/validate/schemas.ts","../src/workflows/dynamic/validate/structure.ts","../src/workflows/dynamic/validate/index.ts"],"sourcesContent":["/**\n * Shared typed walker over a serialized workflow graph. Every consumer that\n * needs \"all the leaf entries in this graph\" (schema validation, reference\n * validation, nested-workflow dependency collection) goes through this one\n * function, so recursion into container entries lives in exactly one place\n * and is exhaustiveness-checked against `ValidatableStepFlowEntry`, which\n * covers both persisted rows and wire-shaped authoring submissions.\n */\nimport type { SerializedSingleStepEntry } from '../types';\nimport type { ValidatableStepFlowEntry } from './validate/types';\n\n/**\n * Invoke `visit` for every single-step (leaf) entry in the graph, recursing\n * into `parallel`/`conditional` children and `loop`/`foreach` bodies.\n *\n * Does NOT recurse into a nested workflow's inlined `serializedStepFlow` —\n * a nested workflow's own graph is validated when that workflow is added.\n * `sleep`/`sleepUntil` entries carry no references or schemas and are skipped.\n */\nexport function forEachSingleStepEntry(\n  entries: readonly ValidatableStepFlowEntry[],\n  visit: (entry: SerializedSingleStepEntry) => void,\n): void {\n  for (const entry of entries) {\n    switch (entry.type) {\n      case 'step':\n      case 'agent':\n      case 'tool':\n      case 'classifier':\n      case 'mapping':\n      case 'workflow':\n        visit(entry);\n        break;\n      case 'parallel':\n      case 'conditional':\n        entry.steps.forEach(visit);\n        break;\n      case 'loop':\n      case 'foreach':\n        visit(entry.step);\n        break;\n      case 'sleep':\n      case 'sleepUntil':\n        break;\n      default: {\n        const _exhaustive: never = entry;\n        void _exhaustive;\n      }\n    }\n  }\n}\n\n/**\n * Collect the ids of every nested workflow referenced by a stored graph.\n * Used by boot-time loading to hydrate stored definitions in dependency order.\n */\nexport function collectNestedWorkflowIds(graph: readonly ValidatableStepFlowEntry[]): Set<string> {\n  const out = new Set<string>();\n  forEachSingleStepEntry(graph, entry => {\n    if (entry.type === 'workflow') out.add(entry.workflowId);\n  });\n  return out;\n}\n\n/**\n * Same traversal as {@link forEachSingleStepEntry} but reports each leaf's\n * position as a dotted path (`graph.2`, `graph.2.steps.0`, `graph.2.step`) —\n * the path contract shared by validation issues and the Studio draft UI.\n *\n * Accepts the wider {@link ValidatableStepFlowEntry} union so both persisted\n * graphs and wire-shaped authoring submissions can be walked.\n */\nexport function forEachSingleStepEntryWithPath(\n  entries: readonly ValidatableStepFlowEntry[],\n  visit: (entry: SerializedSingleStepEntry, path: string) => void,\n): void {\n  entries.forEach((entry, index) => {\n    const path = `graph.${index}`;\n    switch (entry.type) {\n      case 'step':\n      case 'agent':\n      case 'tool':\n      case 'classifier':\n      case 'mapping':\n      case 'workflow':\n        visit(entry, path);\n        break;\n      case 'parallel':\n      case 'conditional':\n        entry.steps.forEach((child, childIndex) => visit(child, `${path}.steps.${childIndex}`));\n        break;\n      case 'loop':\n      case 'foreach':\n        visit(entry.step, `${path}.step`);\n        break;\n      case 'sleep':\n      case 'sleepUntil':\n        break;\n      default: {\n        const _exhaustive: never = entry;\n        void _exhaustive;\n      }\n    }\n  });\n}\n","/**\n * Reference checks against a caller-supplied registry index.\n *\n * Checks are gated per kind: a kind whose key is absent from the index is\n * skipped entirely, so callers that cannot enumerate (say) workflows never\n * produce false missing-reference issues. Mis-classified references get swap\n * hints (agent id that is actually a registered tool, and vice versa).\n *\n * `type: 'step'` descriptors are intentionally not checked — they resolve\n * late against the live Mastra instance at rehydration time.\n */\nimport { forEachSingleStepEntryWithPath } from '../graph';\nimport type { WorkflowRegistryIndex, WorkflowValidationInput, WorkflowValidationIssue } from './types';\n\nexport function validateWorkflowRefs(\n  def: WorkflowValidationInput,\n  index: WorkflowRegistryIndex,\n): WorkflowValidationIssue[] {\n  const issues: WorkflowValidationIssue[] = [];\n  forEachSingleStepEntryWithPath(def.graph, (entry, path) => {\n    switch (entry.type) {\n      case 'agent': {\n        if (!index.agents || index.agents[entry.agentId]) return;\n        issues.push({\n          code: 'missing-reference',\n          path: `${path}.agentId`,\n          message: index.tools?.[entry.agentId]\n            ? `Step \"${entry.id}\" declares { type: \"agent\", agentId: \"${entry.agentId}\" } but \"${entry.agentId}\" is a registered TOOL, not an agent. Change this entry to { type: \"tool\", toolId: \"${entry.agentId}\" }.`\n            : `Step \"${entry.id}\" declares agentId \"${entry.agentId}\" which is not a registered agent.`,\n        });\n        return;\n      }\n      case 'tool': {\n        if (!index.tools || index.tools[entry.toolId]) return;\n        issues.push({\n          code: 'missing-reference',\n          path: `${path}.toolId`,\n          message: index.agents?.[entry.toolId]\n            ? `Step \"${entry.id}\" declares { type: \"tool\", toolId: \"${entry.toolId}\" } but \"${entry.toolId}\" is a registered AGENT, not a tool. Change this entry to { type: \"agent\", agentId: \"${entry.toolId}\" }.`\n            : `Step \"${entry.id}\" declares toolId \"${entry.toolId}\" which is not a registered tool.`,\n        });\n        return;\n      }\n      case 'classifier': {\n        if (!index.classifiers || index.classifiers[entry.classifierId]) return;\n        const available = Object.keys(index.classifiers);\n        issues.push({\n          code: 'missing-reference',\n          path: `${path}.classifierId`,\n          message: `Step \"${entry.id}\" declares classifierId \"${entry.classifierId}\" which is not a registered classifier.${available.length ? ` Available classifiers: ${available.join(', ')}.` : ''}`,\n        });\n        return;\n      }\n      case 'workflow': {\n        // Self-references are a structural issue (`self-reference`), and the\n        // registry may well contain a previous version of this very workflow\n        // on upsert — skip the existence check for them.\n        if (entry.workflowId === def.id) return;\n        if (!index.workflows || index.workflows[entry.workflowId]) return;\n        issues.push({\n          code: 'missing-reference',\n          path: `${path}.workflowId`,\n          message: `Step \"${entry.id}\" declares workflowId \"${entry.workflowId}\" which is not a registered workflow.`,\n        });\n        return;\n      }\n      default:\n        return;\n    }\n  });\n  return issues;\n}\n","/**\n * Pure JSON-Schema helpers shared by schema-flow analysis and mapping-config\n * analysis. Everything here is best-effort and three-valued: a check only\n * reports `incompatible` when it can prove a mismatch, so absent or partial\n * schemas degrade to `unknown` instead of producing false positives.\n */\nimport { standardSchemaToJSONSchema, toStandardSchema } from '../../../schema';\nimport type { JsonSchema } from '../json-schema-to-zod';\n\nexport type SchemaCompatibility = 'compatible' | 'incompatible' | 'unknown';\n\n/**\n * Best-effort conversion of a live (Zod / standard) schema to JSON Schema for\n * registry-index building. Unconvertible or absent schemas yield `undefined`\n * (\"unknown\"), which schema-flow treats as never-incompatible.\n */\nexport function toJsonSchemaOrUndefined(schema: unknown): JsonSchema | undefined {\n  if (schema === undefined || schema === null) return undefined;\n  try {\n    return standardSchemaToJSONSchema(toStandardSchema(schema)) as JsonSchema;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** True when both types are numeric, i.e. some mix of `integer` and `number`. */\nfunction isNumeric(sourceType: string, destinationType: string): boolean {\n  const numeric = new Set(['integer', 'number']);\n  return numeric.has(sourceType) && numeric.has(destinationType);\n}\n\n/**\n * Structural compatibility of `source` output feeding a `destination` input.\n * Recurses through array items and object properties; a destination `required`\n * key missing from the source is a proven incompatibility.\n */\nexport function schemaCompatibility(source: unknown, destination: unknown): SchemaCompatibility {\n  if (!isRecord(source) || !isRecord(destination)) return 'unknown';\n  const sourceType = typeof source.type === 'string' ? source.type : undefined;\n  const destinationType = typeof destination.type === 'string' ? destination.type : undefined;\n  if (!sourceType || !destinationType) return 'unknown';\n  // `integer` is a subtype of `number`, so a whole-number source satisfies a\n  // `number` destination. The reverse isn't provably wrong either: a `number`\n  // source can hold whole values at runtime, and this function only reports\n  // incompatibilities it can prove.\n  if (sourceType !== destinationType && !isNumeric(sourceType, destinationType)) return 'incompatible';\n  if (destinationType === 'array') return schemaCompatibility(source.items, destination.items);\n  if (destinationType !== 'object') return 'compatible';\n\n  const sourceProperties = isRecord(source.properties) ? source.properties : {};\n  const destinationProperties = isRecord(destination.properties) ? destination.properties : {};\n  const required = Array.isArray(destination.required)\n    ? destination.required.filter((key): key is string => typeof key === 'string')\n    : [];\n  for (const key of required) {\n    if (!(key in sourceProperties)) return 'incompatible';\n  }\n  for (const [key, destinationProperty] of Object.entries(destinationProperties)) {\n    if (!(key in sourceProperties)) continue;\n    if (schemaCompatibility(sourceProperties[key], destinationProperty) === 'incompatible') return 'incompatible';\n  }\n  return 'compatible';\n}\n\n/** Follows a dotted mapping path through object `properties`; `''`/`'.'` is the root. */\nexport function schemaAtPath(schema: JsonSchema | undefined, path: string): JsonSchema | undefined {\n  if (!schema || path === '' || path === '.') return schema;\n  let current: unknown = schema;\n  for (const segment of path.split('.')) {\n    if (!isRecord(current) || !isRecord(current.properties) || !isRecord(current.properties[segment])) return undefined;\n    current = current.properties[segment];\n  }\n  return current as JsonSchema;\n}\n\n/** Plain dotted segments only — no `$.`, brackets, or empty segments. */\nexport function isCanonicalMappingPath(path: string): boolean {\n  return path === '' || path === '.' || /^[^.[$\\]]+(?:\\.[^.[$\\]]+)*$/.test(path);\n}\n\n/** Infers a JSON Schema for a literal `{ value }` mapping source. */\nexport function schemaForValue(value: unknown): JsonSchema {\n  if (value === null) return { type: 'null' };\n  if (Array.isArray(value)) return { type: 'array' };\n  switch (typeof value) {\n    case 'string':\n    case 'boolean':\n      return { type: typeof value };\n    case 'number':\n      return { type: Number.isInteger(value) ? 'integer' : 'number' };\n    case 'object':\n      return { type: 'object' };\n    default:\n      return {};\n  }\n}\n","/**\n * Shared vocabulary for the one dynamic-workflow validation domain.\n *\n * Every validation surface (Mastra save path, builder preflight, Studio draft\n * UI) speaks in `WorkflowValidationIssue`s produced by the collect-mode core\n * in `./index`. Throwing behavior is a presentation concern layered on top\n * (`assertValidDynamicWorkflow`), not a separate rule set.\n */\nimport type { Predicate } from '../../predicate';\nimport type { SerializedSingleStepEntry, SerializedStepFlowEntry } from '../../types';\nimport type { JsonSchema } from '../json-schema-to-zod';\n\nexport type WorkflowValidationIssueCode =\n  | 'empty-graph'\n  | 'missing-step-id'\n  | 'duplicate-step-id'\n  | 'missing-reference'\n  | 'invalid-nested-workflow-id'\n  | 'invalid-map-config'\n  | 'invalid-map-reference'\n  | 'invalid-map-placement'\n  | 'invalid-parallel'\n  | 'invalid-foreach'\n  | 'invalid-conditional'\n  | 'invalid-loop'\n  | 'invalid-predicate-reference'\n  | 'incompatible-schema'\n  | 'unsupported-schema-keyword'\n  | 'self-reference';\n\nexport interface WorkflowValidationRepairSource {\n  source: { initData: true; path: string } | { step: string; path: string };\n  schema?: JsonSchema;\n  compatibility: 'compatible' | 'incompatible' | 'unknown';\n}\n\nexport interface WorkflowValidationRepairAction {\n  issueCode: WorkflowValidationIssueCode;\n  path: string;\n  entryId?: string;\n  containerId?: string;\n  childId?: string;\n  destinationField?: string;\n  expectedSchema?: JsonSchema;\n  actualSchema?: JsonSchema;\n  legalSources?: WorkflowValidationRepairSource[];\n  operation:\n    | 'insert-workflow-mapping-before'\n    | 'insert-workflow-mapping-after'\n    | 'set-workflow-mapping-source'\n    | 'set-workflow-predicate'\n    | 'update-workflow-step'\n    | 'remove-workflow-step';\n  arguments: Record<string, string | number | boolean>;\n  blocksCheckpoint: boolean;\n  blocksFinalize: boolean;\n}\n\nexport interface WorkflowValidationIssue {\n  code: WorkflowValidationIssueCode;\n  path: string;\n  message: string;\n  repair?: WorkflowValidationRepairAction;\n}\n\n/** Input/output shapes known for one registered dependency. */\nexport interface WorkflowRegistrySchemas {\n  inputSchema?: JsonSchema;\n  outputSchema?: JsonSchema;\n}\n\nexport interface ClassifierRegistrySchemas extends WorkflowRegistrySchemas {\n  questions?: Record<\n    string,\n    { type: 'choice'; choices: string[] } | { type: 'score'; min: number; max: number } | { type: 'boolean' }\n  >;\n}\n\n/**\n * What the validator knows about the surrounding registries. Presence of a\n * top-level key means \"this kind was indexed, check references against it\";\n * an absent key skips reference checks for that kind (a caller that cannot\n * enumerate, say, workflows must not produce false missing-reference issues).\n * Schemas are optional per entry — when present they power schema-flow\n * analysis, when absent compatibility degrades to `unknown` (never a false\n * incompatibility).\n */\nexport interface WorkflowRegistryIndex {\n  agents?: Record<string, WorkflowRegistrySchemas>;\n  tools?: Record<string, WorkflowRegistrySchemas>;\n  classifiers?: Record<string, ClassifierRegistrySchemas>;\n  workflows?: Record<string, WorkflowRegistrySchemas>;\n}\n\n/**\n * The graph-entry union validation accepts: the canonical serialized union,\n * widened only where the wire legitimately diverges from the fluent\n * serializer's output —\n *  - `sleepUntil.date` arrives as an ISO string over HTTP (Date at runtime)\n *  - `serializedConditions` / `serializedCondition` are fluent-builder debug\n *    labels; clients don't send them (rehydration derives them)\n *\n * `SerializedStepFlowEntry` is assignable to this union, and so is the\n * authoring subset (`WorkflowBuilderGraphEntry`) — asserted statically in\n * `workflows/builder`.\n */\nexport type ValidatableStepFlowEntry =\n  | SerializedSingleStepEntry\n  | Extract<SerializedStepFlowEntry, { type: 'sleep' }>\n  | (Omit<Extract<SerializedStepFlowEntry, { type: 'sleepUntil' }>, 'date'> & { date?: Date | string })\n  | Extract<SerializedStepFlowEntry, { type: 'parallel' }>\n  | (Omit<Extract<SerializedStepFlowEntry, { type: 'conditional' }>, 'serializedConditions'> & {\n      serializedConditions?: { id: string; fn: string }[];\n    })\n  | (Omit<Extract<SerializedStepFlowEntry, { type: 'loop' }>, 'serializedCondition'> & {\n      serializedCondition?: { id: string; fn: string };\n      predicate?: Predicate;\n    })\n  | Extract<SerializedStepFlowEntry, { type: 'foreach' }>;\n\n/**\n * The definition shape validation operates on — the common structural core of\n * `DynamicWorkflowGraph` (persistence) and `WorkflowBuilderDefinition`\n * (authoring wire shape).\n */\nexport interface WorkflowValidationInput {\n  id: string;\n  description?: string;\n  inputSchema: JsonSchema;\n  outputSchema: JsonSchema;\n  stateSchema?: JsonSchema;\n  requestContextSchema?: JsonSchema;\n  graph: readonly ValidatableStepFlowEntry[];\n}\n\n/** Step id of a single-step (leaf) entry; `step` descriptors carry theirs nested. */\nexport function leafEntryId(entry: SerializedSingleStepEntry): string | undefined {\n  return entry.type === 'step' ? entry.step.id : entry.id;\n}\n","import type { SerializedSingleStepEntry } from '../../types';\nimport type { JsonSchema } from '../json-schema-to-zod';\nimport { schemaCompatibility } from './schema-utils';\nimport { leafEntryId } from './types';\nimport type {\n  WorkflowRegistryIndex,\n  WorkflowValidationInput,\n  WorkflowValidationIssue,\n  WorkflowValidationRepairAction,\n  WorkflowValidationRepairSource,\n} from './types';\n\nfunction inputSchemaOf(entry: SerializedSingleStepEntry, index: WorkflowRegistryIndex): JsonSchema | undefined {\n  switch (entry.type) {\n    case 'agent':\n      return (\n        index.agents?.[entry.agentId]?.inputSchema ?? {\n          type: 'object',\n          properties: { prompt: { type: 'string' } },\n          required: ['prompt'],\n        }\n      );\n    case 'tool':\n      return index.tools?.[entry.toolId]?.inputSchema;\n    case 'classifier':\n      return index.classifiers?.[entry.classifierId]?.inputSchema;\n    case 'workflow':\n      return index.workflows?.[entry.workflowId]?.inputSchema;\n    case 'mapping':\n    case 'step':\n      return undefined;\n  }\n}\n\nfunction entryAtPath(def: WorkflowValidationInput, path: string): SerializedSingleStepEntry | undefined {\n  const match = /^graph\\.(\\d+)(?:\\.(steps)\\.(\\d+)|\\.(step))?/.exec(path);\n  if (!match) return undefined;\n  const entry = def.graph[Number(match[1])];\n  if (!entry) return undefined;\n  if (match[2] === 'steps' && (entry.type === 'parallel' || entry.type === 'conditional')) {\n    return entry.steps[Number(match[3])];\n  }\n  if (match[4] === 'step' && (entry.type === 'foreach' || entry.type === 'loop')) return entry.step;\n  if (\n    entry.type === 'agent' ||\n    entry.type === 'tool' ||\n    entry.type === 'classifier' ||\n    entry.type === 'workflow' ||\n    entry.type === 'mapping' ||\n    entry.type === 'step'\n  ) {\n    return entry;\n  }\n  return undefined;\n}\n\nfunction precedingSourceIds(def: WorkflowValidationInput, targetIndex: number): string[] {\n  const ids: string[] = [];\n  def.graph.slice(0, targetIndex).forEach(entry => {\n    if (entry.type === 'parallel' || entry.type === 'conditional') {\n      entry.steps.forEach(child => {\n        const childId = leafEntryId(child);\n        if (childId) ids.push(childId);\n      });\n    } else if (entry.type === 'foreach' || entry.type === 'loop') {\n      const childId = leafEntryId(entry.step);\n      if (childId) ids.push(childId);\n    }\n    // Container entries (parallel/conditional/foreach/loop) never produce a\n    // result keyed by their own id — only their executed children do. Advertising\n    // the container id here previously sent authors toward mappings that pass\n    // draft validation and then fail at run time.\n    if (entry.type === 'parallel' || entry.type === 'conditional' || entry.type === 'foreach' || entry.type === 'loop')\n      return;\n    const id = 'id' in entry && entry.id ? entry.id : entry.type === 'step' ? entry.step.id : undefined;\n    if (id) ids.push(id);\n  });\n  return ids;\n}\n\nfunction legalSources(\n  def: WorkflowValidationInput,\n  targetIndex: number,\n  expectedSchema: JsonSchema | undefined,\n  stepOutputs: Map<string, JsonSchema | undefined>,\n): WorkflowValidationRepairSource[] {\n  const sources: WorkflowValidationRepairSource[] = [\n    {\n      source: { initData: true, path: '' },\n      schema: def.inputSchema,\n      compatibility: schemaCompatibility(def.inputSchema, expectedSchema),\n    },\n    ...precedingSourceIds(def, targetIndex).map(stepId => {\n      const schema = stepOutputs.get(stepId);\n      return {\n        source: { step: stepId, path: '' } as const,\n        ...(schema ? { schema } : {}),\n        compatibility: schemaCompatibility(schema, expectedSchema),\n      };\n    }),\n  ];\n  return sources.filter(source => source.compatibility !== 'incompatible');\n}\n\nexport function addWorkflowValidationRepairActions(\n  def: WorkflowValidationInput,\n  index: WorkflowRegistryIndex,\n  issues: WorkflowValidationIssue[],\n  stepOutputs: Map<string, JsonSchema | undefined>,\n  entryInputs: Map<string, JsonSchema | undefined>,\n  finalOutput: JsonSchema | undefined,\n): WorkflowValidationIssue[] {\n  return issues.map(issue => {\n    const graphMatch = /^graph\\.(\\d+)/.exec(issue.path);\n    const targetIndex = graphMatch ? Number(graphMatch[1]) : def.graph.length;\n    const entry = entryAtPath(def, issue.path);\n    const entryId = entry ? leafEntryId(entry) : undefined;\n    let repair: WorkflowValidationRepairAction | undefined;\n\n    if (issue.code === 'incompatible-schema') {\n      // A foreach consumes a RAW ARRAY of its child's input, so the useful\n      // \"expected\" shape is the iterable — not the child input, and definitely\n      // not the workflow output schema the container path used to fall back to.\n      const containerEntry = graphMatch ? def.graph[targetIndex] : undefined;\n      const foreachChildInput =\n        containerEntry?.type === 'foreach' ? inputSchemaOf(containerEntry.step, index) : undefined;\n      const expectedSchema =\n        containerEntry?.type === 'foreach'\n          ? ({ type: 'array', ...(foreachChildInput ? { items: foreachChildInput } : {}) } as JsonSchema)\n          : entry\n            ? inputSchemaOf(entry, index)\n            : def.outputSchema;\n      const actualSchema =\n        issue.path === 'outputSchema'\n          ? finalOutput\n          : (entryInputs.get(issue.path) ?? (targetIndex === 0 ? def.inputSchema : undefined));\n      repair = {\n        issueCode: issue.code,\n        path: issue.path,\n        ...(entryId ? { entryId } : {}),\n        ...(expectedSchema ? { expectedSchema } : {}),\n        ...(actualSchema ? { actualSchema } : {}),\n        legalSources: legalSources(def, targetIndex, expectedSchema, stepOutputs),\n        // A foreach consumes a raw array, and mappings always emit an object —\n        // inserting a mapping can never satisfy it. Advertise fixing the\n        // upstream producer (or the foreach body) instead.\n        operation:\n          containerEntry?.type === 'foreach'\n            ? 'update-workflow-step'\n            : issue.path === 'outputSchema'\n              ? 'insert-workflow-mapping-after'\n              : 'insert-workflow-mapping-before',\n        arguments: entryId ? { targetStepId: entryId } : { targetPath: issue.path },\n        blocksCheckpoint: false,\n        blocksFinalize: true,\n      };\n    } else if (issue.code === 'invalid-map-config' || issue.code === 'invalid-map-reference') {\n      const destinationField = /\\.mapConfig\\.([^\\.]+)/.exec(issue.path)?.[1];\n      repair = {\n        issueCode: issue.code,\n        path: issue.path,\n        ...(entryId ? { entryId } : {}),\n        ...(destinationField ? { destinationField } : {}),\n        legalSources: legalSources(def, targetIndex, undefined, stepOutputs),\n        operation: 'set-workflow-mapping-source',\n        arguments: {\n          ...(entryId ? { mappingStepId: entryId } : {}),\n          ...(destinationField ? { field: destinationField } : {}),\n        },\n        blocksCheckpoint: false,\n        blocksFinalize: true,\n      };\n    } else if (issue.code === 'invalid-predicate-reference') {\n      repair = {\n        issueCode: issue.code,\n        path: issue.path,\n        ...(entryId ? { childId: entryId } : {}),\n        operation: 'set-workflow-predicate',\n        arguments: { predicatePath: issue.path },\n        blocksCheckpoint: false,\n        blocksFinalize: true,\n      };\n    } else if (issue.code === 'missing-reference') {\n      repair = {\n        issueCode: issue.code,\n        path: issue.path,\n        ...(entryId ? { entryId } : {}),\n        operation: 'update-workflow-step',\n        arguments: entryId ? { stepId: entryId } : { targetPath: issue.path },\n        blocksCheckpoint: false,\n        blocksFinalize: true,\n      };\n    } else if (issue.code === 'invalid-map-placement') {\n      repair = {\n        issueCode: issue.code,\n        path: issue.path,\n        ...(entryId ? { childId: entryId } : {}),\n        operation: 'remove-workflow-step',\n        arguments: entryId ? { stepId: entryId } : { targetPath: issue.path },\n        blocksCheckpoint: false,\n        blocksFinalize: true,\n      };\n    }\n\n    return repair ? { ...issue, repair } : issue;\n  });\n}\n","/**\n * The single home for stored `mapConfig` handling.\n *\n * A mapping entry's config crosses the storage boundary as a JSON string.\n * - {@link parseMapConfig} is the one parser (rehydration + validation both\n *   use it; rehydration via the throwing form).\n * - {@link analyzeMapConfig} is the one validator: it walks each descriptor,\n *   collects issues, and infers the mapping's output schema in the same pass\n *   (the two are inseparable — a descriptor's validity determines its\n *   contribution to the output shape).\n *\n * Template syntax checking delegates to `mapping-template.ts`'s\n * `validateTemplate` — the same parser the runtime uses — plus a scope check\n * over the placeholders' step ids.\n */\nimport { collectTemplateStepIds, validateTemplate } from '../mapping-template';\nimport type { JsonSchema } from './json-schema-to-zod';\nimport { isCanonicalMappingPath, isRecord, schemaAtPath, schemaForValue } from './validate/schema-utils';\nimport type { WorkflowValidationIssue } from './validate/types';\n\n/** Parses a stored mapConfig JSON string; throws with the step id on malformed JSON. */\nexport function parseMapConfig(raw: string, stepId: string): Record<string, any> {\n  try {\n    return JSON.parse(raw) as Record<string, any>;\n  } catch (e) {\n    throw new Error(`Stored mapping step \"${stepId}\" has invalid JSON mapConfig: ${(e as Error).message}`);\n  }\n}\n\n/** A recognizable Handlebars/Mustache placeholder: `{{ name }}`, `{{a.b}}`, … */\nconst HANDLEBARS_PLACEHOLDER = /\\{\\{\\s*[\\w$][\\w.$-]*\\s*\\}\\}/;\n\nexport interface MapConfigAnalysisOptions {\n  /** Issue path prefix of the mapping entry, e.g. `graph.2`. */\n  path: string;\n  /** Outputs of preceding workflow-local steps (schema may be undefined when unknown). */\n  availableOutputs: ReadonlyMap<string, JsonSchema | undefined>;\n  /** The workflow's input schema (for `{ initData: true }` sources). */\n  inputSchema: JsonSchema | undefined;\n  /** The workflow's request-context schema (for `{ requestContextPath }` sources). */\n  requestContextSchema: JsonSchema | undefined;\n}\n\nexport interface MapConfigAnalysis {\n  issues: WorkflowValidationIssue[];\n  /** Inferred output schema of the mapping step; undefined when the config is unusable. */\n  outputSchema: JsonSchema | undefined;\n}\n\n/**\n * Validates a mapping entry's raw `mapConfig` string and infers the step's\n * output schema. Every key must define exactly one source\n * (`value` | `template` | `requestContextPath` | `initData`/`step` + `path`);\n * step references must point at preceding workflow-local steps.\n */\nexport function analyzeMapConfig(rawConfig: string, opts: MapConfigAnalysisOptions): MapConfigAnalysis {\n  const issues: WorkflowValidationIssue[] = [];\n  const { path, availableOutputs } = opts;\n\n  let config: unknown;\n  try {\n    config = JSON.parse(rawConfig);\n  } catch {\n    config = undefined;\n  }\n  if (!isRecord(config)) {\n    issues.push({\n      code: 'invalid-map-config',\n      path: `${path}.mapConfig`,\n      message: 'Mapping config must be a JSON object.',\n    });\n    return { issues, outputSchema: undefined };\n  }\n\n  const properties: Record<string, JsonSchema> = {};\n  for (const [key, descriptor] of Object.entries(config)) {\n    const descriptorPath = `${path}.mapConfig.${key}`;\n    if (!isRecord(descriptor)) {\n      issues.push({\n        code: 'invalid-map-config',\n        path: descriptorPath,\n        message: 'Mapping descriptor must be an object.',\n      });\n      continue;\n    }\n    const forms = [\n      'value' in descriptor,\n      typeof descriptor.template === 'string',\n      typeof descriptor.requestContextPath === 'string',\n      'path' in descriptor,\n    ].filter(Boolean).length;\n    if (forms !== 1) {\n      issues.push({\n        code: 'invalid-map-config',\n        path: descriptorPath,\n        message: 'Mapping descriptor must define exactly one source.',\n      });\n      continue;\n    }\n    if ('value' in descriptor) {\n      properties[key] = schemaForValue(descriptor.value);\n      continue;\n    }\n    if (typeof descriptor.template === 'string') {\n      let syntaxError: string | undefined;\n      try {\n        validateTemplate(descriptor.template);\n      } catch (err) {\n        syntaxError = (err as Error).message;\n      }\n      // Handlebars-style `{{name}}` is not a workflow placeholder — the runtime\n      // would emit it literally, which is never what the author meant.\n      if (syntaxError === undefined && HANDLEBARS_PLACEHOLDER.test(descriptor.template)) {\n        syntaxError = `Templates use \\${...} placeholders (e.g. \"\\${initData.name}\"), not {{...}}. \"${descriptor.template}\" would be emitted literally.`;\n      }\n      const unknownStep =\n        syntaxError === undefined\n          ? collectTemplateStepIds(descriptor.template).find(stepId => !availableOutputs.has(stepId))\n          : undefined;\n      if (syntaxError !== undefined || unknownStep !== undefined) {\n        issues.push({\n          code: 'invalid-map-reference',\n          path: `${descriptorPath}.template`,\n          message: syntaxError ?? 'Template references must use an available workflow-local source.',\n        });\n      }\n      properties[key] = { type: 'string' };\n      continue;\n    }\n    if (typeof descriptor.requestContextPath === 'string') {\n      if (!isCanonicalMappingPath(descriptor.requestContextPath) || descriptor.requestContextPath === '') {\n        issues.push({\n          code: 'invalid-map-config',\n          path: `${descriptorPath}.requestContextPath`,\n          message: 'Mapping paths must use plain dotted segments.',\n        });\n      }\n      properties[key] = schemaAtPath(opts.requestContextSchema, descriptor.requestContextPath) ?? {};\n      continue;\n    }\n\n    if (typeof descriptor.path !== 'string' || !isCanonicalMappingPath(descriptor.path)) {\n      issues.push({\n        code: 'invalid-map-config',\n        path: `${descriptorPath}.path`,\n        message: 'Mapping paths must use plain dotted segments.',\n      });\n      continue;\n    }\n    const hasInitData = descriptor.initData === true;\n    const stepIds =\n      typeof descriptor.step === 'string' ? [descriptor.step] : Array.isArray(descriptor.step) ? descriptor.step : [];\n    if (hasInitData === stepIds.length > 0 || stepIds.some(stepId => typeof stepId !== 'string')) {\n      issues.push({\n        code: 'invalid-map-config',\n        path: descriptorPath,\n        message: 'Path mappings must reference exactly one of initData or step.',\n      });\n      continue;\n    }\n    let sourceSchema: JsonSchema | undefined;\n    if (hasInitData) {\n      sourceSchema = opts.inputSchema;\n    } else {\n      const missing = stepIds.find(stepId => !availableOutputs.has(stepId));\n      if (missing) {\n        issues.push({\n          code: 'invalid-map-reference',\n          path: `${descriptorPath}.step`,\n          message: `Mapping source \"${missing}\" must be a preceding workflow-local step.`,\n        });\n        continue;\n      }\n      sourceSchema = stepIds.map(stepId => availableOutputs.get(stepId)).find(Boolean);\n    }\n    const selectedSchema = schemaAtPath(sourceSchema, descriptor.path);\n    if (sourceSchema && !selectedSchema) {\n      issues.push({\n        code: 'invalid-map-config',\n        path: `${descriptorPath}.path`,\n        message: `Path \"${descriptor.path}\" does not exist in the source schema.`,\n      });\n    }\n    properties[key] = selectedSchema ?? {};\n  }\n  return { issues, outputSchema: { type: 'object', properties, required: Object.keys(config) } };\n}\n","/**\n * Schema-flow analysis: a small type-checker over the workflow graph.\n *\n * Folds an inferred \"current schema\" through the top-level entries — each\n * step's output feeds the next step's input — and reports a proven mismatch\n * as `incompatible-schema`. Mapping configs are analyzed here (via\n * `mapping-config.ts`) because a mapping's validity and its output schema are\n * inseparable. Unknown schemas degrade to `undefined` and never produce false\n * positives.\n *\n * Unlike the old preflight implementation, state is threaded explicitly:\n * `fold` takes the incoming schema and returns the outgoing one — no\n * closure-mutable `currentSchema` with save/restore tricks.\n */\nimport type { PathOrLiteral, Predicate } from '../../predicate';\nimport type { SerializedSingleStepEntry } from '../../types';\nimport type { JsonSchema } from '../json-schema-to-zod';\nimport { analyzeMapConfig } from '../mapping-config';\nimport { isCanonicalMappingPath, isRecord, schemaAtPath, schemaCompatibility } from './schema-utils';\nimport { leafEntryId } from './types';\nimport type { WorkflowRegistryIndex, WorkflowValidationInput, WorkflowValidationIssue } from './types';\n\nexport interface GraphSchemaInference {\n  /** Output schema of each runtime-visible step id (undefined = unknown). */\n  stepOutputs: Map<string, JsonSchema | undefined>;\n  /** Input schema reaching each evaluated graph path (undefined = unknown). */\n  entryInputs: Map<string, JsonSchema | undefined>;\n  /** Inferred output of the last entry in the graph (undefined = unknown). */\n  finalOutput: JsonSchema | undefined;\n  issues: WorkflowValidationIssue[];\n}\n\n/** Agents accept `{ prompt }` unless the registry says otherwise. */\nconst agentInputSchema: JsonSchema = {\n  type: 'object',\n  properties: { prompt: { type: 'string' } },\n  required: ['prompt'],\n};\n\n/**\n * An agent entry without declared structured output returns exactly\n * `{ text }` at runtime (`runAgentEntry`), so invented output paths like\n * `.response` are provably wrong rather than unknown.\n */\nconst agentTextOutputSchema: JsonSchema = {\n  type: 'object',\n  properties: { text: { type: 'string' } },\n  required: ['text'],\n};\n\nconst classifierOutputSchema: JsonSchema = {\n  type: 'object',\n  properties: {\n    answers: { type: 'object', additionalProperties: true },\n    usage: { type: 'object', additionalProperties: true },\n  },\n  required: ['answers', 'usage'],\n};\n\nfunction inputSchemaOf(entry: SerializedSingleStepEntry, index: WorkflowRegistryIndex): JsonSchema | undefined {\n  switch (entry.type) {\n    case 'agent':\n      return index.agents?.[entry.agentId]?.inputSchema ?? agentInputSchema;\n    case 'tool':\n      return index.tools?.[entry.toolId]?.inputSchema;\n    case 'classifier':\n      return undefined;\n    case 'workflow':\n      return index.workflows?.[entry.workflowId]?.inputSchema;\n    case 'mapping':\n    case 'step':\n      return undefined;\n  }\n}\n\nfunction outputSchemaOf(entry: SerializedSingleStepEntry, index: WorkflowRegistryIndex): JsonSchema | undefined {\n  switch (entry.type) {\n    case 'agent':\n      return entry.outputSchema ?? index.agents?.[entry.agentId]?.outputSchema ?? agentTextOutputSchema;\n    case 'tool':\n      return index.tools?.[entry.toolId]?.outputSchema;\n    case 'classifier':\n      return index.classifiers?.[entry.classifierId]?.outputSchema ?? classifierOutputSchema;\n    case 'workflow':\n      return index.workflows?.[entry.workflowId]?.outputSchema;\n    case 'mapping':\n    case 'step':\n      return undefined;\n  }\n}\n\nfunction validatePredicate(\n  predicate: Predicate,\n  path: string,\n  context: {\n    initData: JsonSchema;\n    inputData: JsonSchema | undefined;\n    state: JsonSchema | undefined;\n    stepResults: Map<string, JsonSchema | undefined>;\n  },\n): WorkflowValidationIssue[] {\n  const issues: WorkflowValidationIssue[] = [];\n\n  const validatePath = (rawPath: string, issuePath: string) => {\n    if (!isCanonicalMappingPath(rawPath)) {\n      issues.push({\n        code: 'invalid-predicate-reference',\n        path: issuePath,\n        message: 'Predicate paths must use plain dotted segments rooted at initData, inputData, stepResults, or state.',\n      });\n      return;\n    }\n\n    const [root, ...segments] = rawPath.split('.');\n    let schema: JsonSchema | undefined;\n    let schemaPath = segments.join('.');\n    if (root === 'initData') schema = context.initData;\n    else if (root === 'inputData') schema = context.inputData;\n    else if (root === 'state') schema = context.state;\n    else if (root === 'stepResults') {\n      const stepId = segments.shift();\n      if (!stepId || !context.stepResults.has(stepId)) {\n        issues.push({\n          code: 'invalid-predicate-reference',\n          path: issuePath,\n          message: stepId\n            ? `Predicate step result \"${stepId}\" must reference a preceding top-level step.`\n            : 'Predicate stepResults paths must include a preceding top-level step id.',\n        });\n        return;\n      }\n      schema = context.stepResults.get(stepId);\n      schemaPath = segments.join('.');\n    } else {\n      issues.push({\n        code: 'invalid-predicate-reference',\n        path: issuePath,\n        message: 'Predicate paths must be rooted at initData, inputData, stepResults, or state.',\n      });\n      return;\n    }\n\n    if (schemaPath && isRecord(schema) && typeof schema.type === 'string' && !schemaAtPath(schema, schemaPath)) {\n      issues.push({\n        code: 'invalid-predicate-reference',\n        path: issuePath,\n        message: `Predicate path \"${rawPath}\" does not exist in the known schema.`,\n      });\n    }\n  };\n\n  const validateRef = (ref: PathOrLiteral, refPath: string) => {\n    if ('path' in ref) validatePath(ref.path, `${refPath}.path`);\n  };\n\n  switch (predicate.op) {\n    case 'and':\n    case 'or':\n      predicate.args.forEach((arg, index) => issues.push(...validatePredicate(arg, `${path}.args.${index}`, context)));\n      break;\n    case 'not':\n      issues.push(...validatePredicate(predicate.arg, `${path}.arg`, context));\n      break;\n    case 'exists':\n    case 'notExists':\n      validatePath(predicate.path, `${path}.path`);\n      break;\n    case 'truthy':\n    case 'falsy':\n      validateRef(predicate.value, `${path}.value`);\n      break;\n    case 'in':\n    case 'notIn':\n      validateRef(predicate.value, `${path}.value`);\n      break;\n    default:\n      validateRef(predicate.left, `${path}.left`);\n      validateRef(predicate.right, `${path}.right`);\n  }\n\n  return issues;\n}\n\nexport function inferGraphSchemas(def: WorkflowValidationInput, index: WorkflowRegistryIndex): GraphSchemaInference {\n  const issues: WorkflowValidationIssue[] = [];\n  const stepOutputs = new Map<string, JsonSchema | undefined>();\n  const entryInputs = new Map<string, JsonSchema | undefined>();\n\n  /** Evaluates one leaf entry: checks its input against `incoming`, returns its output. */\n  const evalLeaf = (\n    entry: SerializedSingleStepEntry,\n    path: string,\n    incoming: JsonSchema | undefined,\n    container: boolean,\n  ): JsonSchema | undefined => {\n    entryInputs.set(path, incoming);\n    if (entry.type === 'mapping') {\n      // Container placement is a structural issue; don't analyze the config twice.\n      if (container) return undefined;\n      const analysis = analyzeMapConfig(entry.mapConfig, {\n        path,\n        availableOutputs: stepOutputs,\n        inputSchema: def.inputSchema,\n        requestContextSchema: def.requestContextSchema,\n      });\n      issues.push(...analysis.issues);\n      return analysis.outputSchema;\n    }\n    if (entry.type === 'step') return undefined;\n    if (schemaCompatibility(incoming, inputSchemaOf(entry, index)) === 'incompatible') {\n      issues.push({\n        code: 'incompatible-schema',\n        path,\n        message: 'Step input is incompatible with the preceding workflow output.',\n      });\n    }\n    return outputSchemaOf(entry, index);\n  };\n\n  let current: JsonSchema | undefined = def.inputSchema;\n  def.graph.forEach((entry, entryIndex) => {\n    const path = `graph.${entryIndex}`;\n    switch (entry.type) {\n      case 'step':\n      case 'agent':\n      case 'tool':\n      case 'classifier':\n      case 'mapping':\n      case 'workflow':\n        current = evalLeaf(entry, path, current, false);\n        break;\n      case 'sleep':\n      case 'sleepUntil':\n        // Passthrough: sleeping does not reshape the data.\n        break;\n      case 'parallel':\n      case 'conditional': {\n        const incoming = current;\n        if (entry.type === 'conditional') {\n          entry.predicates?.forEach((predicate, predicateIndex) => {\n            if (!predicate) return;\n            issues.push(\n              ...validatePredicate(predicate, `${path}.predicates.${predicateIndex}`, {\n                initData: def.inputSchema,\n                inputData: incoming,\n                state: def.stateSchema,\n                stepResults: stepOutputs,\n              }),\n            );\n          });\n        }\n        const properties: Record<string, JsonSchema> = {};\n        entry.steps.forEach((child, childIndex) => {\n          const output = evalLeaf(child, `${path}.steps.${childIndex}`, incoming, true);\n          const childId = leafEntryId(child);\n          if (childId) {\n            stepOutputs.set(childId, output);\n            if (output) properties[childId] = output;\n          }\n        });\n        current = {\n          type: 'object',\n          properties,\n          ...(entry.type === 'parallel' ? { required: Object.keys(properties) } : {}),\n        };\n        break;\n      }\n      case 'foreach': {\n        const incoming = current;\n        if (isRecord(incoming) && typeof incoming.type === 'string' && incoming.type !== 'array') {\n          issues.push({\n            code: 'incompatible-schema',\n            path,\n            message:\n              'Foreach input must be a raw array. A mapping step cannot produce one — mappings always build an object — so the preceding step (or the workflow inputSchema itself) must already be an array of the child input.',\n          });\n        }\n        const items = isRecord(incoming?.items) ? (incoming.items as JsonSchema) : undefined;\n        const output = evalLeaf(entry.step, `${path}.step`, items, true);\n        const childId = leafEntryId(entry.step);\n        if (childId) stepOutputs.set(childId, output);\n        current = output ? { type: 'array', items: output } : output;\n        break;\n      }\n      case 'loop': {\n        const output = evalLeaf(entry.step, `${path}.step`, current, true);\n        const stepId = leafEntryId(entry.step);\n        if (stepId) stepOutputs.set(stepId, output);\n        if (entry.predicate) {\n          const loopStepOutputs = new Map(stepOutputs);\n          issues.push(\n            ...validatePredicate(entry.predicate, `${path}.predicate`, {\n              initData: def.inputSchema,\n              inputData: output,\n              state: def.stateSchema,\n              stepResults: loopStepOutputs,\n            }),\n          );\n        }\n        if (schemaCompatibility(output, inputSchemaOf(entry.step, index)) === 'incompatible') {\n          issues.push({\n            code: 'incompatible-schema',\n            path: `${path}.step`,\n            message: 'Loop step output is incompatible with its input for a subsequent iteration.',\n          });\n        }\n        current = output;\n        break;\n      }\n      default: {\n        const _exhaustive: never = entry;\n        void _exhaustive;\n      }\n    }\n    // Register the outputs of id-bearing top-level entries so later mappings\n    // and templates can reference them. `step` descriptors register too (their\n    // schema is unknown, which is fine — unknown never fails a check).\n    const id = 'id' in entry && entry.id ? entry.id : entry.type === 'step' ? entry.step.id : undefined;\n    if (id) stepOutputs.set(id, current);\n  });\n\n  if (schemaCompatibility(current, def.outputSchema) === 'incompatible') {\n    issues.push({\n      code: 'incompatible-schema',\n      path: 'outputSchema',\n      message: 'Workflow output schema is incompatible with the final step output.',\n    });\n  }\n  return { stepOutputs, entryInputs, finalOutput: current, issues };\n}\n","/**\n * Minimal JSON-Schema ↔ Zod bridge for dynamic workflows: a converter for the\n * static subset Zod round-trips through `standardSchemaToJSONSchema`, plus a\n * non-throwing validator for the write path.\n */\nimport { z } from 'zod';\n\n/**\n * Minimal JSON-Schema shape we accept. Intentionally untyped on the value side\n * — different JSON Schema producers emit slightly different shapes and the\n * inline converter below just inspects the fields it cares about.\n */\nexport type JsonSchema = Record<string, any>;\n\n/**\n * Options controlling how `jsonSchemaToZod` handles JSON Schema keywords the\n * MVP converter doesn't support.\n *\n * - `throw` (default): hard-crash with a targeted error. Correct for the save\n *   path — the author is right there and can simplify the schema.\n * - `warn`: emit a warning via `onUnsupported` (if provided) and fall back to\n *   `z.any()` for the unsupported subtree. Correct for the boot-time load\n *   path — one bad pre-existing row must not take down startup for every\n *   other workflow.\n */\nexport interface JsonSchemaToZodOptions {\n  onUnsupportedSchema?: 'throw' | 'warn';\n  onUnsupported?: (message: string) => void;\n}\n\n/**\n * Inline converter sufficient for the static subset Zod typically emits when\n * round-tripped through `standardSchemaToJSONSchema`. Handles:\n *\n *  - `object` with `properties` + `required`\n *  - `string` / `number` / `integer` / `boolean` / `null`\n *  - `array` with `items`\n *  - `enum`\n *  - `description` (propagated via `.describe`)\n *\n * For more exotic schemas (unions, intersections, recursive refs) swap in\n * `json-schema-to-zod` from npm. Kept inline to avoid pulling a dependency\n * for the MVP demo.\n */\nexport function jsonSchemaToZod(schema: JsonSchema, opts?: JsonSchemaToZodOptions): z.ZodTypeAny {\n  return walk(schema, opts ?? {});\n}\n\n// JSON Schema keywords that this MVP converter does not support. If a stored\n// workflow's inputSchema/outputSchema uses any of these, silently converting\n// to z.any() would strip the constraint at rehydration and let bad data flow\n// through at execution — hard-crash instead so the corruption surfaces at\n// load time.\nconst UNSUPPORTED_SCHEMA_KEYS = [\n  'oneOf',\n  'anyOf',\n  'allOf',\n  'not',\n  '$ref',\n  'patternProperties',\n  'discriminator',\n] as const;\n\n/** Values `z.literal()` can represent — the only const/enum members that survive conversion losslessly. */\nfunction isLiteralValue(v: unknown): v is string | number | boolean | null {\n  return v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n}\n\n/** Throw or warn-and-fallback per `onUnsupportedSchema`, matching the unsupported-keyword behavior. */\nfunction unsupported(message: string, opts: JsonSchemaToZodOptions): z.ZodTypeAny {\n  if (opts.onUnsupportedSchema === 'warn') {\n    opts.onUnsupported?.(message);\n    return z.any();\n  }\n  throw new Error(message);\n}\n\nfunction walk(schema: JsonSchema, opts: JsonSchemaToZodOptions): z.ZodTypeAny {\n  if (!schema || typeof schema !== 'object') return z.any();\n\n  for (const key of UNSUPPORTED_SCHEMA_KEYS) {\n    if (key in schema) {\n      return unsupported(\n        `Dynamic workflow schema uses unsupported JSON Schema keyword \"${key}\". ` +\n          `This converter only supports the static subset that Zod round-trips through ` +\n          `standardSchemaToJSONSchema (object, array, string, number, integer, boolean, null, enum, const). ` +\n          `Simplify the schema or extend jsonSchemaToZod to cover this keyword.`,\n        opts,\n      );\n    }\n  }\n\n  let out: z.ZodTypeAny;\n\n  if ('const' in schema) {\n    // Zod emits `{ const: value }` for z.literal() — preserve it instead of\n    // silently dropping the constraint. Non-primitive consts (objects/arrays)\n    // can't be represented by z.literal, so treat them as unsupported.\n    if (!isLiteralValue(schema.const)) {\n      return unsupported(\n        `Dynamic workflow schema uses a non-primitive \"const\" value (${JSON.stringify(schema.const)}). ` +\n          `Only string, number, boolean, and null literals are supported.`,\n        opts,\n      );\n    }\n    out = z.literal(schema.const);\n  } else if (Array.isArray(schema.enum) && schema.enum.length > 0) {\n    const values = schema.enum as unknown[];\n    if (!values.every(isLiteralValue)) {\n      return unsupported(\n        `Dynamic workflow schema uses an \"enum\" with non-primitive members. ` +\n          `Only string, number, boolean, and null enum members are supported.`,\n        opts,\n      );\n    }\n    if (values.every(v => typeof v === 'string')) {\n      out = z.enum(values as [string, ...string[]]);\n    } else {\n      // Mixed/non-string enums (e.g. [1, 2, 3] or ['a', 1]): preserve the\n      // original member types via literal union instead of coercing to string.\n      const literals: z.ZodTypeAny[] = values.map(v => z.literal(v));\n      out = literals.length === 1 ? literals[0]! : z.union(literals as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]);\n    }\n  } else if (Array.isArray(schema.type)) {\n    const options = schema.type.map((t: string) => walk({ ...schema, type: t }, opts));\n    // z.union requires a tuple of at least two members; guard shorter arrays.\n    if (options.length === 1) {\n      out = options[0]!;\n    } else {\n      out = z.union(options as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]);\n    }\n  } else {\n    switch (schema.type) {\n      case 'object': {\n        const shape: Record<string, z.ZodTypeAny> = {};\n        const required = new Set<string>(Array.isArray(schema.required) ? schema.required : []);\n        for (const [key, child] of Object.entries(schema.properties ?? {})) {\n          const childSchema = walk(child as JsonSchema, opts);\n          shape[key] = required.has(key) ? childSchema : childSchema.optional();\n        }\n        const obj = z.object(shape);\n        out = schema.additionalProperties === true ? obj.passthrough() : obj;\n        break;\n      }\n      case 'array':\n        // Tuple-form `items: [...]` positional schemas aren't representable by\n        // z.array(); converting to z.array(z.any()) would strip every\n        // positional constraint. Reject instead of silently widening.\n        if (Array.isArray(schema.items)) {\n          return unsupported(\n            `Dynamic workflow schema uses tuple-form \"items\" (an array of positional schemas). ` +\n              `Only a single item schema is supported; use \"items\": { ... } instead.`,\n            opts,\n          );\n        }\n        out = z.array(walk(schema.items ?? {}, opts));\n        break;\n      case 'string':\n        out = z.string();\n        break;\n      case 'number':\n        out = z.number();\n        break;\n      case 'integer':\n        out = z.number().int();\n        break;\n      case 'boolean':\n        out = z.boolean();\n        break;\n      case 'null':\n        out = z.null();\n        break;\n      case undefined:\n        // No `type` and no enum/typed-array — schema is just a description\n        // or annotation wrapper; permit z.any() for these.\n        out = z.any();\n        break;\n      default:\n        return unsupported(\n          `Dynamic workflow schema uses unsupported JSON Schema type \"${String(schema.type)}\". ` +\n            `This converter only supports object, array, string, number, integer, boolean, null, and enum.`,\n          opts,\n        );\n    }\n  }\n\n  if (typeof schema.description === 'string' && schema.description.length > 0) {\n    out = out.describe(schema.description);\n  }\n  return out;\n}\n\n/**\n * Result of a `validateStorableJsonSchema` call.\n * `unsupported` lists every offending keyword usage as `<jsonPointer>: <keyword>`\n * so callers can log or surface a targeted message per offense.\n */\nexport type StorableJsonSchemaValidation = { ok: true } | { ok: false; unsupported: string[] };\n\n/**\n * Non-throwing companion to `jsonSchemaToZod`. Walks a JSON Schema and reports\n * every unsupported-keyword usage without converting. Use this at write time\n * (e.g. inside `Mastra.addDynamicWorkflow`) to surface a warning before the\n * schema is persisted — the row will still fail to rehydrate on the next boot\n * (`jsonSchemaToZod` throws), so this is a heads-up, not a guarantee.\n *\n * Callers decide whether to warn, reject, or ignore. This function never\n * throws for any input shape.\n */\nexport function validateStorableJsonSchema(schema: JsonSchema | undefined): StorableJsonSchemaValidation {\n  if (!schema || typeof schema !== 'object') return { ok: true };\n  const unsupported: string[] = [];\n  const visit = (node: unknown, path: string): void => {\n    if (!node || typeof node !== 'object') return;\n    const n = node as Record<string, unknown>;\n    for (const key of UNSUPPORTED_SCHEMA_KEYS) {\n      if (key in n) unsupported.push(`${path || '#'}: ${key}`);\n    }\n    if (n.properties && typeof n.properties === 'object') {\n      for (const [prop, child] of Object.entries(n.properties as Record<string, unknown>)) {\n        visit(child, `${path}/properties/${prop}`);\n      }\n    }\n    if (n.items) {\n      if (Array.isArray(n.items)) {\n        n.items.forEach((child, i) => visit(child, `${path}/items/${i}`));\n      } else {\n        visit(n.items, `${path}/items`);\n      }\n    }\n    if (n.additionalProperties && typeof n.additionalProperties === 'object') {\n      visit(n.additionalProperties, `${path}/additionalProperties`);\n    }\n  };\n  visit(schema, '');\n  return unsupported.length === 0 ? { ok: true } : { ok: false, unsupported };\n}\n","/**\n * JSON-Schema keyword checks: every schema embedded in the definition must be\n * convertible by `jsonSchemaToZod` (no oneOf/anyOf/allOf/not/$ref/\n * patternProperties/discriminator). Covers the four top-level schemas plus\n * each `agent.outputSchema` reachable through containers.\n */\nimport { forEachSingleStepEntryWithPath } from '../graph';\nimport { validateStorableJsonSchema } from '../json-schema-to-zod';\nimport type { JsonSchema } from '../json-schema-to-zod';\nimport type { WorkflowValidationInput, WorkflowValidationIssue } from './types';\n\nexport function validateWorkflowSchemas(def: WorkflowValidationInput): WorkflowValidationIssue[] {\n  const issues: WorkflowValidationIssue[] = [];\n  const check = (schema: JsonSchema | undefined, path: string, label: string): void => {\n    const result = validateStorableJsonSchema(schema);\n    if (result.ok) return;\n    issues.push({\n      code: 'unsupported-schema-keyword',\n      path,\n      message: `${label} uses JSON Schema keyword(s) jsonSchemaToZod cannot convert: ${result.unsupported.join(', ')}. Simplify the schema (or extend the converter).`,\n    });\n  };\n  check(def.inputSchema, 'inputSchema', 'inputSchema');\n  check(def.outputSchema, 'outputSchema', 'outputSchema');\n  if (def.stateSchema) check(def.stateSchema, 'stateSchema', 'stateSchema');\n  if (def.requestContextSchema) check(def.requestContextSchema, 'requestContextSchema', 'requestContextSchema');\n  forEachSingleStepEntryWithPath(def.graph, (entry, path) => {\n    if (entry.type === 'agent' && entry.outputSchema) {\n      check(entry.outputSchema, `${path}.outputSchema`, `step \"${entry.id}\" outputSchema`);\n    }\n  });\n  return issues;\n}\n","/**\n * Context-free structural rules: everything that can be decided from the\n * definition alone — ids, duplicates, entry placement, container arity,\n * declarative-predicate presence, nested-workflow identity, self-cycles.\n */\nimport { forEachSingleStepEntryWithPath } from '../graph';\nimport { leafEntryId } from './types';\nimport type { WorkflowValidationInput, WorkflowValidationIssue } from './types';\n\nconst TOP_LEVEL_PATH = /^graph\\.\\d+$/;\n\nexport function validateWorkflowStructure(def: WorkflowValidationInput): WorkflowValidationIssue[] {\n  const issues: WorkflowValidationIssue[] = [];\n\n  if (def.graph.length === 0) {\n    issues.push({ code: 'empty-graph', path: 'graph', message: 'Workflow graph must contain at least one step.' });\n  }\n\n  const seenIds = new Set<string>();\n  forEachSingleStepEntryWithPath(def.graph, (entry, path) => {\n    const id = leafEntryId(entry);\n    const idPath = entry.type === 'step' ? `${path}.step.id` : `${path}.id`;\n    if (!id) issues.push({ code: 'missing-step-id', path: idPath, message: 'Step id is required.' });\n    else if (seenIds.has(id))\n      issues.push({ code: 'duplicate-step-id', path: idPath, message: `Step id \"${id}\" is duplicated.` });\n    else seenIds.add(id);\n\n    if (entry.type === 'mapping' && !TOP_LEVEL_PATH.test(path)) {\n      issues.push({\n        code: 'invalid-map-placement',\n        path,\n        message: 'Persisted mapping steps must be top-level workflow entries.',\n      });\n    }\n\n    if (entry.type === 'workflow') {\n      if (entry.workflowId === def.id) {\n        issues.push({\n          code: 'self-reference',\n          path: `${path}.workflowId`,\n          message: `Step \"${entry.id}\" declares { type: \"workflow\", workflowId: \"${entry.workflowId}\" } which refers to itself. Nested workflow cycles are not allowed.`,\n        });\n      }\n    }\n  });\n\n  // Reserve sleep/sleepUntil ids before checking container ids, WITHOUT\n  // emitting issues for the sleeps themselves: stored definitions carried\n  // author-supplied sleep ids long before duplicates were validated, so\n  // flagging sleep-to-sleep (or sleep-to-leaf) collisions would reject\n  // previously-valid rows at boot. Reserving them still stops a NEW container\n  // id from squatting on a sleep id, regardless of graph order.\n  for (const entry of def.graph) {\n    if ((entry.type === 'sleep' || entry.type === 'sleepUntil') && entry.id) {\n      seenIds.add(entry.id);\n    }\n  }\n\n  def.graph.forEach((entry, index) => {\n    const path = `graph.${index}`;\n    // Container ids are optional stable addresses; when supplied they must be\n    // non-empty and unique against every other id in the workflow (leaf and\n    // sleep ids included — both passes above have populated `seenIds`).\n    if (\n      (entry.type === 'parallel' ||\n        entry.type === 'conditional' ||\n        entry.type === 'foreach' ||\n        entry.type === 'loop') &&\n      entry.id !== undefined\n    ) {\n      if (!entry.id) {\n        issues.push({\n          code: 'missing-step-id',\n          path: `${path}.id`,\n          message: 'Entry id must not be empty when supplied.',\n        });\n      } else if (seenIds.has(entry.id)) {\n        issues.push({\n          code: 'duplicate-step-id',\n          path: `${path}.id`,\n          message: `Entry id \"${entry.id}\" is duplicated.`,\n        });\n      } else {\n        seenIds.add(entry.id);\n      }\n    }\n    switch (entry.type) {\n      case 'parallel':\n      case 'conditional': {\n        if (entry.steps.length === 0) {\n          issues.push({\n            code: entry.type === 'parallel' ? 'invalid-parallel' : 'invalid-conditional',\n            path: `${path}.steps`,\n            message: `${entry.type} steps cannot be empty.`,\n          });\n        }\n        if (entry.type === 'conditional') {\n          if (!entry.predicates) {\n            issues.push({\n              code: 'invalid-conditional',\n              path,\n              message: 'Conditional entries must use declarative predicates.',\n            });\n          } else {\n            if (entry.steps.length !== entry.predicates.length) {\n              issues.push({\n                code: 'invalid-conditional',\n                path,\n                message: 'Conditional steps and predicates must be aligned.',\n              });\n            }\n            entry.predicates.forEach((predicate, predicateIndex) => {\n              if (predicate === null) {\n                issues.push({\n                  code: 'invalid-conditional',\n                  path: `${path}.predicates.${predicateIndex}`,\n                  message: 'Conditional entries must use declarative predicates.',\n                });\n              }\n            });\n          }\n        }\n        return;\n      }\n      case 'loop': {\n        if (!entry.predicate) {\n          issues.push({\n            code: 'invalid-loop',\n            path,\n            message: 'Loop entries must use a declarative predicate.',\n          });\n        }\n        return;\n      }\n      case 'foreach': {\n        if (entry.opts?.concurrency !== undefined && entry.opts.concurrency < 1) {\n          issues.push({\n            code: 'invalid-foreach',\n            path: `${path}.opts.concurrency`,\n            message: 'Concurrency must be positive.',\n          });\n        }\n        return;\n      }\n      default:\n        return;\n    }\n  });\n\n  return issues;\n}\n","/**\n * The one dynamic-workflow validation domain.\n *\n * `validateDynamicWorkflow` is the collect-mode core every surface shares:\n * structure, JSON-Schema keywords, registry references, and schema-flow\n * analysis, each emitting `{ code, path, message }` issues. UIs consume the\n * array; the save path throws via `assertValidDynamicWorkflow`.\n */\nimport { validateWorkflowRefs } from './refs';\nimport { addWorkflowValidationRepairActions } from './repair-actions';\nimport { inferGraphSchemas } from './schema-flow';\nimport { validateWorkflowSchemas } from './schemas';\nimport { validateWorkflowStructure } from './structure';\nimport type { WorkflowRegistryIndex, WorkflowValidationInput, WorkflowValidationIssue } from './types';\n\nexport type {\n  ValidatableStepFlowEntry,\n  WorkflowRegistryIndex,\n  WorkflowRegistrySchemas,\n  WorkflowValidationInput,\n  WorkflowValidationIssue,\n  WorkflowValidationIssueCode,\n  WorkflowValidationRepairAction,\n  WorkflowValidationRepairSource,\n} from './types';\nexport { validateWorkflowStructure } from './structure';\nexport { validateWorkflowRefs } from './refs';\nexport { validateWorkflowSchemas } from './schemas';\nexport { inferGraphSchemas } from './schema-flow';\nexport type { GraphSchemaInference } from './schema-flow';\nexport { schemaCompatibility, toJsonSchemaOrUndefined } from './schema-utils';\nexport type { SchemaCompatibility } from './schema-utils';\n\n/**\n * Runs every check and returns the collected issues (empty = valid).\n *\n * The registry index gates context-dependent checks: reference checks only\n * run for kinds present in the index, and schema-flow compatibility only\n * proves mismatches where schemas are known.\n */\nexport function validateDynamicWorkflow(\n  def: WorkflowValidationInput,\n  index: WorkflowRegistryIndex = {},\n): WorkflowValidationIssue[] {\n  const inference = inferGraphSchemas(def, index);\n  return addWorkflowValidationRepairActions(\n    def,\n    index,\n    [\n      ...validateWorkflowStructure(def),\n      ...validateWorkflowSchemas(def),\n      ...validateWorkflowRefs(def, index),\n      ...inference.issues,\n    ],\n    inference.stepOutputs,\n    inference.entryInputs,\n    inference.finalOutput,\n  );\n}\n\n/** Throwing presentation of {@link validateDynamicWorkflow} for the save path. */\nexport function assertValidDynamicWorkflow(def: WorkflowValidationInput, index: WorkflowRegistryIndex = {}): void {\n  const issues = validateDynamicWorkflow(def, index);\n  if (issues.length === 0) return;\n  const details = issues.map(issue => `- [${issue.code}] ${issue.path}: ${issue.message}`).join('\\n');\n  throw new Error(`Dynamic workflow \"${def.id}\" failed validation with ${issues.length} issue(s):\\n${details}`);\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,uBACd,SACA,OACM;CACN,KAAK,MAAM,SAAS,SAClB,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;GACH,MAAM,KAAK;GACX;EACF,KAAK;EACL,KAAK;GACH,MAAM,MAAM,QAAQ,KAAK;GACzB;EACF,KAAK;EACL,KAAK;GACH,MAAM,MAAM,IAAI;GAChB;EACF,KAAK;EACL,KAAK,cACH;EACF;CAIF;AAEJ;;;;;AAMA,SAAgB,yBAAyB,OAAyD;CAChG,MAAM,sBAAM,IAAI,IAAY;CAC5B,uBAAuB,QAAO,UAAS;EACrC,IAAI,MAAM,SAAS,YAAY,IAAI,IAAI,MAAM,UAAU;CACzD,CAAC;CACD,OAAO;AACT;;;;;;;;;AAUA,SAAgB,+BACd,SACA,OACM;CACN,QAAQ,SAAS,OAAO,UAAU;EAChC,MAAM,OAAO,SAAS;EACtB,QAAQ,MAAM,MAAd;GACE,KAAK;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