@sanity/workflow-engine 0.2.0 → 0.4.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.
- package/dist/_chunks-cjs/schema.cjs +405 -0
- package/dist/_chunks-cjs/schema.cjs.map +1 -0
- package/dist/_chunks-es/schema.js +390 -0
- package/dist/_chunks-es/schema.js.map +1 -0
- package/dist/define.cjs +483 -477
- package/dist/define.cjs.map +1 -1
- package/dist/define.d.cts +7404 -4450
- package/dist/define.d.ts +7404 -4450
- package/dist/define.js +480 -473
- package/dist/define.js.map +1 -1
- package/dist/index.cjs +1911 -1619
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11783 -6206
- package/dist/index.d.ts +11783 -6206
- package/dist/index.js +1908 -1615
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/define.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.js","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":[],"mappings":";AA0BA,SAAS,UAAU,KAA+B;AAChD,SAAO,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,EAAE,KAAK,IAAI;AAChD;AAOA,SAAS,oBAAoB,KAAqB,QAAwC;AACxF,QAAM,+BAAe,IAAA;AACrB,aAAW,CAAC,GAAG,KAAK,KAAK,IAAI,OAAO,QAAA;AAC9B,aAAS,IAAI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AAQ,SAAS,gBAAgB,QAAQ,IAAI,CAAC;AAClF;AAMO,SAAS,iBAAiB,YAAoC;AACnE,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAQ,WAA8B,MAAO,WACzC,qBAAsB,WAA4B,EAAE,OACpD,OAAQ,WAA8B,MAAO,WAC3C,4BAAwB,WAA4B,EAAE,OACtD;AAAA,EAAA;AAEV;AAMO,SAAS,aAAa,QAAwB;AACnD,SAAO,aAAa,cAAc,QAAQ,cAAc;AAC1D;AAMO,SAAS,eAAe,UAA8B;AAC3D,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,QAAqC,OAAU,OAAkB;AACxF,QAAM,SAAS,EAAE,UAAU,QAAQ,KAAK;AACxC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,sBAAsB,OAAO,kBAAkB,OAAO,MAAM,CAAC,CAAC;AAEhF,SAAO,OAAO;AAChB;AAEA,SAAS,SAAS,IAAY,OAAgB,KAAqB;AACjE,MAAI,SAAS,OAAO,SAAU,YAAY,OAAO,OAAO;AACtD,UAAM,MAAO,MAAkC,GAAG;AAClD,QAAI,OAAO,OAAQ,iBAAiB,GAAG,EAAE,KAAK,GAAG;AAAA,EACnD;AACA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"define.js","sources":["../src/define/groq.ts","../src/define/desugar.ts","../src/define/invariants.ts","../src/define/index.ts"],"sourcesContent":["/**\n * Hygienic GROQ interpolation for define-time condition building.\n *\n * Parameterized predicate reuse lives in the host language — a TypeScript\n * function producing a condition string — and this tag is its safe splice:\n * interpolated *values* serialize as GROQ literals (JSON literal syntax is\n * valid GROQ), never as raw query text, so quoting and precedence cannot\n * break. The produced string is stored as a plain condition and validated at\n * deploy like any other.\n *\n * ```ts\n * const regulated = (kinds: string[]) => groq`$state.subject.category in ${kinds}`\n * defineTask({ name: \"legal\", filter: regulated([\"finance\", \"health\"]), … })\n * ```\n */\nexport function groq(strings: TemplateStringsArray, ...values: unknown[]): string {\n return strings.reduce((out, part, i) => {\n if (i === 0) return part\n return `${out}${serializeGroqValue(values[i - 1])}${part}`\n }, '')\n}\n\nfunction serializeGroqValue(value: unknown): string {\n const serialized = JSON.stringify(value)\n if (serialized === undefined) {\n throw new Error(\n `groq tag cannot serialize ${typeof value} — interpolate JSON-representable values only`,\n )\n }\n return serialized\n}\n","/**\n * Define-time expansion: authoring input (primitives + sugar) → the stored\n * definition (primitives only). Storage never sees a sugar type.\n *\n * Every expansion is strictly **in-bounds** — confined to the node that\n * declares it. A pattern that spans nodes (the `claim` state/action pair) is\n * tied by an ordinary deploy-checked *reference*, never by creation: sugar\n * never adds a state entry, an action, or anything else outside its node, so\n * the authored arrays remain the complete inventory of the definition.\n *\n * Reference scopes resolve **lexically** here — most-local outward\n * (task → stage → workflow), like variable lookup — so every stored op\n * TARGET carries an explicit `scope` the runtime never re-resolves.\n * `Source.stateRead` VALUES are different: their `scope` stays optional in\n * the stored form, and an omitted scope resolves lexically at read time.\n */\n\nimport {groq} from './groq.ts'\nimport type {\n Action,\n AuthoringAction,\n AuthoringOp,\n AuthoringStateEntry,\n AuthoringStateRef,\n AuthoringTask,\n AuthoringTransition,\n AuthoringWorkflow,\n IssuePath,\n Op,\n Source,\n StateEntry,\n StoredStateRef,\n Task,\n Transition,\n TransitionOp,\n ValidationIssue,\n WorkflowDefinition,\n} from './schema.ts'\n\n/** One lexical layer: the state entries declared at a scope, by name. */\ntype ScopeLayer = ReadonlyMap<string, StateEntry>\n\n/**\n * The lexical environment a reference resolves in: innermost first. A task's\n * ops see task → stage → workflow; a transition's ops see stage → workflow\n * (the stage's tasks are tearing down when a transition fires).\n */\ninterface LexicalEnv {\n layers: readonly {scope: 'workflow' | 'stage' | 'task'; entries: ScopeLayer}[]\n}\n\ninterface DesugarResult {\n definition: WorkflowDefinition\n issues: ValidationIssue[]\n}\n\ninterface Ctx {\n issues: ValidationIssue[]\n /**\n * Entries declared via the `claim` sugar type, keyed by the desugared\n * entry object (the same object the lexical layers hand back), so pairing\n * is exact per declaration — never by bare name across scopes.\n */\n claimStates: Map<StateEntry, {name: string; path: IssuePath}>\n /** Claim-state entries that at least one `claim` action resolved to — pair validation. */\n claimedStates: Set<StateEntry>\n}\n\nexport function desugarWorkflow(authoring: AuthoringWorkflow): DesugarResult {\n const ctx: Ctx = {issues: [], claimStates: new Map(), claimedStates: new Set()}\n\n const workflowState = desugarStateEntries(authoring.state, ['state'], ctx)\n const workflowLayer = layerOf(workflowState)\n\n const stages = authoring.stages.map((stage, i) => {\n const path: IssuePath = ['stages', i]\n const stageState = desugarStateEntries(stage.state, [...path, 'state'], ctx)\n const stageEnv: LexicalEnv = {\n layers: [\n {scope: 'stage', entries: layerOf(stageState)},\n {scope: 'workflow', entries: workflowLayer},\n ],\n }\n const tasks = (stage.tasks ?? []).map((task, j) =>\n desugarTask(task, [...path, 'tasks', j], stageEnv, ctx),\n )\n const transitions = (stage.transitions ?? []).map((transition, k) =>\n desugarTransition(transition, [...path, 'transitions', k], stageEnv, ctx),\n )\n return {\n ...stripUndefined({\n name: stage.name,\n title: stage.title,\n description: stage.description,\n guards: stage.guards,\n }),\n ...(stageState ? {state: stageState} : {}),\n ...(tasks.length > 0 ? {tasks} : {}),\n ...(transitions.length > 0 ? {transitions} : {}),\n }\n })\n\n checkUnclaimedClaimStates(ctx)\n\n const definition = {\n ...stripUndefined({\n name: authoring.name,\n version: authoring.version,\n title: authoring.title,\n description: authoring.description,\n initialStage: authoring.initialStage,\n predicates: authoring.predicates,\n }),\n ...(workflowState ? {state: workflowState} : {}),\n stages,\n } as WorkflowDefinition\n\n return {definition, issues: ctx.issues}\n}\n\n// State entries — the `claim` sugar expands to value.actor with an implied\n// `write` source, strictly within the entry.\n\nfunction desugarStateEntries(\n entries: readonly AuthoringStateEntry[] | undefined,\n path: IssuePath,\n ctx: Ctx,\n): StateEntry[] | undefined {\n if (!entries || entries.length === 0) return entries === undefined ? undefined : []\n return entries.map((entry, i) => {\n if (entry.type !== 'claim') return entry\n const desugared = {\n ...stripUndefined({name: entry.name, title: entry.title, description: entry.description}),\n type: 'value.actor',\n source: {type: 'write'},\n } as StateEntry\n ctx.claimStates.set(desugared, {name: entry.name, path: [...path, i]})\n return desugared\n })\n}\n\nfunction layerOf(entries: readonly StateEntry[] | undefined): ScopeLayer {\n return new Map((entries ?? []).map((entry) => [entry.name, entry]))\n}\n\n// Tasks — activation defaults to `manual` (a task never activates silently;\n// \"auto\" is the explicit opt-in), ops resolve in the task's lexical env, and\n// each action expands within itself.\n\nfunction desugarTask(task: AuthoringTask, path: IssuePath, stageEnv: LexicalEnv, ctx: Ctx): Task {\n const taskState = desugarStateEntries(task.state, [...path, 'state'], ctx)\n const env: LexicalEnv = {\n layers: [{scope: 'task', entries: layerOf(taskState)}, ...stageEnv.layers],\n }\n const ops = desugarOps(task.ops, [...path, 'ops'], env, task.name, ctx)\n const actions = (task.actions ?? []).map((action, a) =>\n desugarAction(action, [...path, 'actions', a], env, task.name, ctx),\n )\n return {\n ...stripUndefined({\n name: task.name,\n title: task.title,\n description: task.description,\n filter: task.filter,\n completeWhen: task.completeWhen,\n failWhen: task.failWhen,\n effects: task.effects,\n subworkflows: task.subworkflows,\n }),\n activation: task.activation ?? 'manual',\n ...(taskState ? {state: taskState} : {}),\n ...(ops ? {ops} : {}),\n ...(actions.length > 0 ? {actions} : {}),\n } as Task\n}\n\n// Actions — the `claim` sugar type and the `roles` / `status` field sugars.\n\nfunction desugarAction(\n action: AuthoringAction,\n path: IssuePath,\n env: LexicalEnv,\n taskName: string,\n ctx: Ctx,\n): Action {\n // Only the claim sugar variant carries a `type` — raw actions have none.\n if ('type' in action) {\n return desugarClaimAction(action, path, env, ctx)\n }\n\n const filter = composeFilter([rolesCondition(action.roles), action.filter])\n const ops = desugarOps(action.ops, [...path, 'ops'], env, taskName, ctx) ?? []\n if (action.status !== undefined) {\n // Appended AFTER the authored ops — the expansion has a defined position.\n ops.push({type: 'status.set', task: taskName, status: action.status})\n }\n return {\n ...stripUndefined({\n name: action.name,\n title: action.title,\n description: action.description,\n params: action.params,\n effects: action.effects,\n }),\n ...(filter ? {filter} : {}),\n ...(ops.length > 0 ? {ops} : {}),\n } as Action\n}\n\nfunction desugarClaimAction(\n action: Extract<AuthoringAction, {type: 'claim'}>,\n path: IssuePath,\n env: LexicalEnv,\n ctx: Ctx,\n): Action {\n const ref = typeof action.state === 'string' ? {state: action.state} : action.state\n const resolved = resolveRef(ref, env, [...path, 'state'], ctx)\n if (resolved) {\n const entry = entryAt(env, resolved)\n if (entry && entry.type !== 'value.actor') {\n ctx.issues.push({\n path: [...path, 'state'],\n message:\n `claim action \"${action.name}\" references \"${resolved.state}\" of kind ` +\n `\"${entry.type}\" — a claim pair needs an actor-valued entry ` +\n `(a \"claim\" or \"value.actor\" state declaration)`,\n })\n }\n checkShadowedClaimTarget(action.name, ref.state, resolved, env, [...path, 'state'], ctx)\n if (entry) ctx.claimedStates.add(entry)\n }\n\n const noSteal = `!defined($state.${ref.state})`\n const filter = composeFilter([noSteal, rolesCondition(action.roles), action.filter])\n const ops: Op[] = resolved ? [{type: 'state.set', target: resolved, value: {type: 'actor'}}] : []\n return {\n ...stripUndefined({\n name: action.name,\n title: action.title,\n description: action.description,\n params: action.params,\n effects: action.effects,\n }),\n filter,\n ...(ops.length > 0 ? {ops} : {}),\n } as Action\n}\n\n/**\n * The claim action's two halves must address ONE entry: the no-steal filter\n * reads `$state.<name>` (nearest declaring scope wins in the rendered\n * overlay), while the `state.set` op writes the resolved ref. An explicit\n * `scope:` that lands on an entry lexically shadowed at the action's\n * position would split them — the filter checks the shadowing entry, the\n * op claims the shadowed one — so that is a define-time error.\n */\nfunction checkShadowedClaimTarget(\n actionName: string,\n state: string,\n resolved: StoredStateRef,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): void {\n const nearest = env.layers.find((l) => l.entries.has(state))\n if (nearest === undefined || nearest.scope === resolved.scope) return\n ctx.issues.push({\n path,\n message:\n `claim action \"${actionName}\" targets \"${state}\" at scope \"${resolved.scope}\", but a ` +\n `nearer ${nearest.scope}-scope entry of the same name shadows it in $state — the ` +\n `no-steal filter would read the shadowing entry while the claim writes the ` +\n `\"${resolved.scope}\" one. Rename one of the entries or claim the nearer one`,\n })\n}\n\n/** Pair validation, the other direction: a `claim` state nothing claims into. */\nfunction checkUnclaimedClaimStates(ctx: Ctx): void {\n for (const [entry, {name, path}] of ctx.claimStates) {\n if (ctx.claimedStates.has(entry)) continue\n ctx.issues.push({\n path,\n message:\n `claim state \"${name}\" is never referenced by a claim action — ` +\n `you announced the pattern and wrote half of it. Declare a ` +\n `defineAction({ type: \"claim\", state: \"${name}\" }) or use a raw value.actor entry`,\n })\n }\n}\n\n// Transitions — an omitted filter desugars to the safe, dominant gate.\n// The lexical env for transition ops skips the task layer: the stage's tasks\n// are tearing down when a transition fires.\n\nfunction desugarTransition(\n transition: AuthoringTransition,\n path: IssuePath,\n stageEnv: LexicalEnv,\n ctx: Ctx,\n): Transition {\n const ops = desugarOps(transition.ops, [...path, 'ops'], stageEnv, undefined, ctx)\n return {\n ...stripUndefined({\n name: transition.name,\n title: transition.title,\n description: transition.description,\n to: transition.to,\n effects: transition.effects,\n }),\n filter: transition.filter ?? '$allTasksDone',\n ...(ops ? {ops: ops as TransitionOp[]} : {}),\n } as Transition\n}\n\n// Ops — the `audit` sugar (a stamped append, in-bounds: it only touches its\n// own value) plus lexical target resolution and the firing-task default on\n// `status.set`.\n\nfunction desugarOps(\n ops: readonly AuthoringOp[] | undefined,\n path: IssuePath,\n env: LexicalEnv,\n firingTask: string | undefined,\n ctx: Ctx,\n): Op[] | undefined {\n if (!ops) return undefined\n return ops.map((op, i) => desugarOp(op, [...path, i], env, firingTask, ctx))\n}\n\nfunction desugarOp(\n op: AuthoringOp,\n path: IssuePath,\n env: LexicalEnv,\n firingTask: string | undefined,\n ctx: Ctx,\n): Op {\n if (op.type === 'status.set') {\n const task = op.task ?? firingTask\n if (task === undefined) {\n ctx.issues.push({\n path: [...path, 'task'],\n message: 'status.set outside an action must name its target task',\n })\n }\n return {type: 'status.set', task: task ?? '', status: op.status}\n }\n if (op.type === 'audit') return desugarAuditOp(op, path, env, ctx)\n const target = resolveRef(op.target, env, [...path, 'target'], ctx) ?? fallbackRef(op.target)\n return {...op, target} as Op\n}\n\nconst AUDIT_STAMPS = {actor: {type: 'actor'}, at: {type: 'now'}} as const\n\nfunction desugarAuditOp(\n op: Extract<AuthoringOp, {type: 'audit'}>,\n path: IssuePath,\n env: LexicalEnv,\n ctx: Ctx,\n): Op {\n const target = resolveRef(op.target, env, [...path, 'target'], ctx) ?? fallbackRef(op.target)\n if (op.value.type !== 'object') {\n ctx.issues.push({\n path: [...path, 'value'],\n message: `audit value must be an object source carrying the domain fields (got \"${op.value.type}\")`,\n })\n return {type: 'state.append', target, value: op.value}\n }\n const actorField = op.stampFields?.actor ?? 'actor'\n const atField = op.stampFields?.at ?? 'at'\n const fields: Record<string, Source> = {...op.value.fields}\n for (const [stamp, source] of [\n [actorField, AUDIT_STAMPS.actor],\n [atField, AUDIT_STAMPS.at],\n ] as const) {\n if (stamp in fields) {\n ctx.issues.push({\n path: [...path, 'value', 'fields', stamp],\n message:\n `audit stamp field \"${stamp}\" collides with an authored domain field — ` +\n `rename yours or remap the stamp via stampFields`,\n })\n continue\n }\n fields[stamp] = source\n }\n return {type: 'state.append', target, value: {type: 'object', fields}}\n}\n\n// Lexical reference resolution — most-local outward, like variable lookup.\n// An explicit `scope` overrides; an unresolvable reference fails loud.\n\nfunction resolveRef(\n ref: AuthoringStateRef,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): StoredStateRef | undefined {\n const layers =\n ref.scope === undefined ? env.layers : env.layers.filter((l) => l.scope === ref.scope)\n for (const layer of layers) {\n if (layer.entries.has(ref.state)) return {scope: layer.scope, state: ref.state}\n }\n const reachable = env.layers.flatMap((l) => [...l.entries.keys()].map((n) => `${l.scope}:${n}`))\n ctx.issues.push({\n path,\n message:\n `state reference \"${ref.state}\"${ref.scope ? ` (scope \"${ref.scope}\")` : ''} does not ` +\n `resolve to a declared entry. Reachable: ${reachable.join(', ') || '(none)'}`,\n })\n return undefined\n}\n\nfunction entryAt(env: LexicalEnv, ref: StoredStateRef): StateEntry | undefined {\n return env.layers.find((l) => l.scope === ref.scope)?.entries.get(ref.state)\n}\n\n/** Keeps the stored shape parseable after a resolution issue was reported. */\nfunction fallbackRef(ref: AuthoringStateRef): StoredStateRef {\n return {scope: ref.scope ?? 'workflow', state: ref.state}\n}\n\n// Small shared helpers\n\nfunction rolesCondition(roles: readonly string[] | undefined): string | undefined {\n if (!roles || roles.length === 0) return undefined\n return groq`count($actor.roles[@ in ${roles}]) > 0`\n}\n\nfunction composeFilter(parts: (string | undefined)[]): string | undefined {\n const present = parts.filter((p): p is string => p !== undefined)\n if (present.length === 0) return undefined\n if (present.length === 1) return present[0]\n return present.map((p) => `(${p})`).join(' && ')\n}\n\nfunction stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n const out: Record<string, unknown> = {}\n for (const [k, value] of Object.entries(obj)) {\n if (value !== undefined) out[k] = value\n }\n return out as T\n}\n","import type {Effect, IssuePath, Op, Task, ValidationIssue, WorkflowDefinition} from './schema.ts'\nimport {GROQ_IDENTIFIER} from './schema.ts'\n\n/**\n * The rendered-scope variable names the engine binds for conditions. An\n * author predicate redefining one would silently shadow engine behaviour,\n * so it is rejected at deploy — engine-owned and author names share one\n * namespace, fail loud.\n */\nconst RESERVED_CONDITION_VARS = [\n 'state',\n 'actor',\n 'assigned',\n 'can',\n 'row',\n 'now',\n 'effects',\n 'tasks',\n 'subworkflows',\n 'self',\n 'stage',\n 'parent',\n 'ancestors',\n 'allTasksDone',\n 'anyTaskFailed',\n] as const\n\n/**\n * Caller-bound vars a predicate body may not read: predicates pre-evaluate\n * once per instance against the built-in scope (no caller), while the\n * commit-path re-evaluates conditions WITH the caller bound — the same\n * predicate would give divergent verdicts on the two paths.\n */\nconst PREDICATE_CALLER_VARS = ['actor', 'assigned', 'can'] as const\n\nfunction knownList(ids: Iterable<string>): string {\n return [...ids].map((s) => `\"${s}\"`).join(', ')\n}\n\nfunction checkDuplicates(\n names: Iterable<{name: string; path: IssuePath}>,\n what: string,\n issues: ValidationIssue[],\n): Set<string> {\n const seen = new Set<string>()\n for (const {name, path} of names) {\n if (seen.has(name)) {\n issues.push({path, message: `duplicate ${what} \"${name}\" (already declared earlier)`})\n }\n seen.add(name)\n }\n return seen\n}\n\nfunction checkStages(def: WorkflowDefinition, issues: ValidationIssue[]): Set<string> {\n const stageNames = checkDuplicates(\n def.stages.map((stage, i) => ({name: stage.name, path: ['stages', i, 'name']})),\n 'stage name',\n issues,\n )\n for (const [i, stage] of def.stages.entries()) {\n const taskNames = checkDuplicates(\n (stage.tasks ?? []).map((task, j) => ({\n name: task.name,\n path: ['stages', i, 'tasks', j, 'name'],\n })),\n `task name in stage \"${stage.name}\"`,\n issues,\n )\n checkDuplicates(\n (stage.transitions ?? []).map((t, k) => ({\n name: t.name,\n path: ['stages', i, 'transitions', k, 'name'],\n })),\n `transition name in stage \"${stage.name}\"`,\n issues,\n )\n checkTasks(def, i, taskNames, issues)\n }\n return stageNames\n}\n\nfunction checkTasks(\n def: WorkflowDefinition,\n i: number,\n taskNames: Set<string>,\n issues: ValidationIssue[],\n): void {\n const stage = def.stages[i]!\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n const path: IssuePath = ['stages', i, 'tasks', j]\n checkDuplicates(\n (task.actions ?? []).map((action, a) => ({\n name: action.name,\n path: [...path, 'actions', a, 'name'],\n })),\n `action name in task \"${task.name}\"`,\n issues,\n )\n checkStatusSetTargets(task, taskNames, path, issues)\n }\n}\n\n/**\n * A `status.set` may re-activate a SIBLING task — the name must exist in\n * the stage. Both op sites can carry one: action ops and the task's own\n * activation ops. (Transition ops cannot — the schema's transition-op\n * subset excludes `status.set` at parse time.)\n */\nfunction checkStatusSetTargets(\n task: Task,\n taskNames: Set<string>,\n path: IssuePath,\n issues: ValidationIssue[],\n): void {\n checkStatusSetOps(task.ops, taskNames, [...path, 'ops'], issues)\n for (const [a, action] of (task.actions ?? []).entries()) {\n checkStatusSetOps(action.ops, taskNames, [...path, 'actions', a, 'ops'], issues)\n }\n}\n\nfunction checkStatusSetOps(\n ops: readonly Op[] | undefined,\n taskNames: Set<string>,\n path: IssuePath,\n issues: ValidationIssue[],\n): void {\n for (const [o, op] of (ops ?? []).entries()) {\n if (op.type !== 'status.set' || taskNames.has(op.task)) continue\n issues.push({\n path: [...path, o, 'task'],\n message:\n `status.set targets task \"${op.task}\" which is not declared in this stage. ` +\n `Known tasks: ${knownList(taskNames)}`,\n })\n }\n}\n\nfunction checkInitialStage(\n def: WorkflowDefinition,\n stageNames: Set<string>,\n issues: ValidationIssue[],\n): void {\n if (stageNames.has(def.initialStage)) return\n issues.push({\n path: ['initialStage'],\n message:\n `initialStage \"${def.initialStage}\" is not a declared stage. ` +\n `Known stages: ${knownList(stageNames)}`,\n })\n}\n\nfunction checkTransitionTargets(\n def: WorkflowDefinition,\n stageNames: 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 (stageNames.has(t.to)) continue\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(stageNames)}`,\n })\n }\n }\n}\n\n/**\n * Effect names are the registry keys handlers bind to AND the `$effects.<name>`\n * read keys — unique across the whole definition so a read is unambiguous.\n * Reusing one handler function under two names happens in app code.\n */\nfunction checkEffectNames(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n const sites: {name: string; path: IssuePath}[] = []\n for (const [i, stage] of def.stages.entries()) {\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n collectEffects(task.effects, ['stages', i, 'tasks', j, 'effects'], sites)\n for (const [a, action] of (task.actions ?? []).entries()) {\n collectEffects(action.effects, ['stages', i, 'tasks', j, 'actions', a, 'effects'], sites)\n }\n }\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n collectEffects(t.effects, ['stages', i, 'transitions', k, 'effects'], sites)\n }\n }\n checkDuplicates(sites, 'effect name (registry key — unique per definition)', issues)\n}\n\nfunction collectEffects(\n effects: readonly {name: string}[] | undefined,\n path: IssuePath,\n sites: {name: string; path: IssuePath}[],\n): void {\n for (const [e, effect] of (effects ?? []).entries()) {\n sites.push({name: effect.name, path: [...path, e, 'name']})\n }\n}\n\n/**\n * The guard lake `_id` derives from (instanceId, guard.name) — see\n * {@link lakeGuardId}'s callers. A duplicate guard name ANYWHERE in the\n * definition aliases two guards onto one lake document: when a stage move\n * deploys the entered stage's guard and then the exited stage's retract\n * patches the SAME `_id` to an unconditional allow, a hard lock is silently\n * lifted. Unique per definition, not per stage.\n */\nfunction checkGuardNames(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n const sites = def.stages.flatMap((stage, i) =>\n (stage.guards ?? []).map((guard, g): {name: string; path: IssuePath} => ({\n name: guard.name,\n path: ['stages', i, 'guards', g, 'name'],\n })),\n )\n checkDuplicates(\n sites,\n 'guard name (the guard lake _id derives from it — unique per definition)',\n issues,\n )\n}\n\ninterface StateScopeSite {\n entries: readonly {type: string; name: string}[] | undefined\n path: IssuePath\n label: string\n}\n\nfunction stateScopes(def: WorkflowDefinition): StateScopeSite[] {\n const scopes: StateScopeSite[] = [{entries: def.state, path: ['state'], label: 'workflow state'}]\n for (const [i, stage] of def.stages.entries()) {\n scopes.push({\n entries: stage.state,\n path: ['stages', i, 'state'],\n label: `stage \"${stage.name}\" state`,\n })\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n scopes.push({\n entries: task.state,\n path: ['stages', i, 'tasks', j, 'state'],\n label: `task \"${task.name}\" state`,\n })\n }\n }\n return scopes\n}\n\n/**\n * State entry names are the per-scope lookup keys (`$state.<name>`, op\n * targets, runtime `find()` reads) — a duplicate within one scope makes\n * different readers silently land on different entries.\n */\nfunction checkStateEntryNames(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const {entries, path, label} of stateScopes(def)) {\n checkDuplicates(\n (entries ?? []).map((entry, n) => ({name: entry.name, path: [...path, n, 'name']})),\n `state entry name in ${label}`,\n issues,\n )\n }\n}\n\nfunction checkPredicates(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n const reserved = new Set<string>(RESERVED_CONDITION_VARS)\n const names = Object.keys(def.predicates ?? {})\n for (const name of names) {\n if (!reserved.has(name)) continue\n issues.push({\n path: ['predicates', name],\n message: `predicate \"${name}\" shadows the built-in $${name} — pick another name`,\n })\n }\n for (const [name, groq] of Object.entries(def.predicates ?? {})) {\n checkPredicateBody(name, groq, names, issues)\n }\n}\n\nfunction checkPredicateBody(\n name: string,\n groq: string,\n names: string[],\n issues: ValidationIssue[],\n): void {\n for (const caller of PREDICATE_CALLER_VARS) {\n if (!referencesVar(groq, caller)) continue\n issues.push({\n path: ['predicates', name],\n message:\n `predicate \"${name}\" reads $${caller} — predicates are instance-level (pre-evaluated ` +\n `once, without a caller); compose caller gates at the condition site instead`,\n })\n }\n // Predicates pre-evaluate against the built-in scope only, so a body\n // referencing a sibling would need a dependency order — fail loud instead.\n for (const other of names) {\n if (other === name || !referencesVar(groq, other)) continue\n issues.push({\n path: ['predicates', name],\n message:\n `predicate \"${name}\" references predicate $${other} — predicates may read ` +\n `built-in vars only (no cross-references; compose at the condition site instead)`,\n })\n }\n}\n\n/**\n * Whether a condition body reads `$<name>`. Only identifier-safe names can\n * appear as a GROQ var at all (and only they splice into a RegExp without\n * escaping), so anything else is a no-reference by construction.\n */\nfunction referencesVar(groq: string, name: string): boolean {\n if (!GROQ_IDENTIFIER.test(name)) return false\n return new RegExp(`\\\\$${name}\\\\b`).test(groq)\n}\n\ninterface ConditionSite {\n groq: string\n path: IssuePath\n label: string\n}\n\n/**\n * `$can` (the caller's advisory grants) is bound only while an action\n * fires — every other condition site evaluates without it and would hit\n * an unbound-param error mid-cascade at runtime. Reject it everywhere but\n * action filters.\n */\nfunction checkCanOutsideActionFilters(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const site of nonActionFilterConditionSites(def)) {\n if (!referencesVar(site.groq, 'can')) continue\n issues.push({\n path: site.path,\n message:\n `${site.label} reads $can — $can (the caller's grants) is bound only when an ` +\n `action fires, so it may appear in action filters only`,\n })\n }\n}\n\nfunction nonActionFilterConditionSites(def: WorkflowDefinition): ConditionSite[] {\n const sites: ConditionSite[] = []\n for (const [i, stage] of def.stages.entries()) {\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n sites.push({\n groq: t.filter,\n path: ['stages', i, 'transitions', k, 'filter'],\n label: `transition \"${t.name}\" filter`,\n })\n collectBindingSites(\n t.effects,\n ['stages', i, 'transitions', k, 'effects'],\n `transition \"${t.name}\"`,\n sites,\n )\n }\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n collectTaskConditionSites(task, ['stages', i, 'tasks', j], sites)\n }\n }\n return sites\n}\n\nfunction collectTaskConditionSites(task: Task, path: IssuePath, sites: ConditionSite[]): void {\n for (const field of ['filter', 'completeWhen', 'failWhen'] as const) {\n const groq = task[field]\n if (groq !== undefined) {\n sites.push({groq, path: [...path, field], label: `task \"${task.name}\".${field}`})\n }\n }\n collectBindingSites(task.effects, [...path, 'effects'], `task \"${task.name}\"`, sites)\n for (const [a, action] of (task.actions ?? []).entries()) {\n collectBindingSites(\n action.effects,\n [...path, 'actions', a, 'effects'],\n `action \"${action.name}\"`,\n sites,\n )\n }\n collectSubworkflowSites(task, path, sites)\n}\n\nfunction collectSubworkflowSites(task: Task, path: IssuePath, sites: ConditionSite[]): void {\n const sub = task.subworkflows\n if (sub === undefined) return\n const subPath = [...path, 'subworkflows']\n sites.push({\n groq: sub.forEach,\n path: [...subPath, 'forEach'],\n label: `task \"${task.name}\".subworkflows.forEach`,\n })\n for (const [group, record] of [\n ['with', sub.with],\n ['context', sub.context],\n ] as const) {\n for (const [key, groq] of Object.entries(record ?? {})) {\n sites.push({\n groq,\n path: [...subPath, group, key],\n label: `task \"${task.name}\".subworkflows.${group} \"${key}\"`,\n })\n }\n }\n}\n\nfunction collectBindingSites(\n effects: readonly Effect[] | undefined,\n path: IssuePath,\n label: string,\n sites: ConditionSite[],\n): void {\n for (const [e, effect] of (effects ?? []).entries()) {\n for (const [key, groq] of Object.entries(effect.bindings ?? {})) {\n sites.push({\n groq,\n path: [...path, e, 'bindings', key],\n label: `${label} effect \"${effect.name}\" binding \"${key}\"`,\n })\n }\n }\n}\n\n/** The inbox and `$assigned` read the assignees-kind entry — at most one per scope. */\nfunction checkAssigneesEntries(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const {entries, path} of stateScopes(def)) {\n const assignees = (entries ?? []).filter((e) => e.type === 'assignees')\n if (assignees.length <= 1) continue\n issues.push({\n path,\n message: 'at most one assignees-kind state entry per scope — the inbox reads it by kind',\n })\n }\n}\n\n/**\n * Run every cross-field invariant of a (desugared, stored-shape) workflow\n * definition, returning issues whose paths land on the offending field. Kept\n * separate from the structural schema so each invariant is independently\n * named and testable, and runs only after the structural parse succeeds.\n */\nexport function checkWorkflowInvariants(def: WorkflowDefinition): ValidationIssue[] {\n const issues: ValidationIssue[] = []\n const stageNames = checkStages(def, issues)\n checkInitialStage(def, stageNames, issues)\n checkTransitionTargets(def, stageNames, issues)\n checkEffectNames(def, issues)\n checkGuardNames(def, issues)\n checkStateEntryNames(def, issues)\n checkPredicates(def, issues)\n checkCanOutsideActionFilters(def, issues)\n checkAssigneesEntries(def, issues)\n return issues\n}\n","/**\n * Authoring helpers — schema-first.\n *\n * The schemas in `./schema.ts` are the canonical source of truth for what a\n * workflow author may write. Each `define*` helper validates one authoring\n * node (raw primitive or sugar type) so a type error lands on the offending\n * element with autocomplete — the Sanity idiom (`defineConfig` / `defineType`\n * / `defineField`), which is also why identity is `name` everywhere.\n *\n * `defineWorkflow` is the composer and the compile boundary: it parses the\n * authoring tree, **desugars** it (sugar types and field sugars expand\n * in-bounds, lexical scopes resolve, defaults fill — see `./desugar.ts`),\n * then checks cross-field invariants on the resulting STORED definition.\n * What it returns is exactly what deploys: primitives only.\n */\n\nimport * as v from 'valibot'\n\nimport {desugarWorkflow} from './desugar.ts'\nimport {checkWorkflowInvariants} from './invariants.ts'\nimport {\n AuthoringActionSchema,\n AuthoringOpSchema,\n AuthoringStageSchema,\n AuthoringStateEntrySchema,\n AuthoringTaskSchema,\n AuthoringTransitionSchema,\n AuthoringWorkflowSchema,\n EffectSchema,\n GuardSchema,\n formatValidationError,\n issuesFromValibot,\n type AuthoringAction,\n type AuthoringOp,\n type AuthoringStage,\n type AuthoringStateEntry,\n type AuthoringTask,\n type AuthoringTransition,\n type AuthoringWorkflow,\n type Effect,\n type Guard,\n type ValidationIssue,\n type WorkflowDefinition,\n} from './schema.ts'\n\nexport {groq} from './groq.ts'\n\n/**\n * Validate, desugar, and return a workflow definition in its stored shape.\n * Throws with a formatted, 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 * - predicates.allTasksDone: predicate \"allTasksDone\" shadows the built-in $allTasksDone — pick another name\n * ```\n */\nexport function defineWorkflow(definition: AuthoringWorkflow): WorkflowDefinition {\n const label = labelFor('defineWorkflow', definition)\n // Structural parse first; desugar and cross-field invariants only run on a\n // structurally-valid authoring tree (their logic assumes the shape holds).\n const parsed = parseOrThrow(AuthoringWorkflowSchema, definition, label)\n const {definition: stored, issues: desugarIssues} = desugarWorkflow(parsed)\n const issues: ValidationIssue[] = [...desugarIssues, ...checkWorkflowInvariants(stored)]\n if (issues.length > 0) throw new Error(formatValidationError(label, issues))\n return stored\n}\n\n// Companion `define*` helpers — one per authoring node. Each validates the\n// AUTHORING shape (primitives + sugar); expansion happens when the node is\n// composed into `defineWorkflow`.\n\nexport function defineStage(stage: AuthoringStage): AuthoringStage {\n return parseOrThrow(AuthoringStageSchema, stage, labelFor('defineStage', stage))\n}\n\nexport function defineTask(task: AuthoringTask): AuthoringTask {\n return parseOrThrow(AuthoringTaskSchema, task, labelFor('defineTask', task))\n}\n\nexport function defineAction(action: AuthoringAction): AuthoringAction {\n return parseOrThrow(AuthoringActionSchema, action, labelFor('defineAction', action))\n}\n\nexport function defineTransition(transition: AuthoringTransition): AuthoringTransition {\n return parseOrThrow(AuthoringTransitionSchema, transition, transitionLabel(transition))\n}\n\nexport function defineState(entry: AuthoringStateEntry): AuthoringStateEntry {\n return parseOrThrow(AuthoringStateEntrySchema, entry, labelFor('defineState', entry))\n}\n\nexport function defineOp(op: AuthoringOp): AuthoringOp {\n return parseOrThrow(AuthoringOpSchema, op, 'defineOp')\n}\n\nexport function defineGuard(guard: Guard): Guard {\n return parseOrThrow(GuardSchema, guard, labelFor('defineGuard', guard))\n}\n\n/**\n * Validate and return an effect declaration — the registry model: `name` is\n * the effect's only identity; the host app registers a handler against it.\n */\nexport function defineEffect(effect: Effect): Effect {\n return parseOrThrow(EffectSchema, effect, labelFor('defineEffect', effect))\n}\n\nfunction transitionLabel(transition: AuthoringTransition): string {\n const {name, to} = transition as {name?: unknown; to?: unknown}\n if (typeof name === 'string') return `defineTransition(\"${name}\")`\n if (typeof to === 'string') return `defineTransition(→ \"${to}\")`\n return 'defineTransition'\n}\n\n// Effect handler descriptor (runtime side)\n\n/**\n * Effect handler descriptor, registered by the runtime against an effect\n * `name` (1:1 — the stored definition never references code). The description\n * and param shape live in the registry, which the SDK snapshots into\n * `pendingEffects[]` at queue time.\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): string {\n if (value && typeof value === 'object' && 'name' in value) {\n const raw = (value as Record<string, unknown>).name\n if (typeof raw === 'string') return `${fn}(\"${raw}\")`\n }\n return fn\n}\n"],"names":["groq"],"mappings":";;AAeO,SAAS,KAAK,YAAkC,QAA2B;AAChF,SAAO,QAAQ,OAAO,CAAC,KAAK,MAAM,MAC5B,MAAM,IAAU,OACb,GAAG,GAAG,GAAG,mBAAmB,OAAO,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IACvD,EAAE;AACP;AAEA,SAAS,mBAAmB,OAAwB;AAClD,QAAM,aAAa,KAAK,UAAU,KAAK;AACvC,MAAI,eAAe;AACjB,UAAM,IAAI;AAAA,MACR,6BAA6B,OAAO,KAAK;AAAA,IAAA;AAG7C,SAAO;AACT;ACsCO,SAAS,gBAAgB,WAA6C;AAC3E,QAAM,MAAW,EAAC,QAAQ,CAAA,GAAI,aAAa,oBAAI,OAAO,eAAe,oBAAI,IAAA,EAAI,GAEvE,gBAAgB,oBAAoB,UAAU,OAAO,CAAC,OAAO,GAAG,GAAG,GACnE,gBAAgB,QAAQ,aAAa,GAErC,SAAS,UAAU,OAAO,IAAI,CAAC,OAAO,MAAM;AAChD,UAAM,OAAkB,CAAC,UAAU,CAAC,GAC9B,aAAa,oBAAoB,M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