@sanity/workflow-engine 0.10.0 → 0.11.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 +41 -5
- package/dist/_chunks-cjs/schema.cjs.map +1 -1
- package/dist/_chunks-es/schema.js +41 -5
- package/dist/_chunks-es/schema.js.map +1 -1
- package/dist/define.cjs +53 -2
- package/dist/define.cjs.map +1 -1
- package/dist/define.d.cts +380 -2
- package/dist/define.d.ts +380 -2
- package/dist/define.js +53 -2
- package/dist/define.js.map +1 -1
- package/dist/index.cjs +61 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +718 -2
- package/dist/index.d.ts +718 -2
- package/dist/index.js +62 -9
- 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/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`$fields.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` field/action pair) is\n * tied by an ordinary deploy-checked *reference*, never by creation: sugar\n * never adds a field 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.fieldRead` VALUES are different: their `scope` stays optional in\n * the stored form, and an omitted scope resolves lexically at read time.\n */\n\nimport {andConditions} from '../core/conditions.ts'\nimport {expandRequiredRoles} from '../core/roles.ts'\nimport {groq} from './groq.ts'\nimport type {\n Action,\n AuthoringAction,\n AuthoringEditable,\n AuthoringOp,\n AuthoringFieldEntry,\n AuthoringFieldRef,\n AuthoringTask,\n AuthoringTransition,\n AuthoringWorkflow,\n Editable,\n IssuePath,\n Op,\n RoleAliases,\n Source,\n FieldEntry,\n StoredFieldRef,\n Task,\n Transition,\n TransitionOp,\n ValidationIssue,\n WorkflowDefinition,\n} from './schema.ts'\n\n/** One lexical layer: the field entries declared at a scope, by name. */\ntype ScopeLayer = ReadonlyMap<string, FieldEntry>\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 claimFields: Map<FieldEntry, {name: string; path: IssuePath}>\n /** Claim-field entries that at least one `claim` action resolved to — pair validation. */\n claimedFields: Set<FieldEntry>\n /** The definition's `roleAliases`, baked into every `roles` gate it desugars. */\n roleAliases: RoleAliases | undefined\n}\n\nexport function desugarWorkflow(authoring: AuthoringWorkflow): DesugarResult {\n const ctx: Ctx = {\n issues: [],\n claimFields: new Map(),\n claimedFields: new Set(),\n roleAliases: authoring.roleAliases,\n }\n\n const workflowFields = desugarFieldEntries(authoring.fields, ['fields'], ctx)\n const workflowLayer = layerOf(workflowFields)\n\n const stages = authoring.stages.map((stage, i) => {\n const path: IssuePath = ['stages', i]\n const stageFields = desugarFieldEntries(stage.fields, [...path, 'fields'], ctx)\n const stageEnv: LexicalEnv = {\n layers: [\n {scope: 'stage', entries: layerOf(stageFields)},\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 const editable = desugarStageEditable(\n stage.editable,\n editableSlotNames(workflowFields, stageFields, tasks),\n [...path, 'editable'],\n ctx,\n )\n return {\n ...stripUndefined({\n name: stage.name,\n title: stage.title,\n description: stage.description,\n guards: stage.guards,\n }),\n ...(stageFields ? {fields: stageFields} : {}),\n ...(tasks.length > 0 ? {tasks} : {}),\n ...(transitions.length > 0 ? {transitions} : {}),\n ...(editable ? {editable} : {}),\n }\n })\n\n checkUnclaimedClaimFields(ctx)\n\n const definition = {\n ...stripUndefined({\n name: authoring.name,\n version: authoring.version,\n title: authoring.title,\n description: authoring.description,\n role: authoring.role,\n initialStage: authoring.initialStage,\n predicates: authoring.predicates,\n roleAliases: authoring.roleAliases,\n }),\n ...(workflowFields ? {fields: workflowFields} : {}),\n stages,\n } as WorkflowDefinition\n\n return {definition, issues: ctx.issues}\n}\n\n// Field entries — the `claim` sugar expands to value.actor with an implied\n// `write` source, strictly within the entry; the `editable` grammar's\n// `role[]` convenience normalises to a membership predicate.\n\nfunction desugarFieldEntries(\n entries: readonly AuthoringFieldEntry[] | undefined,\n path: IssuePath,\n ctx: Ctx,\n): FieldEntry[] | undefined {\n if (!entries || entries.length === 0) return entries === undefined ? undefined : []\n return entries.map((entry, i) => {\n if (entry.type === 'claim') {\n const desugared = {\n ...stripUndefined({name: entry.name, title: entry.title, description: entry.description}),\n type: 'value.actor',\n source: {type: 'write'},\n } as FieldEntry\n ctx.claimFields.set(desugared, {name: entry.name, path: [...path, i]})\n return desugared\n }\n const editable = normalizeEditable(entry.editable, [...path, i, 'editable'], ctx)\n return {\n ...stripUndefined({\n type: entry.type,\n name: entry.name,\n title: entry.title,\n description: entry.description,\n required: entry.required,\n editable,\n }),\n source: entry.source,\n } as FieldEntry\n })\n}\n\n/**\n * Normalise the authoring `editable` grammar to its stored form: `true` and a\n * raw predicate string pass through; a non-empty role list becomes the same\n * membership predicate `action.roles` desugars to. An empty list is an author\n * error (it would name no one) — fail loud rather than silently opening or\n * closing the slot.\n */\nfunction normalizeEditable(\n editable: AuthoringEditable | undefined,\n path: IssuePath,\n ctx: Ctx,\n): Editable | undefined {\n if (editable === undefined || editable === true) return editable\n if (Array.isArray(editable)) {\n const condition = rolesCondition(editable, ctx.roleAliases)\n if (condition === undefined) {\n ctx.issues.push({\n path,\n message:\n 'editable: [] names no roles — use `true` to open the slot to anyone in its scope, ' +\n 'or list at least one role',\n })\n return undefined\n }\n return condition\n }\n return editable\n}\n\n/** The names of slots that declare `editable` across the scopes a stage's\n * override can narrow: workflow + this stage + this stage's tasks. */\nfunction editableSlotNames(\n workflowFields: readonly FieldEntry[] | undefined,\n stageFields: readonly FieldEntry[] | undefined,\n tasks: readonly Task[],\n): Set<string> {\n const names = new Set<string>()\n const collect = (entries: readonly FieldEntry[] | undefined): void => {\n for (const entry of entries ?? []) if (entry.editable !== undefined) names.add(entry.name)\n }\n collect(workflowFields)\n collect(stageFields)\n for (const task of tasks) collect(task.fields)\n return names\n}\n\n/**\n * Normalise a stage's `editable` override map. Each value goes through the same\n * grammar normalisation as a slot's own `editable`; each key must name a slot\n * that declares `editable` somewhere in scope, since an override on a closed\n * slot is inert (the runtime ANDs override with baseline, and `false && x` is\n * still closed) — a likely author mistake, so fail loud.\n */\nfunction desugarStageEditable(\n overrides: Record<string, AuthoringEditable> | undefined,\n inScope: Set<string>,\n path: IssuePath,\n ctx: Ctx,\n): Record<string, Editable> | undefined {\n if (overrides === undefined) return undefined\n const out: Record<string, Editable> = {}\n for (const [name, value] of Object.entries(overrides)) {\n if (!inScope.has(name)) {\n ctx.issues.push({\n path: [...path, name],\n message:\n `stage editable override \"${name}\" does not narrow an editable slot in scope — name a ` +\n 'workflow/stage/task slot of this stage that declares `editable`',\n })\n continue\n }\n const normalized = normalizeEditable(value, [...path, name], ctx)\n if (normalized !== undefined) out[name] = normalized\n }\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction layerOf(entries: readonly FieldEntry[] | 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 taskFields = desugarFieldEntries(task.fields, [...path, 'fields'], ctx)\n const env: LexicalEnv = {\n layers: [{scope: 'task', entries: layerOf(taskFields)}, ...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 requirements: task.requirements,\n completeWhen: task.completeWhen,\n failWhen: task.failWhen,\n effects: task.effects,\n subworkflows: task.subworkflows,\n }),\n activation: task.activation ?? 'manual',\n ...(taskFields ? {fields: taskFields} : {}),\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 = andConditions([rolesCondition(action.roles, ctx.roleAliases), 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.field === 'string' ? {field: action.field} : action.field\n const resolved = resolveRef(ref, env, [...path, 'field'], ctx)\n if (resolved) {\n const entry = entryAt(env, resolved)\n if (entry && entry.type !== 'value.actor') {\n ctx.issues.push({\n path: [...path, 'field'],\n message:\n `claim action \"${action.name}\" references \"${resolved.field}\" of kind ` +\n `\"${entry.type}\" — a claim pair needs an actor-valued entry ` +\n `(a \"claim\" or \"value.actor\" field declaration)`,\n })\n }\n checkShadowedClaimTarget(action.name, ref.field, resolved, env, [...path, 'field'], ctx)\n if (entry) ctx.claimedFields.add(entry)\n }\n\n const noSteal = `!defined($fields.${ref.field})`\n const filter = andConditions([\n noSteal,\n rolesCondition(action.roles, ctx.roleAliases),\n action.filter,\n ])\n const ops: Op[] = resolved ? [{type: 'field.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 `$fields.<name>` (nearest declaring scope wins in the rendered\n * overlay), while the `field.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 field: string,\n resolved: StoredFieldRef,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): void {\n const nearest = env.layers.find((l) => l.entries.has(field))\n if (nearest === undefined || nearest.scope === resolved.scope) return\n ctx.issues.push({\n path,\n message:\n `claim action \"${actionName}\" targets \"${field}\" at scope \"${resolved.scope}\", but a ` +\n `nearer ${nearest.scope}-scope entry of the same name shadows it in $fields — 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` field nothing claims into. */\nfunction checkUnclaimedClaimFields(ctx: Ctx): void {\n for (const [entry, {name, path}] of ctx.claimFields) {\n if (ctx.claimedFields.has(entry)) continue\n ctx.issues.push({\n path,\n message:\n `claim field \"${name}\" is never referenced by a claim action — ` +\n `you announced the pattern and wrote half of it. Declare a ` +\n `defineAction({ type: \"claim\", field: \"${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: 'field.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: 'field.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: AuthoringFieldRef,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): StoredFieldRef | 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.field)) return {scope: layer.scope, field: ref.field}\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 `field reference \"${ref.field}\"${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: StoredFieldRef): FieldEntry | undefined {\n return env.layers.find((l) => l.scope === ref.scope)?.entries.get(ref.field)\n}\n\n/** Keeps the stored shape parseable after a resolution issue was reported. */\nfunction fallbackRef(ref: AuthoringFieldRef): StoredFieldRef {\n return {scope: ref.scope ?? 'workflow', field: ref.field}\n}\n\n// Small shared helpers\n\nfunction rolesCondition(\n roles: readonly string[] | undefined,\n aliases: RoleAliases | undefined,\n): string | undefined {\n if (!roles || roles.length === 0) return undefined\n return groq`count($actor.roles[@ in ${expandRequiredRoles(roles, aliases)}]) > 0`\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 {\n Effect,\n IssuePath,\n Op,\n FieldEntry,\n Task,\n ValidationIssue,\n WorkflowDefinition,\n} 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 'fields',\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 FieldScopeSite {\n entries: readonly FieldEntry[] | undefined\n scope: 'workflow' | 'stage' | 'task'\n path: IssuePath\n label: string\n}\n\nfunction fieldScopes(def: WorkflowDefinition): FieldScopeSite[] {\n const scopes: FieldScopeSite[] = [\n {entries: def.fields, scope: 'workflow', path: ['fields'], label: 'workflow fields'},\n ]\n for (const [i, stage] of def.stages.entries()) {\n scopes.push({\n entries: stage.fields,\n scope: 'stage',\n path: ['stages', i, 'fields'],\n label: `stage \"${stage.name}\" fields`,\n })\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n scopes.push({\n entries: task.fields,\n scope: 'task',\n path: ['stages', i, 'tasks', j, 'fields'],\n label: `task \"${task.name}\" fields`,\n })\n }\n }\n return scopes\n}\n\n/**\n * `required` is the start/spawn fail-fast for a load-bearing `init` slot: the\n * caller MUST fill it or {@link RequiredFieldNotProvidedError} fires. It only\n * makes sense on a WORKFLOW-scope `init` entry — that is the one scope a caller\n * seeds (via `initialFields` at start, or the parent's `subworkflows.with` at\n * spawn). Stage/task fields are engine-resolved at entry/activation with no\n * caller seed, and a non-`init` source fills itself — so `required` anywhere\n * else can never be satisfied. Reject it at deploy rather than ship a slot that\n * always throws.\n */\nfunction checkRequiredField(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const {entries, scope, path, label} of fieldScopes(def)) {\n for (const [n, entry] of (entries ?? []).entries()) {\n if (entry.required !== true) continue\n if (scope !== 'workflow') {\n issues.push({\n path: [...path, n, 'required'],\n message:\n `${label} entry \"${entry.name}\" is \\`required\\`, but \\`required\\` applies only to ` +\n `workflow-scope \\`init\\` entries — only those are caller-supplied at start/spawn`,\n })\n } else if (entry.source.type !== 'init') {\n issues.push({\n path: [...path, n, 'required'],\n message:\n `field entry \"${entry.name}\" is \\`required\\` but its source is \"${entry.source.type}\" — ` +\n `\\`required\\` applies only to \\`init\\`-sourced entries (the caller fills them at start/spawn)`,\n })\n }\n }\n }\n}\n\n/**\n * Field entry names are the per-scope lookup keys (`$fields.<name>`, op\n * targets, runtime `find()` reads) — a duplicate within one scope makes\n * different readers silently land on different entries.\n */\nfunction checkFieldEntryNames(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const {entries, path, label} of fieldScopes(def)) {\n checkDuplicates(\n (entries ?? []).map((entry, n) => ({name: entry.name, path: [...path, n, 'name']})),\n `field 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 fieldScopes(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 field 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 checkFieldEntryNames(def, issues)\n checkRequiredField(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 AuthoringFieldEntrySchema,\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 AuthoringFieldEntry,\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 defineField(entry: AuthoringFieldEntry): AuthoringFieldEntry {\n return parseOrThrow(AuthoringFieldEntrySchema, entry, labelFor('defineField', 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;AC6CO,SAAS,gBAAgB,WAA6C;AAC3E,QAAM,MAAW;AAAA,IACf,QAAQ,CAAA;AAAA,IACR,iCAAiB,IAAA;AAAA,IACjB,mCAAmB,IAAA;AAAA,IACnB,aAAa,UAAU;AAAA,EAAA,GAGnB,iBAAiB,oBAAoB,UAAU,QAAQ,CAAC,QAAQ,GAAG,GAAG,GACtE,gBAAgB,QAAQ,cAAc,GAEtC,SAAS,UAAU,OAAO,IAAI,CAAC,OAAO,MAAM;AAChD,UAAM,OAAkB,CAAC,UAAU,CAAC,GAC9B,cAAc,oBAAoB,MAAM,QAAQ,CAAC,GAAG,MAAM,QAAQ,GAAG,GAAG,GACxE,WAAuB;AAAA,MAC3B,QAAQ;AAAA,QACN,EAAC,OAAO,SAAS,SAAS,QAAQ,WAAW,EAAA;AAAA,QAC7C,EAAC,OAAO,YAAY,SAAS,cAAA;AAAA,MAAa;AAAA,IAC5C,GAEI,SAAS,MAAM,SAAS,CAAA,GAAI;AAAA,MAAI,CAAC,MAAM,MA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AwB;AACnD,SAAO,aAAa,cAAc,QAAQ,SAAS,gBAAgB,MAAM,CAAC;AAC5E;AAEA,SAAS,gBAAgB,YAAyC;AAChE,QAAM,EAAC,MAAM,GAAA,IAAM;AACnB,SAAI,OAAO,QAAS,WAAiB,qBAAqB,IAAI,OAC1D,OAAO,MAAO,WAAiB,4BAAuB,EAAE,OACrD;AACT;AAuBO,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,OAAwB;AACpD,MAAI,SAAS,OAAO,SAAU,YAAY,UAAU,OAAO;AACzD,UAAM,MAAO,MAAkC;AAC/C,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`$fields.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` field/action pair) is\n * tied by an ordinary deploy-checked *reference*, never by creation: sugar\n * never adds a field 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.fieldRead` VALUES are different: their `scope` stays optional in\n * the stored form, and an omitted scope resolves lexically at read time.\n */\n\nimport {andConditions} from '../core/conditions.ts'\nimport {expandRequiredRoles} from '../core/roles.ts'\nimport type {FieldKind} from '../types/field-values.ts'\nimport {groq} from './groq.ts'\nimport type {\n Action,\n AuthoringAction,\n AuthoringEditable,\n AuthoringManualTarget,\n AuthoringOp,\n AuthoringFieldEntry,\n AuthoringFieldRef,\n AuthoringTask,\n AuthoringTransition,\n AuthoringWorkflow,\n Editable,\n IssuePath,\n ManualTarget,\n Op,\n RoleAliases,\n Source,\n FieldEntry,\n StoredFieldRef,\n Task,\n Transition,\n TransitionOp,\n ValidationIssue,\n WorkflowDefinition,\n} from './schema.ts'\n\n/** One lexical layer: the field entries declared at a scope, by name. */\ntype ScopeLayer = ReadonlyMap<string, FieldEntry>\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 claimFields: Map<FieldEntry, {name: string; path: IssuePath}>\n /** Claim-field entries that at least one `claim` action resolved to — pair validation. */\n claimedFields: Set<FieldEntry>\n /** The definition's `roleAliases`, baked into every `roles` gate it desugars. */\n roleAliases: RoleAliases | undefined\n}\n\nexport function desugarWorkflow(authoring: AuthoringWorkflow): DesugarResult {\n const ctx: Ctx = {\n issues: [],\n claimFields: new Map(),\n claimedFields: new Set(),\n roleAliases: authoring.roleAliases,\n }\n\n const workflowFields = desugarFieldEntries(authoring.fields, ['fields'], ctx)\n const workflowLayer = layerOf(workflowFields)\n\n const stages = authoring.stages.map((stage, i) => {\n const path: IssuePath = ['stages', i]\n const stageFields = desugarFieldEntries(stage.fields, [...path, 'fields'], ctx)\n const stageEnv: LexicalEnv = {\n layers: [\n {scope: 'stage', entries: layerOf(stageFields)},\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 const editable = desugarStageEditable(\n stage.editable,\n editableSlotNames(workflowFields, stageFields, tasks),\n [...path, 'editable'],\n ctx,\n )\n return {\n ...stripUndefined({\n name: stage.name,\n title: stage.title,\n description: stage.description,\n guards: stage.guards,\n }),\n ...(stageFields ? {fields: stageFields} : {}),\n ...(tasks.length > 0 ? {tasks} : {}),\n ...(transitions.length > 0 ? {transitions} : {}),\n ...(editable ? {editable} : {}),\n }\n })\n\n checkUnclaimedClaimFields(ctx)\n\n const definition = {\n ...stripUndefined({\n name: authoring.name,\n version: authoring.version,\n title: authoring.title,\n description: authoring.description,\n role: authoring.role,\n initialStage: authoring.initialStage,\n predicates: authoring.predicates,\n roleAliases: authoring.roleAliases,\n }),\n ...(workflowFields ? {fields: workflowFields} : {}),\n stages,\n } as WorkflowDefinition\n\n return {definition, issues: ctx.issues}\n}\n\n// Field entries — the `claim` sugar expands to value.actor with an implied\n// `write` source, strictly within the entry; the `editable` grammar's\n// `role[]` convenience normalises to a membership predicate.\n\nfunction desugarFieldEntries(\n entries: readonly AuthoringFieldEntry[] | undefined,\n path: IssuePath,\n ctx: Ctx,\n): FieldEntry[] | undefined {\n if (!entries || entries.length === 0) return entries === undefined ? undefined : []\n return entries.map((entry, i) => {\n if (entry.type === 'claim') {\n const desugared = {\n ...stripUndefined({name: entry.name, title: entry.title, description: entry.description}),\n type: 'value.actor',\n source: {type: 'write'},\n } as FieldEntry\n ctx.claimFields.set(desugared, {name: entry.name, path: [...path, i]})\n return desugared\n }\n const editable = normalizeEditable(entry.editable, [...path, i, 'editable'], ctx)\n return {\n ...stripUndefined({\n type: entry.type,\n name: entry.name,\n title: entry.title,\n description: entry.description,\n required: entry.required,\n editable,\n }),\n source: entry.source,\n } as FieldEntry\n })\n}\n\n/**\n * Normalise the authoring `editable` grammar to its stored form: `true` and a\n * raw predicate string pass through; a non-empty role list becomes the same\n * membership predicate `action.roles` desugars to. An empty list is an author\n * error (it would name no one) — fail loud rather than silently opening or\n * closing the slot.\n */\nfunction normalizeEditable(\n editable: AuthoringEditable | undefined,\n path: IssuePath,\n ctx: Ctx,\n): Editable | undefined {\n if (editable === undefined || editable === true) return editable\n if (Array.isArray(editable)) {\n const condition = rolesCondition(editable, ctx.roleAliases)\n if (condition === undefined) {\n ctx.issues.push({\n path,\n message:\n 'editable: [] names no roles — use `true` to open the slot to anyone in its scope, ' +\n 'or list at least one role',\n })\n return undefined\n }\n return condition\n }\n return editable\n}\n\n/** The names of slots that declare `editable` across the scopes a stage's\n * override can narrow: workflow + this stage + this stage's tasks. */\nfunction editableSlotNames(\n workflowFields: readonly FieldEntry[] | undefined,\n stageFields: readonly FieldEntry[] | undefined,\n tasks: readonly Task[],\n): Set<string> {\n const names = new Set<string>()\n const collect = (entries: readonly FieldEntry[] | undefined): void => {\n for (const entry of entries ?? []) if (entry.editable !== undefined) names.add(entry.name)\n }\n collect(workflowFields)\n collect(stageFields)\n for (const task of tasks) collect(task.fields)\n return names\n}\n\n/**\n * Normalise a stage's `editable` override map. Each value goes through the same\n * grammar normalisation as a slot's own `editable`; each key must name a slot\n * that declares `editable` somewhere in scope, since an override on a closed\n * slot is inert (the runtime ANDs override with baseline, and `false && x` is\n * still closed) — a likely author mistake, so fail loud.\n */\nfunction desugarStageEditable(\n overrides: Record<string, AuthoringEditable> | undefined,\n inScope: Set<string>,\n path: IssuePath,\n ctx: Ctx,\n): Record<string, Editable> | undefined {\n if (overrides === undefined) return undefined\n const out: Record<string, Editable> = {}\n for (const [name, value] of Object.entries(overrides)) {\n if (!inScope.has(name)) {\n ctx.issues.push({\n path: [...path, name],\n message:\n `stage editable override \"${name}\" does not narrow an editable slot in scope — name a ` +\n 'workflow/stage/task slot of this stage that declares `editable`',\n })\n continue\n }\n const normalized = normalizeEditable(value, [...path, name], ctx)\n if (normalized !== undefined) out[name] = normalized\n }\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction layerOf(entries: readonly FieldEntry[] | 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 taskFields = desugarFieldEntries(task.fields, [...path, 'fields'], ctx)\n const env: LexicalEnv = {\n layers: [{scope: 'task', entries: layerOf(taskFields)}, ...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 const target = desugarTarget(task.target, env, [...path, 'target'], ctx)\n return {\n ...stripUndefined({\n name: task.name,\n title: task.title,\n description: task.description,\n kind: task.kind,\n filter: task.filter,\n requirements: task.requirements,\n completeWhen: task.completeWhen,\n failWhen: task.failWhen,\n effects: task.effects,\n subworkflows: task.subworkflows,\n }),\n activation: task.activation ?? 'manual',\n ...(target ? {target} : {}),\n ...(taskFields ? {fields: taskFields} : {}),\n ...(ops ? {ops} : {}),\n ...(actions.length > 0 ? {actions} : {}),\n } as Task\n}\n\n// Document-valued field kinds a manual `target` deep-link can point at — the\n// entry whose resolved GDR the consumer opens. Typed as {@link FieldKind} so a\n// renamed or removed kind fails to compile rather than silently going stale.\nconst TARGET_DOC_KINDS: readonly FieldKind[] = ['doc.ref', 'doc.refs', 'release.ref']\n\n/**\n * Resolve a manual task's deep-link `target`: a URL passes through; a field\n * reference resolves lexically to an explicit-scope {@link StoredFieldRef}\n * (like every op target) and must name a document-valued entry, since the\n * affordance opens that entry's document.\n */\nfunction desugarTarget(\n target: AuthoringManualTarget | undefined,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): ManualTarget | undefined {\n if (target === undefined || target.type === 'url') return target\n const ref = typeof target.field === 'string' ? {field: target.field} : target.field\n const field = resolveRef(ref, env, [...path, 'field'], ctx) ?? fallbackRef(ref)\n const entry = entryAt(env, field)\n if (entry && !TARGET_DOC_KINDS.includes(entry.type)) {\n ctx.issues.push({\n path: [...path, 'field'],\n message:\n `manual task target references \"${field.field}\" of kind \"${entry.type}\" — a deep-link ` +\n `target needs a document-valued entry (${TARGET_DOC_KINDS.join(', ')})`,\n })\n }\n return {type: 'field', field}\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 = andConditions([rolesCondition(action.roles, ctx.roleAliases), 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.field === 'string' ? {field: action.field} : action.field\n const resolved = resolveRef(ref, env, [...path, 'field'], ctx)\n if (resolved) {\n const entry = entryAt(env, resolved)\n if (entry && entry.type !== 'value.actor') {\n ctx.issues.push({\n path: [...path, 'field'],\n message:\n `claim action \"${action.name}\" references \"${resolved.field}\" of kind ` +\n `\"${entry.type}\" — a claim pair needs an actor-valued entry ` +\n `(a \"claim\" or \"value.actor\" field declaration)`,\n })\n }\n checkShadowedClaimTarget(action.name, ref.field, resolved, env, [...path, 'field'], ctx)\n if (entry) ctx.claimedFields.add(entry)\n }\n\n const noSteal = `!defined($fields.${ref.field})`\n const filter = andConditions([\n noSteal,\n rolesCondition(action.roles, ctx.roleAliases),\n action.filter,\n ])\n const ops: Op[] = resolved ? [{type: 'field.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 `$fields.<name>` (nearest declaring scope wins in the rendered\n * overlay), while the `field.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 field: string,\n resolved: StoredFieldRef,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): void {\n const nearest = env.layers.find((l) => l.entries.has(field))\n if (nearest === undefined || nearest.scope === resolved.scope) return\n ctx.issues.push({\n path,\n message:\n `claim action \"${actionName}\" targets \"${field}\" at scope \"${resolved.scope}\", but a ` +\n `nearer ${nearest.scope}-scope entry of the same name shadows it in $fields — 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` field nothing claims into. */\nfunction checkUnclaimedClaimFields(ctx: Ctx): void {\n for (const [entry, {name, path}] of ctx.claimFields) {\n if (ctx.claimedFields.has(entry)) continue\n ctx.issues.push({\n path,\n message:\n `claim field \"${name}\" is never referenced by a claim action — ` +\n `you announced the pattern and wrote half of it. Declare a ` +\n `defineAction({ type: \"claim\", field: \"${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: 'field.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: 'field.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: AuthoringFieldRef,\n env: LexicalEnv,\n path: IssuePath,\n ctx: Ctx,\n): StoredFieldRef | 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.field)) return {scope: layer.scope, field: ref.field}\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 `field reference \"${ref.field}\"${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: StoredFieldRef): FieldEntry | undefined {\n return env.layers.find((l) => l.scope === ref.scope)?.entries.get(ref.field)\n}\n\n/** Keeps the stored shape parseable after a resolution issue was reported. */\nfunction fallbackRef(ref: AuthoringFieldRef): StoredFieldRef {\n return {scope: ref.scope ?? 'workflow', field: ref.field}\n}\n\n// Small shared helpers\n\nfunction rolesCondition(\n roles: readonly string[] | undefined,\n aliases: RoleAliases | undefined,\n): string | undefined {\n if (!roles || roles.length === 0) return undefined\n return groq`count($actor.roles[@ in ${expandRequiredRoles(roles, aliases)}]) > 0`\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 {TaskKind} from '../types/enums.ts'\nimport type {\n Effect,\n IssuePath,\n Op,\n FieldEntry,\n Task,\n ValidationIssue,\n WorkflowDefinition,\n} 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 'fields',\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 FieldScopeSite {\n entries: readonly FieldEntry[] | undefined\n scope: 'workflow' | 'stage' | 'task'\n path: IssuePath\n label: string\n}\n\nfunction fieldScopes(def: WorkflowDefinition): FieldScopeSite[] {\n const scopes: FieldScopeSite[] = [\n {entries: def.fields, scope: 'workflow', path: ['fields'], label: 'workflow fields'},\n ]\n for (const [i, stage] of def.stages.entries()) {\n scopes.push({\n entries: stage.fields,\n scope: 'stage',\n path: ['stages', i, 'fields'],\n label: `stage \"${stage.name}\" fields`,\n })\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n scopes.push({\n entries: task.fields,\n scope: 'task',\n path: ['stages', i, 'tasks', j, 'fields'],\n label: `task \"${task.name}\" fields`,\n })\n }\n }\n return scopes\n}\n\n/**\n * `required` is the start/spawn fail-fast for a load-bearing `init` slot: the\n * caller MUST fill it or {@link RequiredFieldNotProvidedError} fires. It only\n * makes sense on a WORKFLOW-scope `init` entry — that is the one scope a caller\n * seeds (via `initialFields` at start, or the parent's `subworkflows.with` at\n * spawn). Stage/task fields are engine-resolved at entry/activation with no\n * caller seed, and a non-`init` source fills itself — so `required` anywhere\n * else can never be satisfied. Reject it at deploy rather than ship a slot that\n * always throws.\n */\nfunction checkRequiredField(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const {entries, scope, path, label} of fieldScopes(def)) {\n for (const [n, entry] of (entries ?? []).entries()) {\n if (entry.required !== true) continue\n if (scope !== 'workflow') {\n issues.push({\n path: [...path, n, 'required'],\n message:\n `${label} entry \"${entry.name}\" is \\`required\\`, but \\`required\\` applies only to ` +\n `workflow-scope \\`init\\` entries — only those are caller-supplied at start/spawn`,\n })\n } else if (entry.source.type !== 'init') {\n issues.push({\n path: [...path, n, 'required'],\n message:\n `field entry \"${entry.name}\" is \\`required\\` but its source is \"${entry.source.type}\" — ` +\n `\\`required\\` applies only to \\`init\\`-sourced entries (the caller fills them at start/spawn)`,\n })\n }\n }\n }\n}\n\n/**\n * Field entry names are the per-scope lookup keys (`$fields.<name>`, op\n * targets, runtime `find()` reads) — a duplicate within one scope makes\n * different readers silently land on different entries.\n */\nfunction checkFieldEntryNames(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const {entries, path, label} of fieldScopes(def)) {\n checkDuplicates(\n (entries ?? []).map((entry, n) => ({name: entry.name, path: [...path, n, 'name']})),\n `field 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 fieldScopes(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 field entry per scope — the inbox reads it by kind',\n })\n }\n}\n\ninterface TaskShape {\n hasActions: boolean\n hasEffects: boolean\n hasCompleteWhen: boolean\n hasSubworkflows: boolean\n}\n\nfunction taskShape(task: Task): TaskShape {\n return {\n hasActions: (task.actions ?? []).length > 0,\n hasEffects: (task.effects ?? []).length > 0,\n hasCompleteWhen: task.completeWhen !== undefined,\n hasSubworkflows: task.subworkflows !== undefined,\n }\n}\n\n/**\n * Per-kind shape contract: each rule returns one fragment per way the declared\n * kind contradicts the task's actual shape, so a task with several faults\n * reports them all. The completion-mechanism rules (`user`/`manual` need\n * something to resolve them) stop an author shipping a labelled task that\n * silently auto-resolves as a machine step. Keyed exhaustively by\n * {@link TaskKind}, so a new kind forces a contract here.\n *\n * These reject only genuine contradictions, not every shape the derivation\n * would label differently — declaring a kind is precisely how an author\n * overrides the derived default. So `service` permits `actions` (a \"retry\"\n * button on an effect step) and `script` permits `effects` (a fire-and-forget\n * side effect on an inline step), even though those shapes derive as `user` /\n * `service` respectively.\n */\nconst KIND_SHAPE_RULES: Record<TaskKind, (s: TaskShape) => string[]> = {\n user: (s) => (s.hasActions ? [] : ['needs at least one action for a person to fire']),\n service: (s) =>\n s.hasEffects ? [] : ['needs at least one effect — the automated work it performs'],\n manual: (s) =>\n [\n s.hasActions || s.hasCompleteWhen\n ? undefined\n : 'needs a way to complete — an action to acknowledge it, or a `completeWhen` predicate ' +\n 'to verify it (otherwise it auto-resolves on activation)',\n s.hasSubworkflows\n ? 'is off-system work, not a fan-out — drop `subworkflows` or move it to its own task'\n : undefined,\n ].filter((m): m is string => m !== undefined),\n receive: (s) =>\n [\n s.hasCompleteWhen || s.hasSubworkflows\n ? undefined\n : 'needs a `completeWhen` (or `subworkflows`) condition to wait on',\n s.hasActions ? 'has no actor, so it cannot carry actions' : undefined,\n ].filter((m): m is string => m !== undefined),\n script: (s) =>\n [\n s.hasActions ? 'runs inline with no actor, so it cannot carry actions' : undefined,\n s.hasCompleteWhen\n ? 'resolves on activation, so it cannot carry a `completeWhen` (that is a `receive`/`service` wait)'\n : undefined,\n s.hasSubworkflows\n ? 'resolves on activation, so it cannot fan out with `subworkflows`'\n : undefined,\n ].filter((m): m is string => m !== undefined),\n}\n\n/**\n * Verify each task's EXPLICIT {@link Task.kind} against its shape, and that a\n * `target` only rides a `manual` task. Advisory at runtime — this is the\n * deploy-time \"does this definition make sense?\" gate, so every contradiction\n * is reported (never short-circuited) for one en-masse error.\n */\nfunction checkTaskKinds(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const [i, stage] of def.stages.entries()) {\n for (const [j, task] of (stage.tasks ?? []).entries()) {\n const path: IssuePath = ['stages', i, 'tasks', j]\n if (task.target !== undefined && task.kind !== 'manual') {\n issues.push({\n path: [...path, 'target'],\n message: `task \"${task.name}\" has a \\`target\\` but is not \\`kind: \"manual\"\\` — a target is the deep-link for off-system manual work`,\n })\n }\n if (task.kind === undefined) continue\n for (const fault of KIND_SHAPE_RULES[task.kind](taskShape(task))) {\n issues.push({\n path: [...path, 'kind'],\n message: `task \"${task.name}\" declares kind \"${task.kind}\" but ${fault}`,\n })\n }\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 checkFieldEntryNames(def, issues)\n checkRequiredField(def, issues)\n checkPredicates(def, issues)\n checkCanOutsideActionFilters(def, issues)\n checkAssigneesEntries(def, issues)\n checkTaskKinds(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 AuthoringFieldEntrySchema,\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 AuthoringFieldEntry,\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 defineField(entry: AuthoringFieldEntry): AuthoringFieldEntry {\n return parseOrThrow(AuthoringFieldEntrySchema, entry, labelFor('defineField', 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;ACgDO,SAAS,gBAAgB,WAA6C;AAC3E,QAAM,MAAW;AAAA,IACf,QAAQ,CAAA;AAAA,IACR,iCAAiB,IAAA;AAAA,IACjB,mCAAmB,IAAA;AAA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AAEO,SAAS,YAAY,OAAiD;AAC3E,SAAO,aAAa,2BAA2B,OAAO,SAAS,eAAe,KAAK,CAAC;AACtF;AAEO,SAAS,SAAS,IAA8B;AACrD,SAAO,aAAa,mBAAmB,IAAI,UAAU;AACvD;AAEO,SAAS,YAAY,OAAqB;AAC/C,SAAO,aAAa,aAAa,OAAO,SAAS,eAAe,KAAK,CAAC;AACxE;AAMO,SAAS,aAAa,QAAwB;AACnD,SAAO,aAAa,cAAc,QAAQ,SAAS,gBAAgB,MAAM,CAAC;AAC5E;AAEA,SAAS,gBAAgB,YAAyC;AAChE,QAAM,EAAC,MAAM,GAAA,IAAM;AACnB,SAAI,OAAO,QAAS,WAAiB,qBAAqB,IAAI,OAC1D,OAAO,MAAO,WAAiB,4BAAuB,EAAE,OACrD;AACT;AAuBO,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,OAAwB;AACpD,MAAI,SAAS,OAAO,SAAU,YAAY,UAAU,OAAO;AACzD,UAAM,MAAO,MAAkC;AAC/C,QAAI,OAAO,OAAQ,iBAAiB,GAAG,EAAE,KAAK,GAAG;AAAA,EACnD;AACA,SAAO;AACT;"}
|
package/dist/index.cjs
CHANGED
|
@@ -1666,12 +1666,16 @@ function buildInstanceBase(args) {
|
|
|
1666
1666
|
lastChangedAt: now
|
|
1667
1667
|
};
|
|
1668
1668
|
}
|
|
1669
|
-
const
|
|
1669
|
+
const ENGINE_ACTOR_ID_PREFIX = "engine.";
|
|
1670
|
+
function engineSystemActor(name) {
|
|
1671
|
+
return { kind: "system", id: `${ENGINE_ACTOR_ID_PREFIX}${name}` };
|
|
1672
|
+
}
|
|
1673
|
+
function isEngineActor(actor) {
|
|
1674
|
+
return actor.kind === "system" && actor.id.startsWith(ENGINE_ACTOR_ID_PREFIX);
|
|
1675
|
+
}
|
|
1676
|
+
const MAX_SPAWN_DEPTH = 6, SUBWORKFLOWS_ALL_DONE = "count($subworkflows[status != 'done']) == 0";
|
|
1670
1677
|
function gateActor(outcome) {
|
|
1671
|
-
return
|
|
1672
|
-
kind: "system",
|
|
1673
|
-
id: outcome === "failed" ? FAIL_WHEN_SYSTEM_ID : COMPLETE_WHEN_SYSTEM_ID
|
|
1674
|
-
};
|
|
1678
|
+
return engineSystemActor(outcome === "failed" ? "failWhen" : "completeWhen");
|
|
1675
1679
|
}
|
|
1676
1680
|
function effectiveCompleteWhen(task) {
|
|
1677
1681
|
return task.completeWhen ?? (task.subworkflows !== void 0 ? SUBWORKFLOWS_ALL_DONE : void 0);
|
|
@@ -2310,7 +2314,7 @@ function resolveMachineStep(mutation, task, entry, now) {
|
|
|
2310
2314
|
stage: mutation.currentStage,
|
|
2311
2315
|
to: "done",
|
|
2312
2316
|
at: now,
|
|
2313
|
-
actor:
|
|
2317
|
+
actor: engineSystemActor("machineStep")
|
|
2314
2318
|
});
|
|
2315
2319
|
}
|
|
2316
2320
|
async function buildStageTasks(ctx, stage) {
|
|
@@ -2798,6 +2802,18 @@ function editDisabledReason(args) {
|
|
|
2798
2802
|
if (!predicateSatisfied)
|
|
2799
2803
|
return { kind: "editor-not-permitted", predicate: effective === !0 ? "true" : effective };
|
|
2800
2804
|
}
|
|
2805
|
+
function hasItems(arr) {
|
|
2806
|
+
return arr !== void 0 && arr.length > 0;
|
|
2807
|
+
}
|
|
2808
|
+
function deriveTaskKind(task) {
|
|
2809
|
+
return hasItems(task.actions) ? "user" : hasItems(task.effects) ? "service" : task.completeWhen !== void 0 || task.subworkflows !== void 0 ? "receive" : "script";
|
|
2810
|
+
}
|
|
2811
|
+
function taskKind(task) {
|
|
2812
|
+
return task.kind ?? deriveTaskKind(task);
|
|
2813
|
+
}
|
|
2814
|
+
function driverKind(actor) {
|
|
2815
|
+
return actor.kind === "user" ? "person" : actor.kind === "ai" ? "agent" : isEngineActor(actor) ? "engine" : "service";
|
|
2816
|
+
}
|
|
2801
2817
|
async function evaluateInstance(args) {
|
|
2802
2818
|
const { client, tag, instanceId, resourceClients } = args, now = (args.clock ?? wallClock)();
|
|
2803
2819
|
validateTag(tag);
|
|
@@ -2987,6 +3003,7 @@ async function evaluateTask(args) {
|
|
|
2987
3003
|
return {
|
|
2988
3004
|
task,
|
|
2989
3005
|
status,
|
|
3006
|
+
kind: taskKind(task),
|
|
2990
3007
|
// "pending on actor" treats both `pending` and `active` as waiting on
|
|
2991
3008
|
// the assignee — pending tasks just haven't been activated yet, but
|
|
2992
3009
|
// they're still inbox items. The inbox reads the assignees-kind field
|
|
@@ -3241,7 +3258,7 @@ async function commitAction(ctx, taskName, actionName, callerParams, options) {
|
|
|
3241
3258
|
stage: stage.name,
|
|
3242
3259
|
task: taskName,
|
|
3243
3260
|
action: actionName,
|
|
3244
|
-
...actor !== void 0 ? { actor } : {}
|
|
3261
|
+
...actor !== void 0 ? { actor, driverKind: driverKind(actor) } : {}
|
|
3245
3262
|
});
|
|
3246
3263
|
const statusBefore = mutEntry.status, ranOps = await runOps({
|
|
3247
3264
|
ops: action.ops,
|
|
@@ -4069,7 +4086,7 @@ async function drainEffectsInternal(args) {
|
|
|
4069
4086
|
effectHandlers,
|
|
4070
4087
|
missingHandler,
|
|
4071
4088
|
logger
|
|
4072
|
-
} = args, drainerActor = args.access?.actor ??
|
|
4089
|
+
} = args, drainerActor = args.access?.actor ?? engineSystemActor("drainEffects"), completionAccess = {
|
|
4073
4090
|
actor: drainerActor,
|
|
4074
4091
|
...args.access?.grants !== void 0 ? { grants: args.access.grants } : {}
|
|
4075
4092
|
};
|
|
@@ -4586,6 +4603,35 @@ const HISTORY_DISPLAY = {
|
|
|
4586
4603
|
title: "Workflow instance",
|
|
4587
4604
|
description: "A running (or finished) workflow against its declared fields."
|
|
4588
4605
|
}
|
|
4606
|
+
}, TASK_KIND_DISPLAY = {
|
|
4607
|
+
user: {
|
|
4608
|
+
title: "User task",
|
|
4609
|
+
description: "A person acts via the app \u2014 renders action buttons ranked by outcome."
|
|
4610
|
+
},
|
|
4611
|
+
service: {
|
|
4612
|
+
title: "Service task",
|
|
4613
|
+
description: "An automated system or effect does the work \u2014 renders effect drain status."
|
|
4614
|
+
},
|
|
4615
|
+
script: {
|
|
4616
|
+
title: "Script task",
|
|
4617
|
+
description: "The engine runs a step inline and resolves on activation \u2014 an audit row."
|
|
4618
|
+
},
|
|
4619
|
+
manual: {
|
|
4620
|
+
title: "Manual task",
|
|
4621
|
+
description: "Work done off-system, acknowledged by a person or verified by a predicate \u2014 renders an instruction card with a deep-link."
|
|
4622
|
+
},
|
|
4623
|
+
receive: {
|
|
4624
|
+
title: "Receive task",
|
|
4625
|
+
description: 'No actor; the engine waits on a condition \u2014 renders "waiting until \u2026", no buttons.'
|
|
4626
|
+
}
|
|
4627
|
+
}, DRIVER_KIND_DISPLAY = {
|
|
4628
|
+
person: { title: "Person", description: "A human fired this action." },
|
|
4629
|
+
agent: { title: "Agent", description: "An AI agent fired this action." },
|
|
4630
|
+
service: { title: "Service", description: "An external system or Function fired this action." },
|
|
4631
|
+
engine: {
|
|
4632
|
+
title: "Engine",
|
|
4633
|
+
description: "The workflow engine itself drove this \u2014 a gate, machine step, or housekeeping."
|
|
4634
|
+
}
|
|
4589
4635
|
}, DISPLAY = {
|
|
4590
4636
|
...HISTORY_DISPLAY,
|
|
4591
4637
|
...FIELD_SLOT_DISPLAY,
|
|
@@ -4600,6 +4646,8 @@ function displayDescription(typeKey) {
|
|
|
4600
4646
|
if (typeKey)
|
|
4601
4647
|
return DISPLAY[typeKey]?.description;
|
|
4602
4648
|
}
|
|
4649
|
+
exports.DRIVER_KINDS = schema.DRIVER_KINDS;
|
|
4650
|
+
exports.TASK_KINDS = schema.TASK_KINDS;
|
|
4603
4651
|
exports.WORKFLOW_DEFINITION_TYPE = schema.WORKFLOW_DEFINITION_TYPE;
|
|
4604
4652
|
exports.isStartableDefinition = schema.isStartableDefinition;
|
|
4605
4653
|
exports.AUTHORING_DISPLAY = AUTHORING_DISPLAY;
|
|
@@ -4610,6 +4658,7 @@ exports.ConcurrentEditFieldError = ConcurrentEditFieldError;
|
|
|
4610
4658
|
exports.ConcurrentFireActionError = ConcurrentFireActionError;
|
|
4611
4659
|
exports.DEFAULT_CONTENT_PERSPECTIVE = DEFAULT_CONTENT_PERSPECTIVE;
|
|
4612
4660
|
exports.DISPLAY = DISPLAY;
|
|
4661
|
+
exports.DRIVER_KIND_DISPLAY = DRIVER_KIND_DISPLAY;
|
|
4613
4662
|
exports.EFFECTS_CONTEXT_DISPLAY = EFFECTS_CONTEXT_DISPLAY;
|
|
4614
4663
|
exports.EditFieldDeniedError = EditFieldDeniedError;
|
|
4615
4664
|
exports.FIELD_SLOT_DISPLAY = FIELD_SLOT_DISPLAY;
|
|
@@ -4621,6 +4670,7 @@ exports.MutationGuardDeniedError = MutationGuardDeniedError;
|
|
|
4621
4670
|
exports.OP_DISPLAY = OP_DISPLAY;
|
|
4622
4671
|
exports.PartialGuardDeployError = PartialGuardDeployError;
|
|
4623
4672
|
exports.RequiredFieldNotProvidedError = RequiredFieldNotProvidedError;
|
|
4673
|
+
exports.TASK_KIND_DISPLAY = TASK_KIND_DISPLAY;
|
|
4624
4674
|
exports.WORKFLOW_INSTANCE_TYPE = WORKFLOW_INSTANCE_TYPE;
|
|
4625
4675
|
exports.WorkflowStateDivergedError = WorkflowStateDivergedError;
|
|
4626
4676
|
exports.abortReason = abortReason;
|
|
@@ -4635,11 +4685,13 @@ exports.datasetResourceParts = datasetResourceParts;
|
|
|
4635
4685
|
exports.defaultLoggerFactory = defaultLoggerFactory;
|
|
4636
4686
|
exports.denyingGuards = denyingGuards;
|
|
4637
4687
|
exports.deployStageGuards = deployStageGuards;
|
|
4688
|
+
exports.deriveTaskKind = deriveTaskKind;
|
|
4638
4689
|
exports.diagnoseInputFromEvaluation = diagnoseInputFromEvaluation;
|
|
4639
4690
|
exports.diagnoseInstance = diagnoseInstance;
|
|
4640
4691
|
exports.diffEntry = diffEntry;
|
|
4641
4692
|
exports.displayDescription = displayDescription;
|
|
4642
4693
|
exports.displayTitle = displayTitle;
|
|
4694
|
+
exports.driverKind = driverKind;
|
|
4643
4695
|
exports.effectsContextMap = effectsContextMap;
|
|
4644
4696
|
exports.evaluateFromSnapshot = evaluateFromSnapshot;
|
|
4645
4697
|
exports.evaluateMutationGuard = evaluateMutationGuard;
|
|
@@ -4671,6 +4723,7 @@ exports.stripSystemFields = stripSystemFields;
|
|
|
4671
4723
|
exports.subscriptionDocument = subscriptionDocument;
|
|
4672
4724
|
exports.subscriptionDocumentsForInstance = subscriptionDocumentsForInstance;
|
|
4673
4725
|
exports.tagScopeFilter = tagScopeFilter;
|
|
4726
|
+
exports.taskKind = taskKind;
|
|
4674
4727
|
exports.validateDefinition = validateDefinition;
|
|
4675
4728
|
exports.validateTag = validateTag;
|
|
4676
4729
|
exports.verdictGuardsForInstance = verdictGuardsForInstance;
|