@sanity/workflow-engine 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"define.cjs","sources":["../src/types/enums.ts","../src/define/invariants.ts","../src/define/schema.ts","../src/define/index.ts"],"sourcesContent":["/**\n * Leaf enums — the const arrays (and their derived union types) that both\n * the authoring schema and the engine address by name.\n *\n * This module imports nothing. It is the schema-free foundation that\n * `../define/schema.ts` reads its value constants from, which is what keeps\n * the type model and the Zod schema free of an import cycle: the value edge\n * `schema.ts → enums.ts` terminates here.\n */\n\n// Task status — used by instance state. Authoring code references this\n// via `Action.setStatus`, which the Zod schema constrains to the\n// terminal subset.\nexport const TASK_STATUSES = ['pending', 'active', 'done', 'skipped', 'failed'] as const\nexport type TaskStatus = (typeof TASK_STATUSES)[number]\n\n// The three state scopes a slot can live in. Authoring (`ScopeKey`,\n// `stateRead` sources) and the engine both address slots by scope.\nexport const STATE_SCOPES = ['workflow', 'stage', 'task'] as const\nexport type StateScope = (typeof STATE_SCOPES)[number]\n\n// Document-value permissions. Grants (`Grant` in ./authorization.ts) compose\n// most-permissive-wins.\nexport const DOCUMENT_VALUE_PERMISSIONS = ['create', 'read', 'update'] as const\nexport type DocumentValuePermission = (typeof DOCUMENT_VALUE_PERMISSIONS)[number]\n\n// Mutation-guard actions — the lake operations a guard can gate. See the\n// guard types in ./authorization.ts.\nexport const MUTATION_GUARD_ACTIONS = [\n 'create',\n 'update',\n 'delete',\n 'publish',\n 'unpublish',\n] as const\nexport type MutationGuardAction = (typeof MUTATION_GUARD_ACTIONS)[number]\n","import type {z} from 'zod'\n\nimport type {Filter} from './schema.ts'\n\ntype Ctx = z.RefinementCtx\ntype IssuePath = (string | number)[]\n\ninterface StageLike {\n id: string\n kind?: string | undefined\n transitions?: {to: string; filter?: Filter | undefined}[] | undefined\n completion?: Filter | undefined\n tasks?:\n | {\n id: string\n filter?: Filter | undefined\n completeWhen?: Filter | undefined\n failWhen?: Filter | undefined\n actions?: {filter?: Filter | undefined}[] | undefined\n }[]\n | undefined\n}\n\ninterface DefinitionLike {\n initialStageId: string\n stages: StageLike[]\n predicates?: {id: string}[] | undefined\n}\n\nfunction knownList(ids: Iterable<string>): string {\n return [...ids].map((s) => `\"${s}\"`).join(', ')\n}\n\n/**\n * Collect stage ids while flagging duplicates and terminal-with-transitions,\n * plus duplicate task ids within each stage. Returns the set of declared\n * stage ids for the cross-reference checks that follow.\n */\nfunction checkStagesAndTasks(def: DefinitionLike, ctx: Ctx): Set<string> {\n const stageIds = new Set<string>()\n for (const [i, stage] of def.stages.entries()) {\n if (stageIds.has(stage.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['stages', i, 'id'],\n message: `duplicate stage id \"${stage.id}\" (already declared earlier)`,\n })\n }\n stageIds.add(stage.id)\n\n if (stage.kind === 'terminal' && stage.transitions && stage.transitions.length > 0) {\n ctx.addIssue({\n code: 'custom',\n path: ['stages', i, 'transitions'],\n message: `terminal stage \"${stage.id}\" must not declare transitions`,\n })\n }\n\n checkDuplicateTaskIds(stage, i, ctx)\n }\n return stageIds\n}\n\nfunction checkDuplicateTaskIds(stage: StageLike, i: number, ctx: Ctx): void {\n const taskIds = new Set<string>()\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n if (taskIds.has(task.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['stages', i, 'tasks', j, 'id'],\n message: `duplicate task id \"${task.id}\" in stage \"${stage.id}\"`,\n })\n }\n taskIds.add(task.id)\n }\n}\n\nfunction checkInitialStage(def: DefinitionLike, stageIds: Set<string>, ctx: Ctx): void {\n if (stageIds.has(def.initialStageId)) return\n ctx.addIssue({\n code: 'custom',\n path: ['initialStageId'],\n message:\n `initialStageId \"${def.initialStageId}\" is not a declared stage. ` +\n `Known stages: ${knownList(stageIds)}`,\n })\n}\n\nfunction checkTransitionTargets(def: DefinitionLike, stageIds: Set<string>, ctx: Ctx): void {\n for (const [i, stage] of def.stages.entries()) {\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n if (!stageIds.has(t.to)) {\n ctx.addIssue({\n code: 'custom',\n path: ['stages', i, 'transitions', k, 'to'],\n message:\n `transition target \"${t.to}\" is not a declared stage. ` +\n `Known stages: ${knownList(stageIds)}`,\n })\n }\n }\n }\n}\n\nfunction collectPredicateIds(def: DefinitionLike, ctx: Ctx): Set<string> {\n const predicateIds = new Set<string>()\n for (const [i, p] of (def.predicates ?? []).entries()) {\n if (predicateIds.has(p.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['predicates', i, 'id'],\n message: `duplicate predicate id \"${p.id}\"`,\n })\n }\n predicateIds.add(p.id)\n }\n return predicateIds\n}\n\nfunction checkFilterRefs(def: DefinitionLike, predicateIds: Set<string>, ctx: Ctx): void {\n const visit = (g: Filter | undefined, path: IssuePath) => {\n if (g === undefined || typeof g === 'string') return // inline GROQ validated at deploy\n if (!predicateIds.has(g.ref)) {\n ctx.addIssue({\n code: 'custom',\n path: [...path, 'ref'],\n message:\n `Filter references predicate \"${g.ref}\" which is not declared. ` +\n `Known predicates: ${knownList(predicateIds) || '(none)'}`,\n })\n }\n }\n\n for (const [i, stage] of def.stages.entries()) {\n visit(stage.completion, ['stages', i, 'completion'])\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n visit(task.filter, ['stages', i, 'tasks', j, 'filter'])\n visit(task.completeWhen, ['stages', i, 'tasks', j, 'completeWhen'])\n visit(task.failWhen, ['stages', i, 'tasks', j, 'failWhen'])\n for (const [a, action] of (task.actions ?? []).entries()) {\n visit(action.filter, ['stages', i, 'tasks', j, 'actions', a, 'filter'])\n }\n }\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n visit(t.filter, ['stages', i, 'transitions', k, 'filter'])\n }\n }\n}\n\n/**\n * Run every cross-field invariant of a workflow definition, emitting issues\n * with paths that land on the offending field. Split out of the schema's\n * `.superRefine` so each invariant is independently named and testable.\n */\nexport function checkWorkflowInvariants(def: DefinitionLike, ctx: Ctx): void {\n const stageIds = checkStagesAndTasks(def, ctx)\n checkInitialStage(def, stageIds, ctx)\n checkTransitionTargets(def, stageIds, ctx)\n const predicateIds = collectPredicateIds(def, ctx)\n checkFilterRefs(def, predicateIds, ctx)\n}\n","/**\n * Zod schemas for the workflow authoring surface — the things a workflow\n * author writes by hand and feeds to `defineWorkflow`. Types in this\n * file are the **canonical** authoring types: they are inferred from\n * Zod, so the runtime schema and the compile-time type cannot drift.\n *\n * Engine-produced shapes (`WorkflowInstance`, `TaskStatusEntry`,\n * `HistoryEntry`, etc.) stay as plain TS interfaces in `../types.ts` —\n * those are outputs, not inputs.\n *\n * Strictness: every object schema uses `.strict()` so unknown keys\n * produce a parse error. That catches typos like `verison: 1` instead\n * of `version: 1` at deploy time, with the path pointing exactly at\n * the offender.\n */\n\nimport {z} from 'zod'\n\nimport {\n DOCUMENT_VALUE_PERMISSIONS,\n MUTATION_GUARD_ACTIONS,\n STATE_SCOPES,\n TASK_STATUSES,\n type StateScope,\n} from '../types/enums.ts'\nimport {checkWorkflowInvariants} from './invariants.ts'\n\nconst NonEmpty = z.string().min(1, 'must be a non-empty string')\n\n/**\n * GDR (Global Document Reference) — see `../refs.ts`. URI form\n * `<scheme>:<...id-parts>`, e.g. `dataset:proj:ds:doc` or\n * `canvas:resourceId:doc`. Every cross-doc reference in the engine API\n * uses this shape.\n */\nconst GdrSchema = z\n .object({\n id: z\n .string()\n .regex(\n /^(dataset|canvas|media-library|dashboard):/,\n \"must be a GDR URI of form '<scheme>:<...id-parts>' where scheme is one of: dataset, canvas, media-library, dashboard\",\n ),\n type: NonEmpty,\n })\n .strict()\n\n// Source — typed binding union. Op fields and effect bindings resolve\n// concrete values through this discriminated union; no GROQ in the binding\n// language. Anywhere a concrete value is needed at commit time, the engine\n// resolves a Source.\n\ntype SourceInternal =\n | {source: 'literal'; value: string | number | boolean | null}\n | {source: 'param'; paramId: string}\n | {source: 'actor'}\n | {source: 'now'}\n | {source: 'self'}\n | {source: 'stageId'}\n | {\n source: 'stateRead'\n scope: StateScope\n slotId: string\n path?: string | undefined\n }\n | {source: 'effectOutput'; contextId: string; path?: string | undefined}\n /**\n * Spawn-only sources. Resolved at spawn-time inside `Spawn.forEach.as`\n * projection. `row` reads from the current iteration row (the GROQ\n * result item). `parentState` reads from the spawning parent's\n * resolved workflow-scope state — the slot envelope as on the\n * parent (`{ id, _type, value, ... }`), with an optional path dive.\n */\n | {source: 'row'; path?: string | undefined}\n | {source: 'parentState'; slotId: string; path?: string | undefined}\n | {source: 'object'; fields: Record<string, SourceInternal>}\n\nconst SourceSchema: z.ZodType<SourceInternal> = z.lazy(() =>\n z.union([\n z\n .object({\n source: z.literal('literal'),\n value: z.union([z.string(), z.number(), z.boolean(), z.null()]),\n })\n .strict(),\n z.object({source: z.literal('param'), paramId: NonEmpty}).strict(),\n z.object({source: z.literal('actor')}).strict(),\n z.object({source: z.literal('now')}).strict(),\n z.object({source: z.literal('self')}).strict(),\n z.object({source: z.literal('stageId')}).strict(),\n z\n .object({\n source: z.literal('stateRead'),\n scope: z.enum(STATE_SCOPES),\n slotId: NonEmpty,\n path: z.string().optional(),\n })\n .strict(),\n // effectsContext lookup — reads from `instance.effectsContext[id === ID].value`.\n // Used by chained effects where one handler's output feeds another's binding.\n z\n .object({\n source: z.literal('effectOutput'),\n contextId: NonEmpty,\n path: z.string().optional(),\n })\n .strict(),\n z.object({source: z.literal('row'), path: z.string().optional()}).strict(),\n z\n .object({\n source: z.literal('parentState'),\n slotId: NonEmpty,\n path: z.string().optional(),\n })\n .strict(),\n // Compound object source — resolves each field's Source recursively\n // and packages the result into a JSON object. Lets ops append rich\n // rows to `checklist` / `notes` / `assignees` slots, e.g.\n // `{ source: \"object\", fields: { signer: { source: \"actor\" },\n // at: { source: \"now\" } } }`.\n z\n .object({\n source: z.literal('object'),\n fields: z.record(NonEmpty, SourceSchema),\n })\n .strict(),\n ]),\n)\nexport type Source = SourceInternal\n\n// ScopeKey — { scope, key } addressing a state slot in one of the three\n// state scopes (workflow, stage, task).\n\nconst ScopeKeySchema = z\n .object({\n scope: z.enum(STATE_SCOPES),\n slotId: NonEmpty,\n })\n .strict()\nexport type ScopeKey = z.infer<typeof ScopeKeySchema>\n\n// Op predicates — small typed predicate for op.state.updateWhere /\n// op.state.removeWhere. Separate from filter GROQ.\n\ntype OpPredicateInternal =\n | {field: string; equals: Source}\n | {all: OpPredicateInternal[]}\n | {any: OpPredicateInternal[]}\n\nconst OpPredicateSchema: z.ZodType<OpPredicateInternal> = z.lazy(() =>\n z.union([\n z\n .object({\n field: NonEmpty,\n equals: SourceSchema,\n })\n .strict(),\n z.object({all: z.array(OpPredicateSchema)}).strict(),\n z.object({any: z.array(OpPredicateSchema)}).strict(),\n ]),\n)\nexport type OpPredicate = OpPredicateInternal\n\n// Ops — workflow.op.* primitives that run inline during an action commit.\n// Each op type has structured fields, NOT a GROQ binding language.\n\nconst OpSchema = z.discriminatedUnion('type', [\n z\n .object({\n type: z.literal('workflow.op.state.set'),\n target: ScopeKeySchema,\n value: SourceSchema,\n })\n .strict(),\n z\n .object({\n type: z.literal('workflow.op.state.append'),\n target: ScopeKeySchema,\n item: SourceSchema,\n })\n .strict(),\n z\n .object({\n type: z.literal('workflow.op.state.updateWhere'),\n target: ScopeKeySchema,\n where: OpPredicateSchema,\n merge: z.record(NonEmpty, SourceSchema),\n })\n .strict(),\n z\n .object({\n type: z.literal('workflow.op.state.removeWhere'),\n target: ScopeKeySchema,\n where: OpPredicateSchema,\n })\n .strict(),\n z\n .object({\n type: z.literal('workflow.op.status.set'),\n taskId: NonEmpty,\n status: z.enum(TASK_STATUSES),\n })\n .strict(),\n])\nexport type Op = z.infer<typeof OpSchema>\n\n// State slots — polymorphic; each variant declares its `source.kind`\n// (init / query / write / computed). Authoring shape only; engine\n// resolves slots into `ResolvedStateSlot` at runtime (types.ts).\n\nconst StateSlotSourceSchema = z.union([\n z.object({kind: z.literal('init')}).strict(),\n z\n .object({\n kind: z.literal('query'),\n query: NonEmpty,\n resource: z.union([z.literal('workflow'), z.literal('subject'), GdrSchema]).optional(),\n })\n .strict(),\n z.object({kind: z.literal('write')}).strict(),\n z.object({kind: z.literal('computed'), compute: NonEmpty}).strict(),\n /**\n * Pre-populate the slot at resolution time with a constant value.\n * Useful for stage- or task-scope slots that should start non-empty\n * (e.g. a default headline, a starting tally).\n */\n z.object({kind: z.literal('literal'), value: z.unknown()}).strict(),\n /**\n * Pre-populate by reading another already-resolved slot. `scope:\n * \"workflow\"` reads from the workflow-scope `state[]` (resolved at\n * startInstance). `scope: \"stage\"` reads from an earlier slot in\n * this same stage entry's `state[]` (sequential resolution).\n * Optional `path` selects a nested field (e.g. `path: \"id\"` on a\n * doc.ref slot).\n */\n z\n .object({\n kind: z.literal('stateRead'),\n scope: z.union([z.literal('workflow'), z.literal('stage')]),\n slotId: NonEmpty,\n path: z.string().optional(),\n })\n .strict(),\n])\nexport type StateSlotSource = z.infer<typeof StateSlotSourceSchema>\n\nconst StateSlotBase = {\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n source: StateSlotSourceSchema,\n}\n\n/**\n * Canonical set of state-slot kinds — the discriminator for both\n * authored {@link StateSlot}s and runtime `StateSlotValueMap`. Spawn\n * projections reuse it so a typo'd slot type is rejected at deploy\n * rather than silently dropped at projection time.\n */\nconst StateSlotKindSchema = z.enum([\n 'workflow.state.doc.ref',\n 'workflow.state.doc.refs',\n // Release reference. A workflow declares this slot to say \"I target a\n // Content Release\"; the runtime fills it with a specific release at\n // start time, and the engine auto-derives the instance's read\n // perspective from it.\n 'workflow.state.release.ref',\n 'workflow.state.query',\n 'workflow.state.value.string',\n 'workflow.state.value.url',\n 'workflow.state.value.number',\n 'workflow.state.value.boolean',\n 'workflow.state.value.dateTime',\n 'workflow.state.value.actor',\n 'workflow.state.checklist',\n 'workflow.state.notes',\n 'workflow.state.assignees',\n])\ntype StateSlotKind = z.infer<typeof StateSlotKindSchema>\n\nconst StateSlotSchema = z.discriminatedUnion(\n 'type',\n StateSlotKindSchema.options.map((kind) =>\n z.object({type: z.literal(kind), ...StateSlotBase}).strict(),\n ) as [\n z.ZodObject<{type: z.ZodLiteral<StateSlotKind>} & typeof StateSlotBase>,\n ...z.ZodObject<{type: z.ZodLiteral<StateSlotKind>} & typeof StateSlotBase>[],\n ],\n)\nexport type StateSlot = z.infer<typeof StateSlotSchema>\n\n// Filters & predicates\n\nexport const FilterSchema = z.union([\n // Inline GROQ — only reserved params allowed at runtime.\n NonEmpty,\n // Reference to a named predicate, optionally with named args.\n z\n .object({\n ref: NonEmpty,\n args: z.record(z.string(), z.unknown()).optional(),\n })\n .strict(),\n])\nexport type Filter = z.infer<typeof FilterSchema>\n\nconst PredicateParamSchema = z\n .object({\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n type: z.enum(['string', 'number', 'boolean', 'string[]', 'reference']),\n enum: z.array(z.string()).optional(),\n })\n .strict()\nexport type PredicateParam = z.infer<typeof PredicateParamSchema>\n\nexport const PredicateSchema = z\n .object({\n type: z.literal('workflow.predicate').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n groq: NonEmpty,\n params: z.array(PredicateParamSchema).optional(),\n })\n .strict()\nexport type Predicate = z.infer<typeof PredicateSchema>\n\n// Effects\n\nexport const EffectSchema = z\n .object({\n type: z.literal('workflow.effect').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n // Bindings resolve typed Source values at commit time, producing\n // concrete JSON in the queued effect's `params`. NO GROQ.\n bindings: z.record(z.string(), SourceSchema).optional(),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .strict()\nexport type Effect = z.infer<typeof EffectSchema>\n\n// Actions\n\nconst TerminalTaskStatus = z.enum(['done', 'skipped', 'failed'])\n\nconst PermissionSchema = z.enum(DOCUMENT_VALUE_PERMISSIONS)\n\n/**\n * Caller-supplied params declared on an action. The engine validates\n * incoming `params` against this list before running ops or queuing\n * effects: missing required params → ActionParamsInvalidError, action\n * does not commit. Resolved values feed `Source.param` lookups.\n */\nconst ActionParamSchema = z\n .object({\n type: z.literal('workflow.action.param').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n paramType: z.enum([\n 'string',\n 'number',\n 'boolean',\n 'url',\n 'dateTime',\n 'actor',\n 'doc.ref',\n 'doc.refs',\n 'json',\n ]),\n required: z.boolean().optional(),\n })\n .strict()\nexport type ActionParam = z.infer<typeof ActionParamSchema>\n\nexport const ActionSchema = z\n .object({\n type: z.literal('workflow.action').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n filter: FilterSchema.optional(),\n /** Caller-supplied params, validated before ops/effects run. */\n params: z.array(ActionParamSchema).optional(),\n /**\n * Status the task flips to when this action fires. Omit to leave\n * the task status unchanged — used by intermediate `claim` /\n * `assign` / partial-update actions where the task should stay\n * active so a later action can fire on it. Declared values must\n * be terminal (`done` / `skipped` / `failed`); the engine never\n * mid-flip back to `active` outside of the `workflow.op.status.set`\n * op explicit path.\n */\n setStatus: TerminalTaskStatus.optional(),\n /**\n * Inline state-mutation primitives executed during the action commit.\n * Each op runs against the in-memory mutation (deterministic, no\n * external I/O). Resolved Sources turn into concrete JSON before the\n * op applies. Logged on `history[]` as `workflow.history.opApplied`\n * and surfaced on the `ActionResult.ranOps`.\n */\n ops: z.array(OpSchema).optional(),\n effects: z.array(EffectSchema).optional(),\n /**\n * Role gating — OR-match against `Actor.roles[]`. If omitted, no role\n * gate. `\"*\"` in Actor.roles always matches (bench / all-access).\n */\n roles: z.array(NonEmpty).optional(),\n /**\n * When true, the actor must appear in the task's `assignees[]` (as a\n * user-kind assignee matching by id) for the action to be allowed.\n */\n requireAssignment: z.boolean().optional(),\n /**\n * Which permission on the workflow.instance document the actor must\n * hold (per supplied `grants`). Defaults to \"update\". Only checked\n * when grants are supplied at evaluate/fireAction time.\n */\n requiredPermission: PermissionSchema.optional(),\n })\n .strict()\nexport type Action = z.infer<typeof ActionSchema>\n\n// Spawn (nested workflows)\n\nconst CompletionPolicySchema = z.union([\n z.object({kind: z.literal('all')}).strict(),\n z.object({kind: z.literal('any')}).strict(),\n z\n .object({\n kind: z.literal('count'),\n n: z.number().int().positive(),\n })\n .strict(),\n])\n\n/**\n * Logical reference to a deployed workflow definition. The engine\n * resolves it at spawn time by querying its own workflow resource for\n * a matching (workflowId, tags ∩ engine.tags, version) tuple, ordering\n * by `version desc` and picking the first — or the matching `version`\n * if explicitly specified.\n *\n * Authors never have a stable GDR URI to reference (tags can be\n * renamed, workflows redeployed). They have the stable contract: the\n * `workflowId`.\n */\nconst LogicalDefinitionRefSchema = z\n .object({\n workflowId: NonEmpty,\n version: z.union([z.number().int().positive(), z.literal('latest')]).optional(),\n })\n .strict()\n\n/**\n * `forEach` — spawn fan-out projection.\n *\n * - `groq` runs against the lake (paramsForLake-stripped reserved\n * params: `$self`, `$state`, `$parent`, `$ancestors`, `$stage`,\n * `$now`). Result is an array; engine creates one child per row.\n * - `as.initialState` is a typed projection from each row to the\n * child's initial state slots. Values use the `Source` union with\n * two spawn-only variants:\n * - `{ source: \"row\", path? }` — pull from the current row.\n * - `{ source: \"parentState\", slotId, path? }` — pull from the\n * spawning parent's resolved workflow-scope state.\n * - `as.effectsContext` optionally seeds the child's effectsContext.\n *\n * The spawn does not auto-stamp anything onto the child. Whatever\n * slots the child needs, the author must declare on the child's\n * workflow definition AND project from each row via `as.initialState`.\n */\nconst SpawnForEachSchema = z\n .object({\n groq: NonEmpty,\n as: z\n .object({\n initialState: z\n .array(\n z\n .object({\n type: StateSlotKindSchema,\n id: NonEmpty,\n value: SourceSchema,\n })\n .strict(),\n )\n .optional(),\n effectsContext: z.record(z.string(), SourceSchema).optional(),\n })\n .strict(),\n })\n .strict()\n\nconst SpawnSchema = z\n .object({\n type: z.literal('workflow.spawn').optional(),\n id: z.string().optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n definitionRef: LogicalDefinitionRefSchema,\n forEach: SpawnForEachSchema,\n completionPolicy: CompletionPolicySchema.optional(),\n })\n .strict()\nexport type Spawn = z.infer<typeof SpawnSchema>\n\n// Assignees — typed. `kind: \"user\"` matches `Actor.id`; `kind: \"role\"`\n// matches if `Actor.roles[]` contains the role string.\n\nexport const AssigneeSchema = z.discriminatedUnion('kind', [\n z.object({kind: z.literal('user'), id: NonEmpty}).strict(),\n z.object({kind: z.literal('role'), role: NonEmpty}).strict(),\n])\nexport type Assignee = z.infer<typeof AssigneeSchema>\n\n// Tasks\n\nexport const TaskSchema = z\n .object({\n type: z.literal('workflow.task').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n assignees: z.array(AssigneeSchema).optional(),\n filter: FilterSchema.optional(),\n invokeOn: z.enum(['stageEnter', 'manual']).optional(),\n /**\n * Auto-completion predicate — same shape as `transition.filter`. When\n * truthy at activation or on any subsequent cascade, the engine\n * flips the task to `done` with a `{ kind: \"system\", id: \"engine.completeWhen\" }`\n * actor. A full filter, not just a wall-clock deadline.\n */\n completeWhen: FilterSchema.optional(),\n /**\n * Auto-failure predicate — symmetric to `completeWhen`. Same shape,\n * same evaluation cadence (activation + every cascade), but flips\n * the task to `failed` (not `done`) with a `{ kind: \"system\",\n * id: \"engine.failWhen\" }` actor. When both `completeWhen` and\n * `failWhen` resolve truthy on the same evaluation, `failWhen`\n * wins — failure is the more notable signal and should not be\n * silently swallowed.\n */\n failWhen: FilterSchema.optional(),\n effects: z.array(EffectSchema).optional(),\n actions: z.array(ActionSchema).optional(),\n spawns: SpawnSchema.optional(),\n contentRefs: z.array(z.unknown()).optional(),\n /** Task-scoped state slots. Resolved at task activation time. */\n state: z.array(StateSlotSchema).optional(),\n })\n .strict()\nexport type Task = z.infer<typeof TaskSchema>\n\n// Transitions\n\nexport const TransitionSchema = z\n .object({\n type: z.literal('workflow.transition').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n to: NonEmpty,\n on: z.string().optional(),\n filter: FilterSchema.optional(),\n effects: z.array(EffectSchema).optional(),\n })\n .strict()\nexport type Transition = z.infer<typeof TransitionSchema>\n\n// Guards — lake mutation guards (Content Lake). DISTINCT from `Filter`\n// above: a `Filter` is the engine's in-memory soft predicate that gates\n// transitions/tasks/actions; a `Guard` compiles to a `temp.system.guard`\n// document the lake evaluates at mutation time and that fails closed.\n//\n// The authoring shape is match + predicate + metadata. Targets in\n// `match.idRefs` are `Source`s resolved at deploy — `{source:\"self\"}`\n// targets the workflow instance; a `stateRead` of a doc-ref slot targets that\n// doc. The engine resolves each Source to a GDR, then splits it into the guard's\n// resource (resourceType/resourceId — the engine's outer-layer encapsulation;\n// the content lake is per-datasource) plus a BARE id. A GDR never appears in\n// `predicate`. All idRefs of one guard must resolve to the same resource (a\n// guard is single-resource).\n\nconst GuardActionSchema = z.enum(MUTATION_GUARD_ACTIONS)\nexport type GuardAction = z.infer<typeof GuardActionSchema>\n\nconst GuardMatchSchema = z\n .object({\n /** Subject `_type`(s); empty matches any type. */\n types: z.array(NonEmpty).optional(),\n /** Target docs as `Source`s resolved at deploy to bare ids + the resource. */\n idRefs: z.array(SourceSchema).optional(),\n /** Glob id patterns (bare, resource-local). */\n idPatterns: z.array(NonEmpty).optional(),\n actions: z.array(GuardActionSchema).min(1, 'a guard must match at least one action'),\n })\n .strict()\nexport type GuardMatch = z.infer<typeof GuardMatchSchema>\n\nconst GuardSchema = z\n .object({\n name: z.string().optional(),\n description: z.string().optional(),\n match: GuardMatchSchema,\n /**\n * Lake GROQ predicate. Reads `document.before`/`document.after`, `mutation`,\n * `guard`, and `identity()`. Bare ids/fields only — no GDRs. Omitted or\n * empty means UNCONDITIONAL DENY.\n */\n predicate: z.string().optional(),\n /**\n * Projected workflow state the predicate reads as `guard.metadata.*`. Values\n * are `Source`s resolved at deploy and re-synced by the engine. Copied data,\n * never a cross-resource pointer.\n */\n metadata: z.record(NonEmpty, SourceSchema).optional(),\n })\n .strict()\nexport type Guard = z.infer<typeof GuardSchema>\n\n// Stages\n\nconst StageKindSchema = z.enum(['initial', 'intermediate', 'terminal', 'waiting'])\nexport type StageKind = z.infer<typeof StageKindSchema>\n\nexport const StageSchema = z\n .object({\n type: z.literal('workflow.stage').optional(),\n id: NonEmpty,\n title: z.string().optional(),\n description: z.string().optional(),\n kind: StageKindSchema.optional(),\n tasks: z.array(TaskSchema).optional(),\n transitions: z.array(TransitionSchema).optional(),\n completion: FilterSchema.optional(),\n onEnter: z.array(EffectSchema).optional(),\n onExit: z.array(EffectSchema).optional(),\n /**\n * Lake mutation guards active while this stage holds. Each compiles to a\n * `temp.system.guard` doc deployed on stage entry and retracted on exit.\n * Plural because one stage's intent may span resources (one guard each).\n */\n guards: z.array(GuardSchema).optional(),\n contentRefs: z.array(z.unknown()).optional(),\n /** Stage-scoped state slots. Resolved at stage entry and persisted on\n * the StageEntry. */\n state: z.array(StateSlotSchema).optional(),\n })\n .strict()\nexport type Stage = z.infer<typeof StageSchema>\n\n// Workflow definition (the root)\n\nconst WorkflowDefinitionShape = z\n .object({\n workflowId: NonEmpty,\n version: z.number().int().positive(),\n title: NonEmpty,\n description: z.string().optional(),\n initialStageId: NonEmpty,\n /**\n * Workflow-level state slots. Persist for the instance lifetime.\n * Every stage's filters/ops can read them via\n * `*[_id == $self][0].state[key == \"<key>\"][0].value`. Init-sourced\n * slots are supplied at `startInstance` via `initialState`.\n */\n state: z.array(StateSlotSchema).optional(),\n stages: z.array(StageSchema).min(1, 'must declare at least one stage'),\n predicates: z.array(PredicateSchema).optional(),\n })\n .strict()\n\n/**\n * The full schema, with cross-field invariants enforced via `.superRefine`\n * so the error path lands exactly on the offending field.\n *\n * Invariants checked:\n * - Every stage id is unique\n * - `initialStageId` references a declared stage\n * - Within each stage, task ids are unique\n * - Every `transition.to` references a declared stage\n * - Every `predicate.id` is unique\n * - Every `Filter.ref` resolves to a declared predicate id\n * - At most one terminal-style stage per `kind: terminal` is fine,\n * but terminal stages must not declare transitions (a transition\n * out of a terminal is nonsense — caught here, not at runtime).\n */\nexport const WorkflowDefinitionSchema = WorkflowDefinitionShape.superRefine(checkWorkflowInvariants)\n\n/**\n * Workflow definition — inferred from the Zod schema so authoring types\n * and runtime validation share one source of truth.\n */\nexport type WorkflowDefinition = z.infer<typeof WorkflowDefinitionSchema>\n\n// Error formatting — turn a ZodError into a multi-line, path-prefixed\n// message that points at the exact field the author got wrong.\n\nexport function formatZodError(error: z.ZodError, label: string): string {\n const lines = error.issues.map((issue) => {\n const path = issue.path.length === 0 ? '(root)' : formatPath(issue.path)\n return ` - ${path}: ${issue.message}`\n })\n return `${label} failed validation (${error.issues.length} issue${\n error.issues.length === 1 ? '' : 's'\n }):\\n${lines.join('\\n')}`\n}\n\nfunction formatPath(path: ReadonlyArray<PropertyKey>): string {\n let out = ''\n for (const seg of path) {\n if (typeof seg === 'number') out += `[${seg}]`\n else out += out.length === 0 ? String(seg) : `.${String(seg)}`\n }\n return out\n}\n","/**\n * Authoring helpers — Zod-first.\n *\n * The schemas in `./schema.ts` are the canonical source of truth for\n * what a workflow author may write. The `define*` helpers here are\n * thin Zod pass-throughs: each one validates its argument against the\n * corresponding schema and returns the result. Errors come back with\n * path-prefixed messages so a typo in `stages[2].tasks[0].actions[1].filter.ref`\n * lands with that exact location.\n *\n * **Why a `define*` per authoring kind.** Long-term, workflows are\n * composed from smaller building blocks — stages, tasks, actions,\n * transitions, predicates, filters, assignees. Each kind is its own\n * authored unit. `defineWorkflow` is just the top-level composer. The\n * companion helpers exist so:\n *\n * 1. Developers can author and unit-test individual building blocks\n * in isolation (a \"draft stage\", a \"two-reviewer approval task\")\n * using the same Zod validation the engine applies at deploy.\n * 2. When 0.2 adds reusable building-block document types, the same\n * helpers transparently grow the ability to deploy each kind as\n * its own document — call sites don't change.\n *\n * Engine-produced shapes (`WorkflowInstance`, `TaskStatusEntry`, etc.)\n * remain plain TS interfaces in `../types.ts`.\n */\n\nimport type {z} from 'zod'\n\nimport {\n ActionSchema,\n AssigneeSchema,\n EffectSchema,\n FilterSchema,\n PredicateSchema,\n StageSchema,\n TaskSchema,\n TransitionSchema,\n WorkflowDefinitionSchema,\n formatZodError,\n type Action,\n type Assignee,\n type Effect,\n type Filter,\n type Predicate,\n type Stage,\n type Task,\n type Transition,\n type WorkflowDefinition,\n} from './schema.ts'\n\n// `defineWorkflow` — the top-level composer\n\n/**\n * Validate and return a workflow definition. Throws with a formatted,\n * path-prefixed error message if validation fails.\n *\n * Example error:\n *\n * ```\n * defineWorkflow(\"article-review\") failed validation (2 issues):\n * - stages[1].transitions[0].to: transition target \"ready\" is not a declared stage. Known stages: \"drafting\", \"review\", \"approved\"\n * - stages[0].tasks[0].actions[0].filter.ref: Filter references predicate \"allTaskDone\" which is not declared. Known predicates: \"allTasksDone\"\n * ```\n */\nexport function defineWorkflow(definition: WorkflowDefinition): WorkflowDefinition {\n return parseOrThrow(\n WorkflowDefinitionSchema,\n definition,\n typeof (definition as {workflowId?: unknown}).workflowId === 'string'\n ? `defineWorkflow(\"${(definition as {workflowId: string}).workflowId}\")`\n : 'defineWorkflow',\n )\n}\n\n// Companion `define*` helpers — one per authoring kind\n\n/**\n * Validate and return a workflow stage. Useful for authoring a stage\n * in isolation (reusable across workflows, unit-testable on its own)\n * and then composing it inside a `defineWorkflow` call.\n */\nexport function defineStage(stage: Stage): Stage {\n return parseOrThrow(StageSchema, stage, labelFor('defineStage', stage, 'id'))\n}\n\n/**\n * Validate and return a workflow task. Task ids only need to be unique\n * within a stage, so the same task definition can appear in multiple\n * stages of the same workflow.\n */\nexport function defineTask(task: Task): Task {\n return parseOrThrow(TaskSchema, task, labelFor('defineTask', task, 'id'))\n}\n\n/**\n * Validate and return a workflow action. Actions are typically defined\n * inline inside a task; this helper exists for unit testing a single\n * action's shape (especially when it carries gates and effects).\n */\nexport function defineAction(action: Action): Action {\n return parseOrThrow(ActionSchema, action, labelFor('defineAction', action, 'id'))\n}\n\n/**\n * Validate and return a stage transition. Useful when a transition's\n * filter or effects warrant their own test fixture.\n */\nexport function defineTransition(transition: Transition): Transition {\n return parseOrThrow(\n TransitionSchema,\n transition,\n typeof (transition as {id?: unknown}).id === 'string'\n ? `defineTransition(\"${(transition as {id: string}).id}\")`\n : typeof (transition as {to?: unknown}).to === 'string'\n ? `defineTransition(→ \"${(transition as {to: string}).to}\")`\n : 'defineTransition',\n )\n}\n\n/**\n * Validate and return a filter. Filters are GROQ strings or references\n * to named predicates; this helper accepts both forms.\n */\nexport function defineFilter(filter: Filter): Filter {\n return parseOrThrow(FilterSchema, filter, 'defineFilter')\n}\n\n/**\n * Validate and return an assignee. Either a user (`kind: \"user\"` + id)\n * or a role (`kind: \"role\"` + role).\n */\nexport function defineAssignee(assignee: Assignee): Assignee {\n return parseOrThrow(AssigneeSchema, assignee, 'defineAssignee')\n}\n\n/**\n * Validate and return a predicate. Predicates are the named-library\n * counterpart to inline GROQ filters.\n */\nexport function definePredicate(predicate: Predicate): Predicate {\n return parseOrThrow(PredicateSchema, predicate, labelFor('definePredicate', predicate, 'id'))\n}\n\n/**\n * Validate and return an effect declaration — the inline shape that\n * appears on stages / tasks / actions in a workflow definition. Not\n * to be confused with `defineEffectDescriptor` (below), which is for\n * registering a runtime handler.\n */\nexport function defineEffect(effect: Effect): Effect {\n return parseOrThrow(EffectSchema, effect, labelFor('defineEffect', effect, 'id'))\n}\n\n// Effect handler descriptor (runtime side)\n\n/**\n * Effect handler descriptor, registered by the runtime. The schema only\n * stores the `name` reference (an inline `Effect`); the description and\n * param shape live in the registry, which the SDK snapshots into\n * `pendingEffects[]` at queue time.\n *\n * For now this is metadata-only — actual handler invocation is the\n * runtime's job, not this engine's.\n */\nexport interface EffectDescriptor {\n name: string\n description?: string\n params?: EffectDescriptorParam[]\n}\n\nexport interface EffectDescriptorParam {\n name: string\n type: 'string' | 'number' | 'boolean' | 'object' | 'string[]'\n required?: boolean\n description?: string\n}\n\nexport function defineEffectDescriptor(descriptor: EffectDescriptor): EffectDescriptor {\n if (!descriptor.name) throw new Error('EffectDescriptor missing name')\n return descriptor\n}\n\n// Internal — shared parse + label\n\nfunction parseOrThrow<T>(schema: z.ZodType<T>, input: T, label: string): T {\n const result = schema.safeParse(input)\n if (!result.success) {\n throw new Error(formatZodError(result.error, label))\n }\n return result.data\n}\n\nfunction labelFor(fn: string, value: unknown, key: string): string {\n if (value && typeof value === 'object' && key in value) {\n const v = (value as Record<string, unknown>)[key]\n if (typeof v === 'string') return `${fn}(\"${v}\")`\n }\n return fn\n}\n"],"names":["z"],"mappings":";;;AAaO,MAAM,gBAAgB,CAAC,WAAW,UAAU,QAAQ,WAAW,QAAQ,GAKjE,eAAe,CAAC,YAAY,SAAS,MAAM,GAK3C,6BAA6B,CAAC,UAAU,QAAQ,QAAQ,GAKxD,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;ACLA,SAAS,UAAU,KAA+B;AAChD,SAAO,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,EAAE,KAAK,IAAI;AAChD;AAOA,SAAS,oBAAoB,KAAqB,KAAuB;AACvE,QAAM,+BAAe,IAAA;AACrB,aAAW,CAAC,GAAG,KAAK,KAAK,IAAI,OAAO,QAAA;AAC9B,aAAS,IAAI,MAAM,EAAE,KACvB,IAAI,SAAS;AAAA,MACX,MAAM;AAAA,MACN,MAAM,CAAC,UAAU,GAAG,IAAI;AAAA,MACxB,SAAS,uBAAuB,MAAM,EAAE;AAAA,IAAA,CACzC,GAEH,SAAS,IAAI,MAAM,EAAE,GAEjB,MAAM,SAAS,cAAc,MAAM,eAAe,MAAM,YAAY,SAAS,KAC/E,IAAI,SAAS;AAAA,MACX,MAAM;AAAA,MACN,MAAM,CAAC,UAAU,GAAG,aAAa;AAAA,MACjC,SAAS,mBAAmB,MAAM,EAAE;AAAA,IAAA,CACrC,GAGH,sBAAsB,OAAO,GAAG,GAAG;AAErC,SAAO;AACT;AAEA,SAAS,sBAAsB,OAAkB,GAAW,KAAgB;AAC1E,QAAM,8BAAc,IAAA;AACpB,aAAW,CAAC,GAAG,IA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SAAO,aAAa,gBAAgB,UAAU,gBAAgB;AAChE;AAMO,SAAS,gBAAgB,WAAiC;AAC/D,SAAO,aAAa,iBAAiB,WAAW,SAAS,mBAAmB,WAAW,IAAI,CAAC;AAC9F;AAQO,SAAS,aAAa,QAAwB;AACnD,SAAO,aAAa,cAAc,QAAQ,SAAS,gBAAgB,QAAQ,IAAI,CAAC;AAClF;AA0BO,SAAS,uBAAuB,YAAgD;AACrF,MAAI,CAAC,WAAW,KAAM,OAAM,IAAI,MAAM,+BAA+B;AACrE,SAAO;AACT;AAIA,SAAS,aAAgB,QAAsB,OAAU,OAAkB;AACzE,QAAM,SAAS,OAAO,UAAU,KAAK;AACrC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,eAAe,OAAO,OAAO,KAAK,CAAC;AAErD,SAAO,OAAO;AAChB;AAEA,SAAS,SAAS,IAAY,OAAgB,KAAqB;AACjE,MAAI,SAAS,OAAO,SAAU,YAAY,OAAO,OAAO;AACtD,UAAM,IAAK,MAAkC,GAAG;AAChD,QAAI,OAAO,KAAM,iBAAiB,GAAG,EAAE,KAAK,CAAC;AAAA,EAC/C;AACA,SAAO;AACT;;;;;;;;;;;"}
1
+ {"version":3,"file":"define.cjs","sources":["../src/define/invariants.ts","../src/types/enums.ts","../src/define/schema.ts","../src/define/index.ts"],"sourcesContent":["import type {Filter, ValidationIssue} from './schema.ts'\n\ntype IssuePath = (string | number)[]\n\ninterface StageLike {\n id: string\n kind?: string | undefined\n transitions?: {to: string; filter?: Filter | undefined}[] | undefined\n completion?: Filter | undefined\n tasks?:\n | {\n id: string\n filter?: Filter | undefined\n completeWhen?: Filter | undefined\n failWhen?: Filter | undefined\n actions?: {filter?: Filter | undefined}[] | undefined\n }[]\n | undefined\n}\n\ninterface DefinitionLike {\n initialStageId: string\n stages: StageLike[]\n predicates?: {id: string}[] | undefined\n}\n\nfunction knownList(ids: Iterable<string>): string {\n return [...ids].map((s) => `\"${s}\"`).join(', ')\n}\n\n/**\n * Collect stage ids while flagging duplicates and terminal-with-transitions,\n * plus duplicate task ids within each stage. Returns the set of declared\n * stage ids for the cross-reference checks that follow.\n */\nfunction checkStagesAndTasks(def: DefinitionLike, issues: ValidationIssue[]): Set<string> {\n const stageIds = new Set<string>()\n for (const [i, stage] of def.stages.entries()) {\n if (stageIds.has(stage.id)) {\n issues.push({\n path: ['stages', i, 'id'],\n message: `duplicate stage id \"${stage.id}\" (already declared earlier)`,\n })\n }\n stageIds.add(stage.id)\n\n if (stage.kind === 'terminal' && stage.transitions && stage.transitions.length > 0) {\n issues.push({\n path: ['stages', i, 'transitions'],\n message: `terminal stage \"${stage.id}\" must not declare transitions`,\n })\n }\n\n checkDuplicateTaskIds(stage, i, issues)\n }\n return stageIds\n}\n\nfunction checkDuplicateTaskIds(stage: StageLike, i: number, issues: ValidationIssue[]): void {\n const taskIds = new Set<string>()\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n if (taskIds.has(task.id)) {\n issues.push({\n path: ['stages', i, 'tasks', j, 'id'],\n message: `duplicate task id \"${task.id}\" in stage \"${stage.id}\"`,\n })\n }\n taskIds.add(task.id)\n }\n}\n\nfunction checkInitialStage(\n def: DefinitionLike,\n stageIds: Set<string>,\n issues: ValidationIssue[],\n): void {\n if (stageIds.has(def.initialStageId)) return\n issues.push({\n path: ['initialStageId'],\n message:\n `initialStageId \"${def.initialStageId}\" is not a declared stage. ` +\n `Known stages: ${knownList(stageIds)}`,\n })\n}\n\nfunction checkTransitionTargets(\n def: DefinitionLike,\n stageIds: Set<string>,\n issues: ValidationIssue[],\n): void {\n for (const [i, stage] of def.stages.entries()) {\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n if (!stageIds.has(t.to)) {\n issues.push({\n path: ['stages', i, 'transitions', k, 'to'],\n message:\n `transition target \"${t.to}\" is not a declared stage. ` +\n `Known stages: ${knownList(stageIds)}`,\n })\n }\n }\n }\n}\n\nfunction collectPredicateIds(def: DefinitionLike, issues: ValidationIssue[]): Set<string> {\n const predicateIds = new Set<string>()\n for (const [i, p] of (def.predicates ?? []).entries()) {\n if (predicateIds.has(p.id)) {\n issues.push({\n path: ['predicates', i, 'id'],\n message: `duplicate predicate id \"${p.id}\"`,\n })\n }\n predicateIds.add(p.id)\n }\n return predicateIds\n}\n\nfunction checkFilterRefs(\n def: DefinitionLike,\n predicateIds: Set<string>,\n issues: ValidationIssue[],\n): void {\n const visit = (g: Filter | undefined, path: IssuePath) => {\n if (g === undefined || typeof g === 'string') return // inline GROQ validated at deploy\n if (!predicateIds.has(g.ref)) {\n issues.push({\n path: [...path, 'ref'],\n message:\n `Filter references predicate \"${g.ref}\" which is not declared. ` +\n `Known predicates: ${knownList(predicateIds) || '(none)'}`,\n })\n }\n }\n\n for (const [i, stage] of def.stages.entries()) {\n visit(stage.completion, ['stages', i, 'completion'])\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n visit(task.filter, ['stages', i, 'tasks', j, 'filter'])\n visit(task.completeWhen, ['stages', i, 'tasks', j, 'completeWhen'])\n visit(task.failWhen, ['stages', i, 'tasks', j, 'failWhen'])\n for (const [a, action] of (task.actions ?? []).entries()) {\n visit(action.filter, ['stages', i, 'tasks', j, 'actions', a, 'filter'])\n }\n }\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n visit(t.filter, ['stages', i, 'transitions', k, 'filter'])\n }\n }\n}\n\n/**\n * Run every cross-field invariant of a workflow definition, returning issues\n * whose paths land on the offending field. Kept separate from the structural\n * schema so each invariant is independently named and testable, and runs only\n * after the structural parse succeeds.\n */\nexport function checkWorkflowInvariants(def: DefinitionLike): ValidationIssue[] {\n const issues: ValidationIssue[] = []\n const stageIds = checkStagesAndTasks(def, issues)\n checkInitialStage(def, stageIds, issues)\n checkTransitionTargets(def, stageIds, issues)\n const predicateIds = collectPredicateIds(def, issues)\n checkFilterRefs(def, predicateIds, issues)\n return issues\n}\n","/**\n * Leaf enums — the const arrays (and their derived union types) that both\n * the authoring schema and the engine address by name.\n *\n * This module imports nothing. It is the schema-free foundation that\n * `../define/schema.ts` reads its value constants from, which is what keeps\n * the type model and the valibot schema free of an import cycle: the value edge\n * `schema.ts → enums.ts` terminates here.\n */\n\n// Task status — used by instance state. Authoring code references this\n// via `Action.setStatus`, which the valibot schema constrains to the\n// terminal subset.\nexport const TASK_STATUSES = ['pending', 'active', 'done', 'skipped', 'failed'] as const\nexport type TaskStatus = (typeof TASK_STATUSES)[number]\n\n// The three state scopes a slot can live in. Authoring (`ScopeKey`,\n// `stateRead` sources) and the engine both address slots by scope.\nexport const STATE_SCOPES = ['workflow', 'stage', 'task'] as const\nexport type StateScope = (typeof STATE_SCOPES)[number]\n\n// Document-value permissions. Grants (`Grant` in ./authorization.ts) compose\n// most-permissive-wins.\nexport const DOCUMENT_VALUE_PERMISSIONS = ['create', 'read', 'update'] as const\nexport type DocumentValuePermission = (typeof DOCUMENT_VALUE_PERMISSIONS)[number]\n\n// Mutation-guard actions — the lake operations a guard can gate. See the\n// guard types in ./authorization.ts.\nexport const MUTATION_GUARD_ACTIONS = [\n 'create',\n 'update',\n 'delete',\n 'publish',\n 'unpublish',\n] as const\nexport type MutationGuardAction = (typeof MUTATION_GUARD_ACTIONS)[number]\n","/**\n * Valibot schemas for the workflow authoring surface — the things a workflow\n * author writes by hand and feeds to `defineWorkflow`. Types in this\n * file are the **canonical** authoring types: they are inferred from\n * the schemas, so the runtime schema and the compile-time type cannot\n * drift.\n *\n * Engine-produced shapes (`WorkflowInstance`, `TaskStatusEntry`,\n * `HistoryEntry`, etc.) stay as plain TS interfaces in `../types.ts` —\n * those are outputs, not inputs.\n *\n * Strictness: every object schema is `v.strictObject` so unknown keys\n * produce a parse error. That catches typos like `verison: 1` instead\n * of `version: 1` at deploy time, with the path pointing exactly at\n * the offender.\n */\n\nimport * as v from 'valibot'\n\nimport {\n DOCUMENT_VALUE_PERMISSIONS,\n MUTATION_GUARD_ACTIONS,\n STATE_SCOPES,\n TASK_STATUSES,\n type StateScope,\n} from '../types/enums.ts'\n\nconst NonEmpty = v.pipe(v.string(), v.minLength(1, 'must be a non-empty string'))\n\nconst PositiveInt = v.pipe(v.number(), v.integer(), v.minValue(1))\n\n/**\n * Picklist with a zod-compatible \"Invalid option\" message that lists every\n * allowed value, so a typo'd discriminator or enum lands with a message an\n * author can act on (e.g. `Invalid option: expected one of \"done\"|\"skipped\"`).\n */\nfunction picklist<const TOptions extends readonly [string, ...string[]]>(options: TOptions) {\n return v.picklist(\n options,\n `Invalid option: expected one of ${options.map((o) => `\"${o}\"`).join('|')}`,\n )\n}\n\n/**\n * GDR (Global Document Reference) — see `../refs.ts`. URI form\n * `<scheme>:<...id-parts>`, e.g. `dataset:proj:ds:doc` or\n * `canvas:resourceId:doc`. Every cross-doc reference in the engine API\n * uses this shape.\n */\nconst GdrSchema = v.strictObject({\n id: v.pipe(\n v.string(),\n v.regex(\n /^(dataset|canvas|media-library|dashboard):/,\n \"must be a GDR URI of form '<scheme>:<...id-parts>' where scheme is one of: dataset, canvas, media-library, dashboard\",\n ),\n ),\n type: NonEmpty,\n})\n\n// Source — typed binding union. Op fields and effect bindings resolve\n// concrete values through this discriminated union; no GROQ in the binding\n// language. Anywhere a concrete value is needed at commit time, the engine\n// resolves a Source.\n\ntype SourceInternal =\n | {source: 'literal'; value: string | number | boolean | null}\n | {source: 'param'; paramId: string}\n | {source: 'actor'}\n | {source: 'now'}\n | {source: 'self'}\n | {source: 'stageId'}\n | {\n source: 'stateRead'\n scope: StateScope\n slotId: string\n path?: string | undefined\n }\n | {source: 'effectOutput'; contextId: string; path?: string | undefined}\n /**\n * Spawn-only sources. Resolved at spawn-time inside `Spawn.forEach.as`\n * projection. `row` reads from the current iteration row (the GROQ\n * result item). `parentState` reads from the spawning parent's\n * resolved workflow-scope state — the slot envelope as on the\n * parent (`{ id, _type, value, ... }`), with an optional path dive.\n */\n | {source: 'row'; path?: string | undefined}\n | {source: 'parentState'; slotId: string; path?: string | undefined}\n | {source: 'object'; fields: Record<string, SourceInternal>}\n\nconst SourceSchema: v.GenericSchema<SourceInternal> = v.lazy(() =>\n v.union([\n v.strictObject({\n source: v.literal('literal'),\n value: v.union([v.string(), v.number(), v.boolean(), v.null()]),\n }),\n v.strictObject({source: v.literal('param'), paramId: NonEmpty}),\n v.strictObject({source: v.literal('actor')}),\n v.strictObject({source: v.literal('now')}),\n v.strictObject({source: v.literal('self')}),\n v.strictObject({source: v.literal('stageId')}),\n v.strictObject({\n source: v.literal('stateRead'),\n scope: picklist(STATE_SCOPES),\n slotId: NonEmpty,\n path: v.optional(v.string()),\n }),\n // effectsContext lookup — reads from `instance.effectsContext[id === ID].value`.\n // Used by chained effects where one handler's output feeds another's binding.\n v.strictObject({\n source: v.literal('effectOutput'),\n contextId: NonEmpty,\n path: v.optional(v.string()),\n }),\n v.strictObject({source: v.literal('row'), path: v.optional(v.string())}),\n v.strictObject({\n source: v.literal('parentState'),\n slotId: NonEmpty,\n path: v.optional(v.string()),\n }),\n // Compound object source — resolves each field's Source recursively\n // and packages the result into a JSON object. Lets ops append rich\n // rows to `checklist` / `notes` / `assignees` slots, e.g.\n // `{ source: \"object\", fields: { signer: { source: \"actor\" },\n // at: { source: \"now\" } } }`.\n v.strictObject({\n source: v.literal('object'),\n fields: v.record(NonEmpty, SourceSchema),\n }),\n ]),\n)\nexport type Source = SourceInternal\n\n// ScopeKey — { scope, key } addressing a state slot in one of the three\n// state scopes (workflow, stage, task).\n\nconst ScopeKeySchema = v.strictObject({\n scope: picklist(STATE_SCOPES),\n slotId: NonEmpty,\n})\nexport type ScopeKey = v.InferOutput<typeof ScopeKeySchema>\n\n// Op predicates — small typed predicate for op.state.updateWhere /\n// op.state.removeWhere. Separate from filter GROQ.\n\ntype OpPredicateInternal =\n | {field: string; equals: Source}\n | {all: OpPredicateInternal[]}\n | {any: OpPredicateInternal[]}\n\nconst OpPredicateSchema: v.GenericSchema<OpPredicateInternal> = v.lazy(() =>\n v.union([\n v.strictObject({\n field: NonEmpty,\n equals: SourceSchema,\n }),\n v.strictObject({all: v.array(OpPredicateSchema)}),\n v.strictObject({any: v.array(OpPredicateSchema)}),\n ]),\n)\nexport type OpPredicate = OpPredicateInternal\n\n// Ops — workflow.op.* primitives that run inline during an action commit.\n// Each op type has structured fields, NOT a GROQ binding language.\n\nconst OpSchema = v.variant('type', [\n v.strictObject({\n type: v.literal('workflow.op.state.set'),\n target: ScopeKeySchema,\n value: SourceSchema,\n }),\n v.strictObject({\n type: v.literal('workflow.op.state.append'),\n target: ScopeKeySchema,\n item: SourceSchema,\n }),\n v.strictObject({\n type: v.literal('workflow.op.state.updateWhere'),\n target: ScopeKeySchema,\n where: OpPredicateSchema,\n merge: v.record(NonEmpty, SourceSchema),\n }),\n v.strictObject({\n type: v.literal('workflow.op.state.removeWhere'),\n target: ScopeKeySchema,\n where: OpPredicateSchema,\n }),\n v.strictObject({\n type: v.literal('workflow.op.status.set'),\n taskId: NonEmpty,\n status: picklist(TASK_STATUSES),\n }),\n])\nexport type Op = v.InferOutput<typeof OpSchema>\n\n// State slots — each declares its `source.kind` (init / query / write /\n// literal / stateRead). Authoring shape only; engine resolves slots into\n// `ResolvedStateSlot` at runtime (types.ts).\n\nconst StateSlotSourceSchema = v.union([\n v.strictObject({kind: v.literal('init')}),\n v.strictObject({\n kind: v.literal('query'),\n query: NonEmpty,\n resource: v.optional(v.union([v.literal('workflow'), v.literal('subject'), GdrSchema])),\n }),\n v.strictObject({kind: v.literal('write')}),\n /**\n * Pre-populate the slot at resolution time with a constant value.\n * Useful for stage- or task-scope slots that should start non-empty\n * (e.g. a default headline, a starting tally).\n */\n v.strictObject({kind: v.literal('literal'), value: v.unknown()}),\n /**\n * Pre-populate by reading another already-resolved slot. `scope:\n * \"workflow\"` reads from the workflow-scope `state[]` (resolved at\n * startInstance). `scope: \"stage\"` reads from an earlier slot in\n * this same stage entry's `state[]` (sequential resolution).\n * Optional `path` selects a nested field (e.g. `path: \"id\"` on a\n * doc.ref slot).\n */\n v.strictObject({\n kind: v.literal('stateRead'),\n scope: v.union([v.literal('workflow'), v.literal('stage')]),\n slotId: NonEmpty,\n path: v.optional(v.string()),\n }),\n])\nexport type StateSlotSource = v.InferOutput<typeof StateSlotSourceSchema>\n\n/**\n * Canonical set of state-slot kinds — the discriminator for both\n * authored {@link StateSlot}s and runtime `StateSlotValueMap`. Spawn\n * projections reuse it so a typo'd slot type is rejected at deploy\n * rather than silently dropped at projection time.\n */\nconst StateSlotKindSchema = picklist([\n 'workflow.state.doc.ref',\n 'workflow.state.doc.refs',\n // Release reference. A workflow declares this slot to say \"I target a\n // Content Release\"; the runtime fills it with a specific release at\n // start time, and the engine auto-derives the instance's read\n // perspective from it.\n 'workflow.state.release.ref',\n 'workflow.state.query',\n 'workflow.state.value.string',\n 'workflow.state.value.url',\n 'workflow.state.value.number',\n 'workflow.state.value.boolean',\n 'workflow.state.value.dateTime',\n 'workflow.state.value.actor',\n 'workflow.state.checklist',\n 'workflow.state.notes',\n 'workflow.state.assignees',\n])\n\n// Every kind shares one shape — only the `type` discriminator differs —\n// so a single object keyed by the kind picklist expresses the slot\n// exactly, and a typo'd `type` is rejected with an \"Invalid option\" path.\nconst StateSlotSchema = v.strictObject({\n type: StateSlotKindSchema,\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n source: StateSlotSourceSchema,\n})\nexport type StateSlot = v.InferOutput<typeof StateSlotSchema>\n\n// Filters & predicates\n\nexport const FilterSchema = v.union([\n // Inline GROQ — only reserved params allowed at runtime.\n NonEmpty,\n // Reference to a named predicate, optionally with named args.\n v.strictObject({\n ref: NonEmpty,\n args: v.optional(v.record(v.string(), v.unknown())),\n }),\n])\nexport type Filter = v.InferOutput<typeof FilterSchema>\n\nconst PredicateParamSchema = v.strictObject({\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n type: picklist(['string', 'number', 'boolean', 'string[]', 'reference']),\n enum: v.optional(v.array(v.string())),\n})\nexport type PredicateParam = v.InferOutput<typeof PredicateParamSchema>\n\nexport const PredicateSchema = v.strictObject({\n type: v.optional(v.literal('workflow.predicate')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n groq: NonEmpty,\n params: v.optional(v.array(PredicateParamSchema)),\n})\nexport type Predicate = v.InferOutput<typeof PredicateSchema>\n\n// Effects\n\nexport const EffectSchema = v.strictObject({\n type: v.optional(v.literal('workflow.effect')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n // Bindings resolve typed Source values at commit time, producing\n // concrete JSON in the queued effect's `params`. NO GROQ.\n bindings: v.optional(v.record(v.string(), SourceSchema)),\n input: v.optional(v.record(v.string(), v.unknown())),\n})\nexport type Effect = v.InferOutput<typeof EffectSchema>\n\n// Actions\n\nconst TerminalTaskStatus = picklist(['done', 'skipped', 'failed'])\n\nconst PermissionSchema = picklist(DOCUMENT_VALUE_PERMISSIONS)\n\n/**\n * Caller-supplied params declared on an action. The engine validates\n * incoming `params` against this list before running ops or queuing\n * effects: missing required params → ActionParamsInvalidError, action\n * does not commit. Resolved values feed `Source.param` lookups.\n */\nconst ActionParamSchema = v.strictObject({\n type: v.optional(v.literal('workflow.action.param')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n paramType: picklist([\n 'string',\n 'number',\n 'boolean',\n 'url',\n 'dateTime',\n 'actor',\n 'doc.ref',\n 'doc.refs',\n 'json',\n ]),\n required: v.optional(v.boolean()),\n})\nexport type ActionParam = v.InferOutput<typeof ActionParamSchema>\n\nexport const ActionSchema = v.strictObject({\n type: v.optional(v.literal('workflow.action')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n filter: v.optional(FilterSchema),\n /** Caller-supplied params, validated before ops/effects run. */\n params: v.optional(v.array(ActionParamSchema)),\n /**\n * Status the task flips to when this action fires. Omit to leave\n * the task status unchanged — used by intermediate `claim` /\n * `assign` / partial-update actions where the task should stay\n * active so a later action can fire on it. Declared values must\n * be terminal (`done` / `skipped` / `failed`); the engine never\n * mid-flip back to `active` outside of the `workflow.op.status.set`\n * op explicit path.\n */\n setStatus: v.optional(TerminalTaskStatus),\n /**\n * Inline state-mutation primitives executed during the action commit.\n * Each op runs against the in-memory mutation (deterministic, no\n * external I/O). Resolved Sources turn into concrete JSON before the\n * op applies. Logged on `history[]` as `workflow.history.opApplied`\n * and surfaced on the `ActionResult.ranOps`.\n */\n ops: v.optional(v.array(OpSchema)),\n effects: v.optional(v.array(EffectSchema)),\n /**\n * Role gating — OR-match against `Actor.roles[]`. If omitted, no role\n * gate. `\"*\"` in Actor.roles always matches (bench / all-access).\n */\n roles: v.optional(v.array(NonEmpty)),\n /**\n * When true, the actor must appear in the task's `assignees[]` (as a\n * user-kind assignee matching by id) for the action to be allowed.\n */\n requireAssignment: v.optional(v.boolean()),\n /**\n * Which permission on the workflow.instance document the actor must\n * hold (per supplied `grants`). Defaults to \"update\". Only checked\n * when grants are supplied at evaluate/fireAction time.\n */\n requiredPermission: v.optional(PermissionSchema),\n})\nexport type Action = v.InferOutput<typeof ActionSchema>\n\n// Spawn (nested workflows)\n\nconst CompletionPolicySchema = v.union([\n v.strictObject({kind: v.literal('all')}),\n v.strictObject({kind: v.literal('any')}),\n v.strictObject({\n kind: v.literal('count'),\n n: PositiveInt,\n }),\n])\n\n/**\n * Logical reference to a deployed workflow definition. The engine\n * resolves it at spawn time by querying its own workflow resource for\n * a matching (workflowId, tags ∩ engine.tags, version) tuple, ordering\n * by `version desc` and picking the first — or the matching `version`\n * if explicitly specified.\n *\n * Authors never have a stable GDR URI to reference (tags can be\n * renamed, workflows redeployed). They have the stable contract: the\n * `workflowId`.\n */\nconst LogicalDefinitionRefSchema = v.strictObject({\n workflowId: NonEmpty,\n version: v.optional(v.union([PositiveInt, v.literal('latest')])),\n})\n\n/**\n * `forEach` — spawn fan-out projection.\n *\n * - `groq` runs against the lake (paramsForLake-stripped reserved\n * params: `$self`, `$state`, `$parent`, `$ancestors`, `$stage`,\n * `$now`). Result is an array; engine creates one child per row.\n * - `as.initialState` is a typed projection from each row to the\n * child's initial state slots. Values use the `Source` union with\n * two spawn-only variants:\n * - `{ source: \"row\", path? }` — pull from the current row.\n * - `{ source: \"parentState\", slotId, path? }` — pull from the\n * spawning parent's resolved workflow-scope state.\n * - `as.effectsContext` optionally seeds the child's effectsContext.\n *\n * The spawn does not auto-stamp anything onto the child. Whatever\n * slots the child needs, the author must declare on the child's\n * workflow definition AND project from each row via `as.initialState`.\n */\nconst SpawnForEachSchema = v.strictObject({\n groq: NonEmpty,\n as: v.strictObject({\n initialState: v.optional(\n v.array(\n v.strictObject({\n type: StateSlotKindSchema,\n id: NonEmpty,\n value: SourceSchema,\n }),\n ),\n ),\n effectsContext: v.optional(v.record(v.string(), SourceSchema)),\n }),\n})\n\nconst SpawnSchema = v.strictObject({\n type: v.optional(v.literal('workflow.spawn')),\n id: v.optional(v.string()),\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n definitionRef: LogicalDefinitionRefSchema,\n forEach: SpawnForEachSchema,\n completionPolicy: v.optional(CompletionPolicySchema),\n})\nexport type Spawn = v.InferOutput<typeof SpawnSchema>\n\n// Assignees — typed. `kind: \"user\"` matches `Actor.id`; `kind: \"role\"`\n// matches if `Actor.roles[]` contains the role string.\n\nexport const AssigneeSchema = v.variant('kind', [\n v.strictObject({kind: v.literal('user'), id: NonEmpty}),\n v.strictObject({kind: v.literal('role'), role: NonEmpty}),\n])\nexport type Assignee = v.InferOutput<typeof AssigneeSchema>\n\n// Tasks\n\nexport const TaskSchema = v.strictObject({\n type: v.optional(v.literal('workflow.task')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n assignees: v.optional(v.array(AssigneeSchema)),\n filter: v.optional(FilterSchema),\n invokeOn: v.optional(picklist(['stageEnter', 'manual'])),\n /**\n * Auto-completion predicate — same shape as `transition.filter`. When\n * truthy at activation or on any subsequent cascade, the engine\n * flips the task to `done` with a `{ kind: \"system\", id: \"engine.completeWhen\" }`\n * actor. A full filter, not just a wall-clock deadline.\n */\n completeWhen: v.optional(FilterSchema),\n /**\n * Auto-failure predicate — symmetric to `completeWhen`. Same shape,\n * same evaluation cadence (activation + every cascade), but flips\n * the task to `failed` (not `done`) with a `{ kind: \"system\",\n * id: \"engine.failWhen\" }` actor. When both `completeWhen` and\n * `failWhen` resolve truthy on the same evaluation, `failWhen`\n * wins — failure is the more notable signal and should not be\n * silently swallowed.\n */\n failWhen: v.optional(FilterSchema),\n effects: v.optional(v.array(EffectSchema)),\n actions: v.optional(v.array(ActionSchema)),\n spawns: v.optional(SpawnSchema),\n contentRefs: v.optional(v.array(v.unknown())),\n /** Task-scoped state slots. Resolved at task activation time. */\n state: v.optional(v.array(StateSlotSchema)),\n})\nexport type Task = v.InferOutput<typeof TaskSchema>\n\n// Transitions\n\nexport const TransitionSchema = v.strictObject({\n type: v.optional(v.literal('workflow.transition')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n to: NonEmpty,\n on: v.optional(v.string()),\n filter: v.optional(FilterSchema),\n effects: v.optional(v.array(EffectSchema)),\n})\nexport type Transition = v.InferOutput<typeof TransitionSchema>\n\n// Guards — lake mutation guards (Content Lake). DISTINCT from `Filter`\n// above: a `Filter` is the engine's in-memory soft predicate that gates\n// transitions/tasks/actions; a `Guard` compiles to a `temp.system.guard`\n// document the lake evaluates at mutation time and that fails closed.\n//\n// The authoring shape is match + predicate + metadata. Targets in\n// `match.idRefs` are `Source`s resolved at deploy — `{source:\"self\"}`\n// targets the workflow instance; a `stateRead` of a doc-ref slot targets that\n// doc. The engine resolves each Source to a GDR, then splits it into the guard's\n// resource (resourceType/resourceId — the engine's outer-layer encapsulation;\n// the content lake is per-datasource) plus a BARE id. A GDR never appears in\n// `predicate`. All idRefs of one guard must resolve to the same resource (a\n// guard is single-resource).\n\nconst GuardActionSchema = picklist(MUTATION_GUARD_ACTIONS)\nexport type GuardAction = v.InferOutput<typeof GuardActionSchema>\n\nconst GuardMatchSchema = v.strictObject({\n /** Subject `_type`(s); empty matches any type. */\n types: v.optional(v.array(NonEmpty)),\n /** Target docs as `Source`s resolved at deploy to bare ids + the resource. */\n idRefs: v.optional(v.array(SourceSchema)),\n /** Glob id patterns (bare, resource-local). */\n idPatterns: v.optional(v.array(NonEmpty)),\n actions: v.pipe(\n v.array(GuardActionSchema),\n v.minLength(1, 'a guard must match at least one action'),\n ),\n})\nexport type GuardMatch = v.InferOutput<typeof GuardMatchSchema>\n\nconst GuardSchema = v.strictObject({\n name: v.optional(v.string()),\n description: v.optional(v.string()),\n match: GuardMatchSchema,\n /**\n * Lake GROQ predicate. Reads `document.before`/`document.after`, `mutation`,\n * `guard`, and `identity()`. Bare ids/fields only — no GDRs. Omitted or\n * empty means UNCONDITIONAL DENY.\n */\n predicate: v.optional(v.string()),\n /**\n * Projected workflow state the predicate reads as `guard.metadata.*`. Values\n * are `Source`s resolved at deploy and re-synced by the engine. Copied data,\n * never a cross-resource pointer.\n */\n metadata: v.optional(v.record(NonEmpty, SourceSchema)),\n})\nexport type Guard = v.InferOutput<typeof GuardSchema>\n\n// Stages\n\nconst StageKindSchema = picklist(['initial', 'intermediate', 'terminal', 'waiting'])\nexport type StageKind = v.InferOutput<typeof StageKindSchema>\n\nexport const StageSchema = v.strictObject({\n type: v.optional(v.literal('workflow.stage')),\n id: NonEmpty,\n title: v.optional(v.string()),\n description: v.optional(v.string()),\n kind: v.optional(StageKindSchema),\n tasks: v.optional(v.array(TaskSchema)),\n transitions: v.optional(v.array(TransitionSchema)),\n completion: v.optional(FilterSchema),\n onEnter: v.optional(v.array(EffectSchema)),\n onExit: v.optional(v.array(EffectSchema)),\n /**\n * Lake mutation guards active while this stage holds. Each compiles to a\n * `temp.system.guard` doc deployed on stage entry and retracted on exit.\n * Plural because one stage's intent may span resources (one guard each).\n */\n guards: v.optional(v.array(GuardSchema)),\n contentRefs: v.optional(v.array(v.unknown())),\n /** Stage-scoped state slots. Resolved at stage entry and persisted on\n * the StageEntry. */\n state: v.optional(v.array(StateSlotSchema)),\n})\nexport type Stage = v.InferOutput<typeof StageSchema>\n\n// Workflow definition (the root)\n\n/**\n * Structural schema for a workflow definition. Cross-field invariants\n * (unique ids, transition/predicate references, terminal-stage rules)\n * are checked separately by `checkWorkflowInvariants` after this parse\n * succeeds — see `defineWorkflow`.\n */\nexport const WorkflowDefinitionSchema = v.strictObject({\n workflowId: NonEmpty,\n version: PositiveInt,\n title: NonEmpty,\n description: v.optional(v.string()),\n initialStageId: NonEmpty,\n /**\n * Workflow-level state slots. Persist for the instance lifetime.\n * Every stage's filters/ops can read them via\n * `*[_id == $self][0].state[key == \"<key>\"][0].value`. Init-sourced\n * slots are supplied at `startInstance` via `initialState`.\n */\n state: v.optional(v.array(StateSlotSchema)),\n stages: v.pipe(v.array(StageSchema), v.minLength(1, 'must declare at least one stage')),\n predicates: v.optional(v.array(PredicateSchema)),\n})\n\n/**\n * Workflow definition — inferred from the schema so authoring types\n * and runtime validation share one source of truth.\n */\nexport type WorkflowDefinition = v.InferOutput<typeof WorkflowDefinitionSchema>\n\n// Error formatting — turn validation issues into a multi-line,\n// path-prefixed message that points at the exact field the author got\n// wrong. Shared by structural parse errors (via {@link issuesFromValibot})\n// and cross-field invariant issues.\n\nexport interface ValidationIssue {\n path: ReadonlyArray<PropertyKey>\n message: string\n}\n\nexport function formatValidationError(label: string, issues: readonly ValidationIssue[]): string {\n const lines = issues.map((issue) => {\n const path = issue.path.length === 0 ? '(root)' : formatPath(issue.path)\n return ` - ${path}: ${issue.message}`\n })\n return `${label} failed validation (${issues.length} issue${\n issues.length === 1 ? '' : 's'\n }):\\n${lines.join('\\n')}`\n}\n\nexport function issuesFromValibot(issues: readonly v.BaseIssue<unknown>[]): ValidationIssue[] {\n return issues.map((issue) => ({\n path: issue.path ? issue.path.map((item) => item.key as PropertyKey) : [],\n message: issue.message,\n }))\n}\n\nfunction formatPath(path: ReadonlyArray<PropertyKey>): string {\n let out = ''\n for (const seg of path) {\n if (typeof seg === 'number') out += `[${seg}]`\n else out += out.length === 0 ? String(seg) : `.${String(seg)}`\n }\n return out\n}\n","/**\n * Authoring helpers — schema-first.\n *\n * The schemas in `./schema.ts` are the canonical source of truth for\n * what a workflow author may write. The `define*` helpers here are\n * thin pass-throughs: each one validates its argument against the\n * corresponding schema and returns the result. Errors come back with\n * path-prefixed messages so a typo in `stages[2].tasks[0].actions[1].filter.ref`\n * lands with that exact location.\n *\n * **Why a `define*` per authoring kind.** Long-term, workflows are\n * composed from smaller building blocks — stages, tasks, actions,\n * transitions, predicates, filters, assignees. Each kind is its own\n * authored unit. `defineWorkflow` is just the top-level composer. The\n * companion helpers exist so:\n *\n * 1. Developers can author and unit-test individual building blocks\n * in isolation (a \"draft stage\", a \"two-reviewer approval task\")\n * using the same validation the engine applies at deploy.\n * 2. When 0.2 adds reusable building-block document types, the same\n * helpers transparently grow the ability to deploy each kind as\n * its own document — call sites don't change.\n *\n * Engine-produced shapes (`WorkflowInstance`, `TaskStatusEntry`, etc.)\n * remain plain TS interfaces in `../types.ts`.\n */\n\nimport * as v from 'valibot'\n\nimport {checkWorkflowInvariants} from './invariants.ts'\nimport {\n ActionSchema,\n AssigneeSchema,\n EffectSchema,\n FilterSchema,\n PredicateSchema,\n StageSchema,\n TaskSchema,\n TransitionSchema,\n WorkflowDefinitionSchema,\n formatValidationError,\n issuesFromValibot,\n type Action,\n type Assignee,\n type Effect,\n type Filter,\n type Predicate,\n type Stage,\n type Task,\n type Transition,\n type WorkflowDefinition,\n} from './schema.ts'\n\n// `defineWorkflow` — the top-level composer\n\n/**\n * Validate and return a workflow definition. Throws with a formatted,\n * path-prefixed error message if validation fails.\n *\n * Example error:\n *\n * ```\n * defineWorkflow(\"article-review\") failed validation (2 issues):\n * - stages[1].transitions[0].to: transition target \"ready\" is not a declared stage. Known stages: \"drafting\", \"review\", \"approved\"\n * - stages[0].tasks[0].actions[0].filter.ref: Filter references predicate \"allTaskDone\" which is not declared. Known predicates: \"allTasksDone\"\n * ```\n */\nexport function defineWorkflow(definition: WorkflowDefinition): WorkflowDefinition {\n const workflowId = (definition as {workflowId?: unknown}).workflowId\n const label =\n typeof workflowId === 'string' ? `defineWorkflow(\"${workflowId}\")` : 'defineWorkflow'\n // Structural parse first; cross-field invariants only run on a\n // structurally-valid definition (their checks assume the shape holds).\n const parsed = parseOrThrow(WorkflowDefinitionSchema, definition, label)\n const issues = checkWorkflowInvariants(parsed)\n if (issues.length > 0) throw new Error(formatValidationError(label, issues))\n return parsed\n}\n\n// Companion `define*` helpers — one per authoring kind\n\n/**\n * Validate and return a workflow stage. Useful for authoring a stage\n * in isolation (reusable across workflows, unit-testable on its own)\n * and then composing it inside a `defineWorkflow` call.\n */\nexport function defineStage(stage: Stage): Stage {\n return parseOrThrow(StageSchema, stage, labelFor('defineStage', stage, 'id'))\n}\n\n/**\n * Validate and return a workflow task. Task ids only need to be unique\n * within a stage, so the same task definition can appear in multiple\n * stages of the same workflow.\n */\nexport function defineTask(task: Task): Task {\n return parseOrThrow(TaskSchema, task, labelFor('defineTask', task, 'id'))\n}\n\n/**\n * Validate and return a workflow action. Actions are typically defined\n * inline inside a task; this helper exists for unit testing a single\n * action's shape (especially when it carries gates and effects).\n */\nexport function defineAction(action: Action): Action {\n return parseOrThrow(ActionSchema, action, labelFor('defineAction', action, 'id'))\n}\n\n/**\n * Validate and return a stage transition. Useful when a transition's\n * filter or effects warrant their own test fixture.\n */\nexport function defineTransition(transition: Transition): Transition {\n return parseOrThrow(\n TransitionSchema,\n transition,\n typeof (transition as {id?: unknown}).id === 'string'\n ? `defineTransition(\"${(transition as {id: string}).id}\")`\n : typeof (transition as {to?: unknown}).to === 'string'\n ? `defineTransition(→ \"${(transition as {to: string}).to}\")`\n : 'defineTransition',\n )\n}\n\n/**\n * Validate and return a filter. Filters are GROQ strings or references\n * to named predicates; this helper accepts both forms.\n */\nexport function defineFilter(filter: Filter): Filter {\n return parseOrThrow(FilterSchema, filter, 'defineFilter')\n}\n\n/**\n * Validate and return an assignee. Either a user (`kind: \"user\"` + id)\n * or a role (`kind: \"role\"` + role).\n */\nexport function defineAssignee(assignee: Assignee): Assignee {\n return parseOrThrow(AssigneeSchema, assignee, 'defineAssignee')\n}\n\n/**\n * Validate and return a predicate. Predicates are the named-library\n * counterpart to inline GROQ filters.\n */\nexport function definePredicate(predicate: Predicate): Predicate {\n return parseOrThrow(PredicateSchema, predicate, labelFor('definePredicate', predicate, 'id'))\n}\n\n/**\n * Validate and return an effect declaration — the inline shape that\n * appears on stages / tasks / actions in a workflow definition. Not\n * to be confused with `defineEffectDescriptor` (below), which is for\n * registering a runtime handler.\n */\nexport function defineEffect(effect: Effect): Effect {\n return parseOrThrow(EffectSchema, effect, labelFor('defineEffect', effect, 'id'))\n}\n\n// Effect handler descriptor (runtime side)\n\n/**\n * Effect handler descriptor, registered by the runtime. The schema only\n * stores the `name` reference (an inline `Effect`); the description and\n * param shape live in the registry, which the SDK snapshots into\n * `pendingEffects[]` at queue time.\n *\n * For now this is metadata-only — actual handler invocation is the\n * runtime's job, not this engine's.\n */\nexport interface EffectDescriptor {\n name: string\n description?: string\n params?: EffectDescriptorParam[]\n}\n\nexport interface EffectDescriptorParam {\n name: string\n type: 'string' | 'number' | 'boolean' | 'object' | 'string[]'\n required?: boolean\n description?: string\n}\n\nexport function defineEffectDescriptor(descriptor: EffectDescriptor): EffectDescriptor {\n if (!descriptor.name) throw new Error('EffectDescriptor missing name')\n return descriptor\n}\n\n// Internal — shared parse + label\n\nfunction parseOrThrow<T>(schema: v.GenericSchema<unknown, T>, input: T, label: string): T {\n const result = v.safeParse(schema, input)\n if (!result.success) {\n throw new Error(formatValidationError(label, issuesFromValibot(result.issues)))\n }\n return result.output\n}\n\nfunction labelFor(fn: string, value: unknown, key: string): string {\n if (value && typeof value === 'object' && key in value) {\n const raw = (value as Record<string, unknown>)[key]\n if (typeof raw === 'string') return `${fn}(\"${raw}\")`\n }\n return fn\n}\n"],"names":["v"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BA,SAAS,UAAU,KAA+B;AAChD,SAAO,CAAC,GAAG,GAAG,E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