@sanity/workflow-engine 0.13.0 → 0.14.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/README.md +30 -0
- package/dist/_chunks-cjs/schema.cjs +715 -67
- package/dist/_chunks-cjs/schema.cjs.map +1 -1
- package/dist/_chunks-es/schema.js +716 -68
- package/dist/_chunks-es/schema.js.map +1 -1
- package/dist/define.cjs +66 -25
- package/dist/define.cjs.map +1 -1
- package/dist/define.d.cts +867 -71
- package/dist/define.d.ts +867 -71
- package/dist/define.js +67 -25
- package/dist/define.js.map +1 -1
- package/dist/index.cjs +2126 -2169
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1630 -517
- package/dist/index.d.ts +1630 -517
- package/dist/index.js +2061 -2104
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/define.cjs
CHANGED
|
@@ -48,7 +48,7 @@ function desugarWorkflow(authoring) {
|
|
|
48
48
|
(transition, k) => desugarTransition({ transition, path: [...path, "transitions", k], stageEnv, ctx })
|
|
49
49
|
), editable = desugarStageEditable({
|
|
50
50
|
overrides: stage.editable,
|
|
51
|
-
inScope:
|
|
51
|
+
inScope: editableFieldNames({ workflowFields, stageFields, activities }),
|
|
52
52
|
path: [...path, "editable"],
|
|
53
53
|
ctx
|
|
54
54
|
});
|
|
@@ -57,7 +57,7 @@ function desugarWorkflow(authoring) {
|
|
|
57
57
|
name: stage.name,
|
|
58
58
|
title: stage.title,
|
|
59
59
|
description: stage.description,
|
|
60
|
-
guards: stage.guards
|
|
60
|
+
guards: stage.guards?.map(desugarGuard)
|
|
61
61
|
}),
|
|
62
62
|
...stageFields ? { fields: stageFields } : {},
|
|
63
63
|
...activities.length > 0 ? { activities } : {},
|
|
@@ -70,7 +70,7 @@ function desugarWorkflow(authoring) {
|
|
|
70
70
|
name: authoring.name,
|
|
71
71
|
title: authoring.title,
|
|
72
72
|
description: authoring.description,
|
|
73
|
-
|
|
73
|
+
lifecycle: authoring.lifecycle,
|
|
74
74
|
initialStage: authoring.initialStage,
|
|
75
75
|
predicates: authoring.predicates,
|
|
76
76
|
roleAliases
|
|
@@ -167,7 +167,7 @@ function normalizeEditable({
|
|
|
167
167
|
if (condition === void 0) {
|
|
168
168
|
ctx.issues.push({
|
|
169
169
|
path,
|
|
170
|
-
message: "editable: [] names no roles \u2014 use `true` to open the
|
|
170
|
+
message: "editable: [] names no roles \u2014 use `true` to open the field to anyone in its scope, or list at least one role"
|
|
171
171
|
});
|
|
172
172
|
return;
|
|
173
173
|
}
|
|
@@ -175,7 +175,7 @@ function normalizeEditable({
|
|
|
175
175
|
}
|
|
176
176
|
return editable;
|
|
177
177
|
}
|
|
178
|
-
function
|
|
178
|
+
function editableFieldNames({
|
|
179
179
|
workflowFields,
|
|
180
180
|
stageFields,
|
|
181
181
|
activities
|
|
@@ -199,7 +199,7 @@ function desugarStageEditable({
|
|
|
199
199
|
if (!inScope.has(name)) {
|
|
200
200
|
ctx.issues.push({
|
|
201
201
|
path: [...path, name],
|
|
202
|
-
message: `stage editable override "${name}" does not narrow an editable
|
|
202
|
+
message: `stage editable override "${name}" does not narrow an editable field in scope \u2014 name a workflow/stage/activity field of this stage that declares \`editable\``
|
|
203
203
|
});
|
|
204
204
|
continue;
|
|
205
205
|
}
|
|
@@ -372,6 +372,21 @@ function desugarTransition({
|
|
|
372
372
|
...ops ? { ops } : {}
|
|
373
373
|
};
|
|
374
374
|
}
|
|
375
|
+
function desugarGuard(guard) {
|
|
376
|
+
const { match, metadata, ...rest } = guard, { idRefs, ...matchRest } = match;
|
|
377
|
+
return {
|
|
378
|
+
...rest,
|
|
379
|
+
match: {
|
|
380
|
+
...matchRest,
|
|
381
|
+
...idRefs !== void 0 ? { idRefs: idRefs.map(schema.printGuardRead) } : {}
|
|
382
|
+
},
|
|
383
|
+
...metadata !== void 0 ? {
|
|
384
|
+
metadata: Object.fromEntries(
|
|
385
|
+
Object.entries(metadata).map(([key, read]) => [key, schema.printGuardRead(read)])
|
|
386
|
+
)
|
|
387
|
+
} : {}
|
|
388
|
+
};
|
|
389
|
+
}
|
|
375
390
|
function desugarOps({
|
|
376
391
|
ops,
|
|
377
392
|
path,
|
|
@@ -460,23 +475,9 @@ function stripUndefined(obj) {
|
|
|
460
475
|
value !== void 0 && (out[k] = value);
|
|
461
476
|
return out;
|
|
462
477
|
}
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
"assigned",
|
|
467
|
-
"can",
|
|
468
|
-
"row",
|
|
469
|
-
"now",
|
|
470
|
-
"effects",
|
|
471
|
-
"activities",
|
|
472
|
-
"subworkflows",
|
|
473
|
-
"self",
|
|
474
|
-
"stage",
|
|
475
|
-
"parent",
|
|
476
|
-
"ancestors",
|
|
477
|
-
"allActivitiesDone",
|
|
478
|
-
"anyActivityFailed"
|
|
479
|
-
], PREDICATE_CALLER_VARS = ["actor", "assigned", "can"];
|
|
478
|
+
const PREDICATE_CALLER_VARS = schema.CONDITION_VARS.filter((v2) => v2.binding === "caller").map(
|
|
479
|
+
(v2) => v2.name
|
|
480
|
+
);
|
|
480
481
|
function knownList(ids) {
|
|
481
482
|
return [...ids].map((s) => `"${s}"`).join(", ");
|
|
482
483
|
}
|
|
@@ -678,7 +679,7 @@ function checkFieldEntryNames(def, issues) {
|
|
|
678
679
|
});
|
|
679
680
|
}
|
|
680
681
|
function checkPredicates(def, issues) {
|
|
681
|
-
const reserved = new Set(RESERVED_CONDITION_VARS), names = Object.keys(def.predicates ?? {});
|
|
682
|
+
const reserved = new Set(schema.RESERVED_CONDITION_VARS), names = Object.keys(def.predicates ?? {});
|
|
682
683
|
for (const name of names)
|
|
683
684
|
reserved.has(name) && issues.push({
|
|
684
685
|
path: ["predicates", name],
|
|
@@ -727,12 +728,30 @@ function nonActionFilterConditionSites(def) {
|
|
|
727
728
|
path: ["stages", i, "transitions", k, "effects"],
|
|
728
729
|
label: `transition "${t.name}"`,
|
|
729
730
|
sites
|
|
731
|
+
}), collectOpWhereSites({
|
|
732
|
+
ops: t.ops,
|
|
733
|
+
path: ["stages", i, "transitions", k, "ops"],
|
|
734
|
+
label: `transition "${t.name}"`,
|
|
735
|
+
sites
|
|
730
736
|
});
|
|
731
737
|
for (const [j, activity] of (stage.activities ?? []).entries())
|
|
732
738
|
collectActivityConditionSites({ activity, path: ["stages", i, "activities", j], sites });
|
|
733
739
|
}
|
|
734
740
|
return sites;
|
|
735
741
|
}
|
|
742
|
+
function collectOpWhereSites({
|
|
743
|
+
ops,
|
|
744
|
+
path,
|
|
745
|
+
label,
|
|
746
|
+
sites
|
|
747
|
+
}) {
|
|
748
|
+
for (const [o, op] of (ops ?? []).entries())
|
|
749
|
+
op.where !== void 0 && sites.push({
|
|
750
|
+
groq: op.where,
|
|
751
|
+
path: [...path, o, "where"],
|
|
752
|
+
label: `${label} ${op.type} where`
|
|
753
|
+
});
|
|
754
|
+
}
|
|
736
755
|
function collectActivityConditionSites({
|
|
737
756
|
activity,
|
|
738
757
|
path,
|
|
@@ -747,6 +766,11 @@ function collectActivityConditionSites({
|
|
|
747
766
|
path: [...path, "effects"],
|
|
748
767
|
label: `activity "${activity.name}"`,
|
|
749
768
|
sites
|
|
769
|
+
}), collectOpWhereSites({
|
|
770
|
+
ops: activity.ops,
|
|
771
|
+
path: [...path, "ops"],
|
|
772
|
+
label: `activity "${activity.name}"`,
|
|
773
|
+
sites
|
|
750
774
|
});
|
|
751
775
|
for (const [a, action] of (activity.actions ?? []).entries())
|
|
752
776
|
collectBindingSites({
|
|
@@ -754,6 +778,11 @@ function collectActivityConditionSites({
|
|
|
754
778
|
path: [...path, "actions", a, "effects"],
|
|
755
779
|
label: `action "${action.name}"`,
|
|
756
780
|
sites
|
|
781
|
+
}), collectOpWhereSites({
|
|
782
|
+
ops: action.ops,
|
|
783
|
+
path: [...path, "actions", a, "ops"],
|
|
784
|
+
label: `action "${action.name}"`,
|
|
785
|
+
sites
|
|
757
786
|
});
|
|
758
787
|
collectSubworkflowSites({ activity, path, sites });
|
|
759
788
|
}
|
|
@@ -851,6 +880,9 @@ function defineWorkflow(definition) {
|
|
|
851
880
|
if (issues.length > 0) throw new Error(schema.formatValidationError(label, issues));
|
|
852
881
|
return stored;
|
|
853
882
|
}
|
|
883
|
+
function defineWorkflowConfig(config) {
|
|
884
|
+
return parseOrThrow({ schema: schema.WorkflowConfigSchema, input: config, label: "defineWorkflowConfig" });
|
|
885
|
+
}
|
|
854
886
|
function defineStage(stage) {
|
|
855
887
|
return parseOrThrow({
|
|
856
888
|
schema: schema.AuthoringStageSchema,
|
|
@@ -890,7 +922,11 @@ function defineOp(op) {
|
|
|
890
922
|
return parseOrThrow({ schema: schema.AuthoringOpSchema, input: op, label: "defineOp" });
|
|
891
923
|
}
|
|
892
924
|
function defineGuard(guard) {
|
|
893
|
-
return parseOrThrow({
|
|
925
|
+
return parseOrThrow({
|
|
926
|
+
schema: schema.AuthoringGuardSchema,
|
|
927
|
+
input: guard,
|
|
928
|
+
label: labelFor("defineGuard", guard)
|
|
929
|
+
});
|
|
894
930
|
}
|
|
895
931
|
function defineEffect(effect) {
|
|
896
932
|
return parseOrThrow({
|
|
@@ -924,6 +960,10 @@ function labelFor(fn, value) {
|
|
|
924
960
|
}
|
|
925
961
|
return fn;
|
|
926
962
|
}
|
|
963
|
+
exports.CONDITION_VARS = schema.CONDITION_VARS;
|
|
964
|
+
exports.FILTER_SCOPE_VARS = schema.FILTER_SCOPE_VARS;
|
|
965
|
+
exports.GUARD_PREDICATE_VARS = schema.GUARD_PREDICATE_VARS;
|
|
966
|
+
exports.RESERVED_CONDITION_VARS = schema.RESERVED_CONDITION_VARS;
|
|
927
967
|
exports.defineAction = defineAction;
|
|
928
968
|
exports.defineActivity = defineActivity;
|
|
929
969
|
exports.defineEffect = defineEffect;
|
|
@@ -934,5 +974,6 @@ exports.defineOp = defineOp;
|
|
|
934
974
|
exports.defineStage = defineStage;
|
|
935
975
|
exports.defineTransition = defineTransition;
|
|
936
976
|
exports.defineWorkflow = defineWorkflow;
|
|
977
|
+
exports.defineWorkflowConfig = defineWorkflowConfig;
|
|
937
978
|
exports.groq = groq;
|
|
938
979
|
//# sourceMappingURL=define.cjs.map
|
package/dist/define.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define.cjs","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 * defineActivity({ name: \"legal\", filter: regulated([\"finance\", \"health\"]), … })\n * ```\n */\nexport function groq(strings: TemplateStringsArray, ...values: unknown[]): string {\n // oxlint-disable-next-line max-params -- reduce callback shape is dictated by Array.prototype.reduce\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 * (activity → stage → workflow), like variable lookup — so every stored op\n * TARGET carries an explicit `scope` the runtime never re-resolves.\n * `fieldRead` VALUES (in a `ValueExpr` op payload or a `FieldSource` seed)\n * are different: their `scope` stays optional in the stored form, and an\n * omitted scope resolves lexically at read time.\n */\n\nimport {andConditions} from '../core/conditions.ts'\nimport {expandRequiredRoles, normalizeRoleAliases} 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 AuthoringActivity,\n AuthoringTransition,\n AuthoringWorkflow,\n Editable,\n FieldShape,\n IssuePath,\n ManualTarget,\n Op,\n RoleAliases,\n FieldEntry,\n StoredFieldRef,\n Activity,\n Transition,\n TransitionOp,\n ValidationIssue,\n ValueExpr,\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. An activity's\n * ops see activity → stage → workflow; a transition's ops see stage → workflow\n * (the stage's activities are tearing down when a transition fires).\n */\ninterface LexicalEnv {\n layers: readonly {scope: 'workflow' | 'stage' | 'activity'; 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 /**\n * The definition's `roleAliases`, normalised to the stored shape (its\n * universal key is lake-safe — see {@link normalizeRoleAliases}) and baked\n * into every `roles` gate it desugars.\n */\n roleAliases: RoleAliases | undefined\n}\n\nexport function desugarWorkflow(authoring: AuthoringWorkflow): DesugarResult {\n const issues: ValidationIssue[] = []\n checkReservedRoleAliasKeys(authoring.roleAliases, issues)\n const roleAliases = normalizeRoleAliases(authoring.roleAliases)\n const ctx: Ctx = {\n issues,\n claimFields: new Map(),\n claimedFields: new Set(),\n roleAliases,\n }\n\n const workflowFields = desugarFieldEntries({entries: authoring.fields, path: ['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({entries: stage.fields, path: [...path, 'fields'], ctx})\n const stageEnv: LexicalEnv = {\n layers: [\n {scope: 'stage', entries: layerOf(stageFields)},\n {scope: 'workflow', entries: workflowLayer},\n ],\n }\n const activities = (stage.activities ?? []).map((activity, j) =>\n desugarActivity({activity, path: [...path, 'activities', j], stageEnv, ctx}),\n )\n const transitions = (stage.transitions ?? []).map((transition, k) =>\n desugarTransition({transition, path: [...path, 'transitions', k], stageEnv, ctx}),\n )\n const editable = desugarStageEditable({\n overrides: stage.editable,\n inScope: editableSlotNames({workflowFields, stageFields, activities}),\n path: [...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 ...(activities.length > 0 ? {activities} : {}),\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 title: authoring.title,\n description: authoring.description,\n role: authoring.role,\n initialStage: authoring.initialStage,\n predicates: authoring.predicates,\n roleAliases,\n }),\n ...(workflowFields ? {fields: workflowFields} : {}),\n stages,\n } as WorkflowDefinition\n\n return {definition, issues: ctx.issues}\n}\n\n/**\n * Reject an authored alias key in the engine's reserved `$` namespace. The\n * universal fulfiller is authored as `\"*\"` and rewritten to a `$`-prefixed\n * stored key ({@link normalizeRoleAliases}); a `$`-prefixed authored key would\n * collide with that stored spelling and silently read as a universal fulfiller,\n * so fail loud at define time instead.\n */\nfunction checkReservedRoleAliasKeys(\n aliases: RoleAliases | undefined,\n issues: ValidationIssue[],\n): void {\n for (const key of Object.keys(aliases ?? {})) {\n if (!key.startsWith('$')) continue\n issues.push({\n path: ['roleAliases', key],\n message:\n `role alias key \"${key}\" uses the reserved \"$\" prefix — that namespace is the ` +\n `engine's stored spelling for the universal fulfiller. Use \"*\" to mean \"fulfills ` +\n `any gate\", or rename the role.`,\n })\n }\n}\n\n// Field entries — the `claim` sugar expands to an `actor` working-memory slot\n// (no `initialValue`; the claim action's op fills it); `todoList` / `notes`\n// expand to an `array` kind with a fixed `of`; the `editable` grammar's\n// `role[]` convenience normalises to a membership predicate. Every expansion is\n// in-bounds: it only rewrites the entry it is declared on.\n\n/** The `of` a `todoList` desugars to: ad-hoc work rows with optional owner/due. */\nconst TODOLIST_OF: FieldShape[] = [\n {type: 'string', name: 'label', title: 'Label'},\n {type: 'string', name: 'status', title: 'Status'},\n {type: 'assignee', name: 'assignee', title: 'Assignee'},\n {type: 'date', name: 'dueDate', title: 'Due date'},\n]\n\n// The `of` a `notes` desugars to: an audit/comment row stamped with who + when.\n// `actor`/`at` match the `audit` op's default stamp names ({@link AUDIT_STAMPS}),\n// so an `audit`-appended row lands in the declared shape rather than beside it.\nconst NOTES_OF: FieldShape[] = [\n {type: 'text', name: 'body', title: 'Body'},\n {type: 'actor', name: 'actor', title: 'Actor'},\n {type: 'datetime', name: 'at', title: 'At'},\n]\n\nfunction desugarFieldEntries({\n entries,\n path,\n ctx,\n}: {\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) => desugarFieldEntry({entry, path: [...path, i], ctx}))\n}\n\nfunction desugarFieldEntry({\n entry,\n path,\n ctx,\n}: {\n entry: AuthoringFieldEntry\n path: IssuePath\n ctx: Ctx\n}): FieldEntry {\n if (entry.type === 'claim') return desugarClaimField({entry, path, ctx})\n if (entry.type === 'todoList' || entry.type === 'notes')\n return desugarListField({entry, path, ctx})\n const editable = normalizeEditable({editable: entry.editable, path: [...path, '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 initialValue: entry.initialValue,\n editable,\n fields: entry.fields,\n of: entry.of,\n }),\n } as FieldEntry\n}\n\nfunction desugarClaimField({\n entry,\n path,\n ctx,\n}: {\n entry: Extract<AuthoringFieldEntry, {type: 'claim'}>\n path: IssuePath\n ctx: Ctx\n}): FieldEntry {\n const desugared = {\n ...stripUndefined({name: entry.name, title: entry.title, description: entry.description}),\n type: 'actor',\n } as FieldEntry\n ctx.claimFields.set(desugared, {name: entry.name, path})\n return desugared\n}\n\nfunction desugarListField({\n entry,\n path,\n ctx,\n}: {\n entry: Extract<AuthoringFieldEntry, {type: 'todoList' | 'notes'}>\n path: IssuePath\n ctx: Ctx\n}): FieldEntry {\n const editable = normalizeEditable({editable: entry.editable, path: [...path, 'editable'], ctx})\n return {\n ...stripUndefined({\n name: entry.name,\n title: entry.title,\n description: entry.description,\n required: entry.required,\n initialValue: entry.initialValue,\n editable,\n }),\n type: 'array',\n of: entry.type === 'todoList' ? TODOLIST_OF : NOTES_OF,\n } as FieldEntry\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,\n path,\n ctx,\n}: {\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 activities. */\nfunction editableSlotNames({\n workflowFields,\n stageFields,\n activities,\n}: {\n workflowFields: readonly FieldEntry[] | undefined\n stageFields: readonly FieldEntry[] | undefined\n activities: readonly Activity[]\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 activity of activities) collect(activity.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,\n inScope,\n path,\n ctx,\n}: {\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/activity slot of this stage that declares `editable`',\n })\n continue\n }\n const normalized = normalizeEditable({editable: value, path: [...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// Activities — activation defaults to `manual` (an activity never activates silently;\n// \"auto\" is the explicit opt-in), ops resolve in the activity's lexical env, and\n// each action expands within itself.\n\nfunction desugarActivity({\n activity,\n path,\n stageEnv,\n ctx,\n}: {\n activity: AuthoringActivity\n path: IssuePath\n stageEnv: LexicalEnv\n ctx: Ctx\n}): Activity {\n const activityFields = desugarFieldEntries({\n entries: activity.fields,\n path: [...path, 'fields'],\n ctx,\n })\n const env: LexicalEnv = {\n layers: [{scope: 'activity', entries: layerOf(activityFields)}, ...stageEnv.layers],\n }\n const ops = desugarOps({\n ops: activity.ops,\n path: [...path, 'ops'],\n env,\n firingActivity: activity.name,\n ctx,\n })\n const actions = (activity.actions ?? []).map((action, a) =>\n desugarAction({action, path: [...path, 'actions', a], env, activityName: activity.name, ctx}),\n )\n const target = desugarTarget({target: activity.target, env, path: [...path, 'target'], ctx})\n return {\n ...stripUndefined({\n name: activity.name,\n title: activity.title,\n description: activity.description,\n kind: activity.kind,\n filter: activity.filter,\n requirements: activity.requirements,\n completeWhen: activity.completeWhen,\n failWhen: activity.failWhen,\n effects: activity.effects,\n subworkflows: activity.subworkflows,\n }),\n activation: activity.activation ?? 'manual',\n ...(target ? {target} : {}),\n ...(activityFields ? {fields: activityFields} : {}),\n ...(ops ? {ops} : {}),\n ...(actions.length > 0 ? {actions} : {}),\n } as Activity\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 activity'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,\n env,\n path,\n ctx,\n}: {\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: [...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 activity 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,\n path,\n env,\n activityName,\n ctx,\n}: {\n action: AuthoringAction\n path: IssuePath\n env: LexicalEnv\n activityName: 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 =\n desugarOps({ops: action.ops, path: [...path, 'ops'], env, firingActivity: activityName, ctx}) ??\n []\n if (action.status !== undefined) {\n // Appended AFTER the authored ops — the expansion has a defined position.\n ops.push({type: 'status.set', activity: activityName, 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,\n path,\n env,\n ctx,\n}: {\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: [...path, 'field'], ctx})\n if (resolved) {\n const entry = entryAt(env, resolved)\n if (entry && entry.type !== '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 \"actor\" field declaration)`,\n })\n }\n checkShadowedClaimTarget({\n actionName: action.name,\n field: ref.field,\n resolved,\n env,\n path: [...path, 'field'],\n ctx,\n })\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,\n field,\n resolved,\n env,\n path,\n ctx,\n}: {\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 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 activity layer: the stage's activities\n// are tearing down when a transition fires.\n\nfunction desugarTransition({\n transition,\n path,\n stageEnv,\n ctx,\n}: {\n transition: AuthoringTransition\n path: IssuePath\n stageEnv: LexicalEnv\n ctx: Ctx\n}): Transition {\n const ops = desugarOps({\n ops: transition.ops,\n path: [...path, 'ops'],\n env: stageEnv,\n firingActivity: undefined,\n ctx,\n })\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 ?? '$allActivitiesDone',\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-activity default on\n// `status.set`.\n\nfunction desugarOps({\n ops,\n path,\n env,\n firingActivity,\n ctx,\n}: {\n ops: readonly AuthoringOp[] | undefined\n path: IssuePath\n env: LexicalEnv\n firingActivity: string | undefined\n ctx: Ctx\n}): Op[] | undefined {\n if (!ops) return undefined\n return ops.map((op, i) => desugarOp({op, path: [...path, i], env, firingActivity, ctx}))\n}\n\nfunction desugarOp({\n op,\n path,\n env,\n firingActivity,\n ctx,\n}: {\n op: AuthoringOp\n path: IssuePath\n env: LexicalEnv\n firingActivity: string | undefined\n ctx: Ctx\n}): Op {\n if (op.type === 'status.set') {\n const activity = op.activity ?? firingActivity\n if (activity === undefined) {\n ctx.issues.push({\n path: [...path, 'activity'],\n message: 'status.set outside an action must name its target activity',\n })\n }\n return {type: 'status.set', activity: activity ?? '', status: op.status}\n }\n if (op.type === 'audit') return desugarAuditOp({op, path, env, ctx})\n const target =\n resolveRef({ref: op.target, env, path: [...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,\n path,\n env,\n ctx,\n}: {\n op: Extract<AuthoringOp, {type: 'audit'}>\n path: IssuePath\n env: LexicalEnv\n ctx: Ctx\n}): Op {\n const target =\n resolveRef({ref: op.target, env, path: [...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, ValueExpr> = {...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,\n env,\n path,\n ctx,\n}: {\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 {ActivityKind} from '../types/enums.ts'\nimport type {\n Effect,\n IssuePath,\n Op,\n FieldEntry,\n Activity,\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 'activities',\n 'subworkflows',\n 'self',\n 'stage',\n 'parent',\n 'ancestors',\n 'allActivitiesDone',\n 'anyActivityFailed',\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,\n what,\n issues,\n}: {\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 names: def.stages.map((stage, i) => ({name: stage.name, path: ['stages', i, 'name']})),\n what: 'stage name',\n issues,\n })\n for (const [i, stage] of def.stages.entries()) {\n const activityNames = checkDuplicates({\n names: (stage.activities ?? []).map((activity, j) => ({\n name: activity.name,\n path: ['stages', i, 'activities', j, 'name'],\n })),\n what: `activity name in stage \"${stage.name}\"`,\n issues,\n })\n checkDuplicates({\n names: (stage.transitions ?? []).map((t, k) => ({\n name: t.name,\n path: ['stages', i, 'transitions', k, 'name'],\n })),\n what: `transition name in stage \"${stage.name}\"`,\n issues,\n })\n checkActivities({def, i, activityNames, issues})\n }\n return stageNames\n}\n\nfunction checkActivities({\n def,\n i,\n activityNames,\n issues,\n}: {\n def: WorkflowDefinition\n i: number\n activityNames: Set<string>\n issues: ValidationIssue[]\n}): void {\n const stage = def.stages[i]!\n for (const [j, activity] of (stage.activities ?? []).entries()) {\n const path: IssuePath = ['stages', i, 'activities', j]\n checkDuplicates({\n names: (activity.actions ?? []).map((action, a) => ({\n name: action.name,\n path: [...path, 'actions', a, 'name'],\n })),\n what: `action name in activity \"${activity.name}\"`,\n issues,\n })\n checkStatusSetTargets({activity, activityNames, path, issues})\n }\n}\n\n/**\n * A `status.set` may re-activate a SIBLING activity — the name must exist in\n * the stage. Both op sites can carry one: action ops and the activity'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 activity,\n activityNames,\n path,\n issues,\n}: {\n activity: Activity\n activityNames: Set<string>\n path: IssuePath\n issues: ValidationIssue[]\n}): void {\n checkStatusSetOps({ops: activity.ops, activityNames, path: [...path, 'ops'], issues})\n for (const [a, action] of (activity.actions ?? []).entries()) {\n checkStatusSetOps({\n ops: action.ops,\n activityNames,\n path: [...path, 'actions', a, 'ops'],\n issues,\n })\n }\n}\n\nfunction checkStatusSetOps({\n ops,\n activityNames,\n path,\n issues,\n}: {\n ops: readonly Op[] | undefined\n activityNames: Set<string>\n path: IssuePath\n issues: ValidationIssue[]\n}): void {\n for (const [o, op] of (ops ?? []).entries()) {\n if (op.type !== 'status.set' || activityNames.has(op.activity)) continue\n issues.push({\n path: [...path, o, 'activity'],\n message:\n `status.set targets activity \"${op.activity}\" which is not declared in this stage. ` +\n `Known activities: ${knownList(activityNames)}`,\n })\n }\n}\n\nfunction checkInitialStage({\n def,\n stageNames,\n issues,\n}: {\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,\n stageNames,\n issues,\n}: {\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, activity] of (stage.activities ?? []).entries()) {\n collectEffects({\n effects: activity.effects,\n path: ['stages', i, 'activities', j, 'effects'],\n sites,\n })\n for (const [a, action] of (activity.actions ?? []).entries()) {\n collectEffects({\n effects: action.effects,\n path: ['stages', i, 'activities', j, 'actions', a, 'effects'],\n sites,\n })\n }\n }\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n collectEffects({effects: t.effects, path: ['stages', i, 'transitions', k, 'effects'], sites})\n }\n }\n checkDuplicates({\n names: sites,\n what: 'effect name (registry key — unique per definition)',\n issues,\n })\n}\n\nfunction collectEffects({\n effects,\n path,\n sites,\n}: {\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 names: sites,\n what: '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' | 'activity'\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, activity] of (stage.activities ?? []).entries()) {\n scopes.push({\n entries: activity.fields,\n scope: 'activity',\n path: ['stages', i, 'activities', j, 'fields'],\n label: `activity \"${activity.name}\" fields`,\n })\n }\n }\n return scopes\n}\n\n/**\n * `required` is the start/spawn fail-fast for a load-bearing `input` slot: the\n * caller MUST fill it or {@link RequiredFieldNotProvidedError} fires. It only\n * makes sense on a WORKFLOW-scope `input` entry — that is the one scope a caller\n * seeds (via `initialFields` at start, or the parent's `subworkflows.with` at\n * spawn). Stage/activity fields are engine-resolved at entry/activation with no\n * caller seed, and a non-`input` 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 \\`input\\` entries — only those are caller-supplied at start/spawn`,\n })\n } else if (entry.initialValue?.type !== 'input') {\n const seed = entry.initialValue?.type ?? 'working memory (no initialValue)'\n issues.push({\n path: [...path, n, 'required'],\n message:\n `field entry \"${entry.name}\" has initialValue \"${seed}\" — ` +\n `\\`required\\` applies only to \\`input\\`-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 names: (entries ?? []).map((entry, n) => ({name: entry.name, path: [...path, n, 'name']})),\n what: `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,\n groq,\n names,\n issues,\n}: {\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 effects: t.effects,\n path: ['stages', i, 'transitions', k, 'effects'],\n label: `transition \"${t.name}\"`,\n sites,\n })\n }\n for (const [j, activity] of (stage.activities ?? []).entries()) {\n collectActivityConditionSites({activity, path: ['stages', i, 'activities', j], sites})\n }\n }\n return sites\n}\n\nfunction collectActivityConditionSites({\n activity,\n path,\n sites,\n}: {\n activity: Activity\n path: IssuePath\n sites: ConditionSite[]\n}): void {\n for (const field of ['filter', 'completeWhen', 'failWhen'] as const) {\n const groq = activity[field]\n if (groq !== undefined) {\n sites.push({groq, path: [...path, field], label: `activity \"${activity.name}\".${field}`})\n }\n }\n collectBindingSites({\n effects: activity.effects,\n path: [...path, 'effects'],\n label: `activity \"${activity.name}\"`,\n sites,\n })\n for (const [a, action] of (activity.actions ?? []).entries()) {\n collectBindingSites({\n effects: action.effects,\n path: [...path, 'actions', a, 'effects'],\n label: `action \"${action.name}\"`,\n sites,\n })\n }\n collectSubworkflowSites({activity, path, sites})\n}\n\nfunction collectSubworkflowSites({\n activity,\n path,\n sites,\n}: {\n activity: Activity\n path: IssuePath\n sites: ConditionSite[]\n}): void {\n const sub = activity.subworkflows\n if (sub === undefined) return\n const subPath = [...path, 'subworkflows']\n sites.push({\n groq: sub.forEach,\n path: [...subPath, 'forEach'],\n label: `activity \"${activity.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: `activity \"${activity.name}\".subworkflows.${group} \"${key}\"`,\n })\n }\n }\n}\n\nfunction collectBindingSites({\n effects,\n path,\n label,\n sites,\n}: {\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 ActivityShape {\n hasActions: boolean\n hasEffects: boolean\n hasCompleteWhen: boolean\n hasSubworkflows: boolean\n}\n\nfunction activityShape(activity: Activity): ActivityShape {\n return {\n hasActions: (activity.actions ?? []).length > 0,\n hasEffects: (activity.effects ?? []).length > 0,\n hasCompleteWhen: activity.completeWhen !== undefined,\n hasSubworkflows: activity.subworkflows !== undefined,\n }\n}\n\n/**\n * Per-kind shape contract: each rule returns one fragment per way the declared\n * kind contradicts the activity's actual shape, so an activity 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 activity that\n * silently auto-resolves as a machine step. Keyed exhaustively by\n * {@link ActivityKind}, 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<ActivityKind, (s: ActivityShape) => 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 activity'\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 activity's EXPLICIT {@link Activity.kind} against its shape, and that a\n * `target` only rides a `manual` activity. 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 checkActivityKinds(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const [i, stage] of def.stages.entries()) {\n for (const [j, activity] of (stage.activities ?? []).entries()) {\n const path: IssuePath = ['stages', i, 'activities', j]\n if (activity.target !== undefined && activity.kind !== 'manual') {\n issues.push({\n path: [...path, 'target'],\n message: `activity \"${activity.name}\" has a \\`target\\` but is not \\`kind: \"manual\"\\` — a target is the deep-link for off-system manual work`,\n })\n }\n if (activity.kind === undefined) continue\n for (const fault of KIND_SHAPE_RULES[activity.kind](activityShape(activity))) {\n issues.push({\n path: [...path, 'kind'],\n message: `activity \"${activity.name}\" declares kind \"${activity.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 checkActivityKinds(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 AuthoringActivitySchema,\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 AuthoringActivity,\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.allActivitiesDone: predicate \"allActivitiesDone\" shadows the built-in $allActivitiesDone — 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({schema: AuthoringWorkflowSchema, input: 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({\n schema: AuthoringStageSchema,\n input: stage,\n label: labelFor('defineStage', stage),\n })\n}\n\nexport function defineActivity(activity: AuthoringActivity): AuthoringActivity {\n return parseOrThrow({\n schema: AuthoringActivitySchema,\n input: activity,\n label: labelFor('defineActivity', activity),\n })\n}\n\nexport function defineAction(action: AuthoringAction): AuthoringAction {\n return parseOrThrow({\n schema: AuthoringActionSchema,\n input: action,\n label: labelFor('defineAction', action),\n })\n}\n\nexport function defineTransition(transition: AuthoringTransition): AuthoringTransition {\n return parseOrThrow({\n schema: AuthoringTransitionSchema,\n input: transition,\n label: transitionLabel(transition),\n })\n}\n\nexport function defineField(entry: AuthoringFieldEntry): AuthoringFieldEntry {\n return parseOrThrow({\n schema: AuthoringFieldEntrySchema,\n input: entry,\n label: labelFor('defineField', entry),\n })\n}\n\nexport function defineOp(op: AuthoringOp): AuthoringOp {\n return parseOrThrow({schema: AuthoringOpSchema, input: op, label: 'defineOp'})\n}\n\nexport function defineGuard(guard: Guard): Guard {\n return parseOrThrow({schema: GuardSchema, input: guard, label: 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({\n schema: EffectSchema,\n input: effect,\n label: labelFor('defineEffect', effect),\n })\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>({\n schema,\n input,\n label,\n}: {\n schema: v.GenericSchema<unknown, T>\n input: T\n label: string\n}): 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":["normalizeRoleAliases","andConditions","expandRequiredRoles","groq","GROQ_IDENTIFIER","AuthoringWorkflowSchema","formatValidationError","AuthoringStageSchema","AuthoringActivitySchema","AuthoringActionSchema","AuthoringTransitionSchema","AuthoringFieldEntrySchema","AuthoringOpSchema","GuardSchema","EffectSchema","schema","v","issuesFromValibot"],"mappings":";;;;;;;;;;;;;;;;;;;AAeO,SAAS,KAAK,YAAkC,QAA2B;AAEhF,SAAO,QAAQ,OAAO,C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uB,YAAgD;AACrF,MAAI,CAAC,WAAW,KAAM,OAAM,IAAI,MAAM,+BAA+B;AACrE,SAAO;AACT;AAIA,SAAS,aAAgB;AAAA,EAAA,QACvBC;AAAAA,EACA;AAAA,EACA;AACF,GAIM;AACJ,QAAM,SAASC,aAAE,UAAUD,UAAQ,KAAK;AACxC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAMT,6BAAsB,OAAOW,OAAAA,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.cjs","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 * defineActivity({ name: \"legal\", filter: regulated([\"finance\", \"health\"]), … })\n * ```\n */\nexport function groq(strings: TemplateStringsArray, ...values: unknown[]): string {\n // oxlint-disable-next-line max-params -- reduce callback shape is dictated by Array.prototype.reduce\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 * (activity → stage → workflow), like variable lookup — so every stored op\n * TARGET carries an explicit `scope` the runtime never re-resolves.\n * `fieldRead` VALUES (in a `ValueExpr` op payload or a `FieldSource` seed)\n * are different: their `scope` stays optional in the stored form, and an\n * omitted scope resolves lexically at read time.\n */\n\nimport {andConditions} from '../core/conditions.ts'\nimport {printGuardRead} from '../core/guard-reads.ts'\nimport {expandRequiredRoles, normalizeRoleAliases} 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 AuthoringGuard,\n AuthoringManualTarget,\n AuthoringOp,\n AuthoringFieldEntry,\n AuthoringFieldRef,\n AuthoringActivity,\n AuthoringTransition,\n AuthoringWorkflow,\n Editable,\n FieldShape,\n Guard,\n IssuePath,\n ManualTarget,\n Op,\n RoleAliases,\n FieldEntry,\n StoredFieldRef,\n Activity,\n Transition,\n TransitionOp,\n ValidationIssue,\n ValueExpr,\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. An activity's\n * ops see activity → stage → workflow; a transition's ops see stage → workflow\n * (the stage's activities are tearing down when a transition fires).\n */\ninterface LexicalEnv {\n layers: readonly {scope: 'workflow' | 'stage' | 'activity'; 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 /**\n * The definition's `roleAliases`, normalised to the stored shape (its\n * universal key is lake-safe — see {@link normalizeRoleAliases}) and baked\n * into every `roles` gate it desugars.\n */\n roleAliases: RoleAliases | undefined\n}\n\nexport function desugarWorkflow(authoring: AuthoringWorkflow): DesugarResult {\n const issues: ValidationIssue[] = []\n checkReservedRoleAliasKeys(authoring.roleAliases, issues)\n const roleAliases = normalizeRoleAliases(authoring.roleAliases)\n const ctx: Ctx = {\n issues,\n claimFields: new Map(),\n claimedFields: new Set(),\n roleAliases,\n }\n\n const workflowFields = desugarFieldEntries({entries: authoring.fields, path: ['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({entries: stage.fields, path: [...path, 'fields'], ctx})\n const stageEnv: LexicalEnv = {\n layers: [\n {scope: 'stage', entries: layerOf(stageFields)},\n {scope: 'workflow', entries: workflowLayer},\n ],\n }\n const activities = (stage.activities ?? []).map((activity, j) =>\n desugarActivity({activity, path: [...path, 'activities', j], stageEnv, ctx}),\n )\n const transitions = (stage.transitions ?? []).map((transition, k) =>\n desugarTransition({transition, path: [...path, 'transitions', k], stageEnv, ctx}),\n )\n const editable = desugarStageEditable({\n overrides: stage.editable,\n inScope: editableFieldNames({workflowFields, stageFields, activities}),\n path: [...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?.map(desugarGuard),\n }),\n ...(stageFields ? {fields: stageFields} : {}),\n ...(activities.length > 0 ? {activities} : {}),\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 title: authoring.title,\n description: authoring.description,\n lifecycle: authoring.lifecycle,\n initialStage: authoring.initialStage,\n predicates: authoring.predicates,\n roleAliases,\n }),\n ...(workflowFields ? {fields: workflowFields} : {}),\n stages,\n } as WorkflowDefinition\n\n return {definition, issues: ctx.issues}\n}\n\n/**\n * Reject an authored alias key in the engine's reserved `$` namespace. The\n * universal fulfiller is authored as `\"*\"` and rewritten to a `$`-prefixed\n * stored key ({@link normalizeRoleAliases}); a `$`-prefixed authored key would\n * collide with that stored spelling and silently read as a universal fulfiller,\n * so fail loud at define time instead.\n */\nfunction checkReservedRoleAliasKeys(\n aliases: RoleAliases | undefined,\n issues: ValidationIssue[],\n): void {\n for (const key of Object.keys(aliases ?? {})) {\n if (!key.startsWith('$')) continue\n issues.push({\n path: ['roleAliases', key],\n message:\n `role alias key \"${key}\" uses the reserved \"$\" prefix — that namespace is the ` +\n `engine's stored spelling for the universal fulfiller. Use \"*\" to mean \"fulfills ` +\n `any gate\", or rename the role.`,\n })\n }\n}\n\n// Field entries — the `claim` sugar expands to an `actor` working-memory field\n// (no `initialValue`; the claim action's op fills it); `todoList` / `notes`\n// expand to an `array` kind with a fixed `of`; the `editable` grammar's\n// `role[]` convenience normalises to a membership predicate. Every expansion is\n// in-bounds: it only rewrites the entry it is declared on.\n\n/** The `of` a `todoList` desugars to: ad-hoc work rows with optional owner/due. */\nconst TODOLIST_OF: FieldShape[] = [\n {type: 'string', name: 'label', title: 'Label'},\n {type: 'string', name: 'status', title: 'Status'},\n {type: 'assignee', name: 'assignee', title: 'Assignee'},\n {type: 'date', name: 'dueDate', title: 'Due date'},\n]\n\n// The `of` a `notes` desugars to: an audit/comment row stamped with who + when.\n// `actor`/`at` match the `audit` op's default stamp names ({@link AUDIT_STAMPS}),\n// so an `audit`-appended row lands in the declared shape rather than beside it.\nconst NOTES_OF: FieldShape[] = [\n {type: 'text', name: 'body', title: 'Body'},\n {type: 'actor', name: 'actor', title: 'Actor'},\n {type: 'datetime', name: 'at', title: 'At'},\n]\n\nfunction desugarFieldEntries({\n entries,\n path,\n ctx,\n}: {\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) => desugarFieldEntry({entry, path: [...path, i], ctx}))\n}\n\nfunction desugarFieldEntry({\n entry,\n path,\n ctx,\n}: {\n entry: AuthoringFieldEntry\n path: IssuePath\n ctx: Ctx\n}): FieldEntry {\n if (entry.type === 'claim') return desugarClaimField({entry, path, ctx})\n if (entry.type === 'todoList' || entry.type === 'notes')\n return desugarListField({entry, path, ctx})\n const editable = normalizeEditable({editable: entry.editable, path: [...path, '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 initialValue: entry.initialValue,\n editable,\n fields: entry.fields,\n of: entry.of,\n }),\n } as FieldEntry\n}\n\nfunction desugarClaimField({\n entry,\n path,\n ctx,\n}: {\n entry: Extract<AuthoringFieldEntry, {type: 'claim'}>\n path: IssuePath\n ctx: Ctx\n}): FieldEntry {\n const desugared = {\n ...stripUndefined({name: entry.name, title: entry.title, description: entry.description}),\n type: 'actor',\n } as FieldEntry\n ctx.claimFields.set(desugared, {name: entry.name, path})\n return desugared\n}\n\nfunction desugarListField({\n entry,\n path,\n ctx,\n}: {\n entry: Extract<AuthoringFieldEntry, {type: 'todoList' | 'notes'}>\n path: IssuePath\n ctx: Ctx\n}): FieldEntry {\n const editable = normalizeEditable({editable: entry.editable, path: [...path, 'editable'], ctx})\n return {\n ...stripUndefined({\n name: entry.name,\n title: entry.title,\n description: entry.description,\n required: entry.required,\n initialValue: entry.initialValue,\n editable,\n }),\n type: 'array',\n of: entry.type === 'todoList' ? TODOLIST_OF : NOTES_OF,\n } as FieldEntry\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 field.\n */\nfunction normalizeEditable({\n editable,\n path,\n ctx,\n}: {\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 field 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 fields that declare `editable` across the scopes a stage's\n * override can narrow: workflow + this stage + this stage's activities. */\nfunction editableFieldNames({\n workflowFields,\n stageFields,\n activities,\n}: {\n workflowFields: readonly FieldEntry[] | undefined\n stageFields: readonly FieldEntry[] | undefined\n activities: readonly Activity[]\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 activity of activities) collect(activity.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 field's own `editable`; each key must name a field\n * that declares `editable` somewhere in scope, since an override on a closed\n * field 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,\n inScope,\n path,\n ctx,\n}: {\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 field in scope — name a ` +\n 'workflow/stage/activity field of this stage that declares `editable`',\n })\n continue\n }\n const normalized = normalizeEditable({editable: value, path: [...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// Activities — activation defaults to `manual` (an activity never activates silently;\n// \"auto\" is the explicit opt-in), ops resolve in the activity's lexical env, and\n// each action expands within itself.\n\nfunction desugarActivity({\n activity,\n path,\n stageEnv,\n ctx,\n}: {\n activity: AuthoringActivity\n path: IssuePath\n stageEnv: LexicalEnv\n ctx: Ctx\n}): Activity {\n const activityFields = desugarFieldEntries({\n entries: activity.fields,\n path: [...path, 'fields'],\n ctx,\n })\n const env: LexicalEnv = {\n layers: [{scope: 'activity', entries: layerOf(activityFields)}, ...stageEnv.layers],\n }\n const ops = desugarOps({\n ops: activity.ops,\n path: [...path, 'ops'],\n env,\n firingActivity: activity.name,\n ctx,\n })\n const actions = (activity.actions ?? []).map((action, a) =>\n desugarAction({action, path: [...path, 'actions', a], env, activityName: activity.name, ctx}),\n )\n const target = desugarTarget({target: activity.target, env, path: [...path, 'target'], ctx})\n return {\n ...stripUndefined({\n name: activity.name,\n title: activity.title,\n description: activity.description,\n kind: activity.kind,\n filter: activity.filter,\n requirements: activity.requirements,\n completeWhen: activity.completeWhen,\n failWhen: activity.failWhen,\n effects: activity.effects,\n subworkflows: activity.subworkflows,\n }),\n activation: activity.activation ?? 'manual',\n ...(target ? {target} : {}),\n ...(activityFields ? {fields: activityFields} : {}),\n ...(ops ? {ops} : {}),\n ...(actions.length > 0 ? {actions} : {}),\n } as Activity\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 activity'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,\n env,\n path,\n ctx,\n}: {\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: [...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 activity 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,\n path,\n env,\n activityName,\n ctx,\n}: {\n action: AuthoringAction\n path: IssuePath\n env: LexicalEnv\n activityName: 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 =\n desugarOps({ops: action.ops, path: [...path, 'ops'], env, firingActivity: activityName, ctx}) ??\n []\n if (action.status !== undefined) {\n // Appended AFTER the authored ops — the expansion has a defined position.\n ops.push({type: 'status.set', activity: activityName, 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,\n path,\n env,\n ctx,\n}: {\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: [...path, 'field'], ctx})\n if (resolved) {\n const entry = entryAt(env, resolved)\n if (entry && entry.type !== '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 \"actor\" field declaration)`,\n })\n }\n checkShadowedClaimTarget({\n actionName: action.name,\n field: ref.field,\n resolved,\n env,\n path: [...path, 'field'],\n ctx,\n })\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,\n field,\n resolved,\n env,\n path,\n ctx,\n}: {\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 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 activity layer: the stage's activities\n// are tearing down when a transition fires.\n\nfunction desugarTransition({\n transition,\n path,\n stageEnv,\n ctx,\n}: {\n transition: AuthoringTransition\n path: IssuePath\n stageEnv: LexicalEnv\n ctx: Ctx\n}): Transition {\n const ops = desugarOps({\n ops: transition.ops,\n path: [...path, 'ops'],\n env: stageEnv,\n firingActivity: undefined,\n ctx,\n })\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 ?? '$allActivitiesDone',\n ...(ops ? {ops: ops as TransitionOp[]} : {}),\n } as Transition\n}\n\n// Guards — authoring reads are typed ({@link GuardRead}); the stored form\n// prints the string spelling the deploy resolver and guard refresh speak\n// ({@link printGuardRead}, co-located with the parse regexes), so hand-built\n// stored definitions and the deployed lake contract never see the typed\n// authoring form.\n\nfunction desugarGuard(guard: AuthoringGuard): Guard {\n const {match, metadata, ...rest} = guard\n const {idRefs, ...matchRest} = match\n return {\n ...rest,\n match: {\n ...matchRest,\n ...(idRefs !== undefined ? {idRefs: idRefs.map(printGuardRead)} : {}),\n },\n ...(metadata !== undefined\n ? {\n metadata: Object.fromEntries(\n Object.entries(metadata).map(([key, read]) => [key, printGuardRead(read)]),\n ),\n }\n : {}),\n }\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-activity default on\n// `status.set`.\n\nfunction desugarOps({\n ops,\n path,\n env,\n firingActivity,\n ctx,\n}: {\n ops: readonly AuthoringOp[] | undefined\n path: IssuePath\n env: LexicalEnv\n firingActivity: string | undefined\n ctx: Ctx\n}): Op[] | undefined {\n if (!ops) return undefined\n return ops.map((op, i) => desugarOp({op, path: [...path, i], env, firingActivity, ctx}))\n}\n\nfunction desugarOp({\n op,\n path,\n env,\n firingActivity,\n ctx,\n}: {\n op: AuthoringOp\n path: IssuePath\n env: LexicalEnv\n firingActivity: string | undefined\n ctx: Ctx\n}): Op {\n if (op.type === 'status.set') {\n const activity = op.activity ?? firingActivity\n if (activity === undefined) {\n ctx.issues.push({\n path: [...path, 'activity'],\n message: 'status.set outside an action must name its target activity',\n })\n }\n return {type: 'status.set', activity: activity ?? '', status: op.status}\n }\n if (op.type === 'audit') return desugarAuditOp({op, path, env, ctx})\n const target =\n resolveRef({ref: op.target, env, path: [...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,\n path,\n env,\n ctx,\n}: {\n op: Extract<AuthoringOp, {type: 'audit'}>\n path: IssuePath\n env: LexicalEnv\n ctx: Ctx\n}): Op {\n const target =\n resolveRef({ref: op.target, env, path: [...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, ValueExpr> = {...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,\n env,\n path,\n ctx,\n}: {\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 {ActivityKind} from '../types/enums.ts'\nimport {CONDITION_VARS, RESERVED_CONDITION_VARS} from './condition-scope.ts'\nimport type {\n Effect,\n IssuePath,\n Op,\n FieldEntry,\n Activity,\n ValidationIssue,\n WorkflowDefinition,\n} from './schema.ts'\nimport {GROQ_IDENTIFIER} from './schema.ts'\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 = CONDITION_VARS.filter((v) => v.binding === 'caller').map(\n (v) => v.name,\n)\n\nfunction knownList(ids: Iterable<string>): string {\n return [...ids].map((s) => `\"${s}\"`).join(', ')\n}\n\nfunction checkDuplicates({\n names,\n what,\n issues,\n}: {\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 names: def.stages.map((stage, i) => ({name: stage.name, path: ['stages', i, 'name']})),\n what: 'stage name',\n issues,\n })\n for (const [i, stage] of def.stages.entries()) {\n const activityNames = checkDuplicates({\n names: (stage.activities ?? []).map((activity, j) => ({\n name: activity.name,\n path: ['stages', i, 'activities', j, 'name'],\n })),\n what: `activity name in stage \"${stage.name}\"`,\n issues,\n })\n checkDuplicates({\n names: (stage.transitions ?? []).map((t, k) => ({\n name: t.name,\n path: ['stages', i, 'transitions', k, 'name'],\n })),\n what: `transition name in stage \"${stage.name}\"`,\n issues,\n })\n checkActivities({def, i, activityNames, issues})\n }\n return stageNames\n}\n\nfunction checkActivities({\n def,\n i,\n activityNames,\n issues,\n}: {\n def: WorkflowDefinition\n i: number\n activityNames: Set<string>\n issues: ValidationIssue[]\n}): void {\n const stage = def.stages[i]!\n for (const [j, activity] of (stage.activities ?? []).entries()) {\n const path: IssuePath = ['stages', i, 'activities', j]\n checkDuplicates({\n names: (activity.actions ?? []).map((action, a) => ({\n name: action.name,\n path: [...path, 'actions', a, 'name'],\n })),\n what: `action name in activity \"${activity.name}\"`,\n issues,\n })\n checkStatusSetTargets({activity, activityNames, path, issues})\n }\n}\n\n/**\n * A `status.set` may re-activate a SIBLING activity — the name must exist in\n * the stage. Both op sites can carry one: action ops and the activity'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 activity,\n activityNames,\n path,\n issues,\n}: {\n activity: Activity\n activityNames: Set<string>\n path: IssuePath\n issues: ValidationIssue[]\n}): void {\n checkStatusSetOps({ops: activity.ops, activityNames, path: [...path, 'ops'], issues})\n for (const [a, action] of (activity.actions ?? []).entries()) {\n checkStatusSetOps({\n ops: action.ops,\n activityNames,\n path: [...path, 'actions', a, 'ops'],\n issues,\n })\n }\n}\n\nfunction checkStatusSetOps({\n ops,\n activityNames,\n path,\n issues,\n}: {\n ops: readonly Op[] | undefined\n activityNames: Set<string>\n path: IssuePath\n issues: ValidationIssue[]\n}): void {\n for (const [o, op] of (ops ?? []).entries()) {\n if (op.type !== 'status.set' || activityNames.has(op.activity)) continue\n issues.push({\n path: [...path, o, 'activity'],\n message:\n `status.set targets activity \"${op.activity}\" which is not declared in this stage. ` +\n `Known activities: ${knownList(activityNames)}`,\n })\n }\n}\n\nfunction checkInitialStage({\n def,\n stageNames,\n issues,\n}: {\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,\n stageNames,\n issues,\n}: {\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, activity] of (stage.activities ?? []).entries()) {\n collectEffects({\n effects: activity.effects,\n path: ['stages', i, 'activities', j, 'effects'],\n sites,\n })\n for (const [a, action] of (activity.actions ?? []).entries()) {\n collectEffects({\n effects: action.effects,\n path: ['stages', i, 'activities', j, 'actions', a, 'effects'],\n sites,\n })\n }\n }\n for (const [k, t] of (stage.transitions ?? []).entries()) {\n collectEffects({effects: t.effects, path: ['stages', i, 'transitions', k, 'effects'], sites})\n }\n }\n checkDuplicates({\n names: sites,\n what: 'effect name (registry key — unique per definition)',\n issues,\n })\n}\n\nfunction collectEffects({\n effects,\n path,\n sites,\n}: {\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 live 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 names: sites,\n what: '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' | 'activity'\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, activity] of (stage.activities ?? []).entries()) {\n scopes.push({\n entries: activity.fields,\n scope: 'activity',\n path: ['stages', i, 'activities', j, 'fields'],\n label: `activity \"${activity.name}\" fields`,\n })\n }\n }\n return scopes\n}\n\n/**\n * `required` is the start/spawn fail-fast for a load-bearing `input` field: the\n * caller MUST fill it or {@link RequiredFieldNotProvidedError} fires. It only\n * makes sense on a WORKFLOW-scope `input` entry — that is the one scope a caller\n * seeds (via `initialFields` at start, or the parent's `subworkflows.with` at\n * spawn). Stage/activity fields are engine-resolved at entry/activation with no\n * caller seed, and a non-`input` source fills itself — so `required` anywhere\n * else can never be satisfied. Reject it at deploy rather than ship a field 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 \\`input\\` entries — only those are caller-supplied at start/spawn`,\n })\n } else if (entry.initialValue?.type !== 'input') {\n const seed = entry.initialValue?.type ?? 'working memory (no initialValue)'\n issues.push({\n path: [...path, n, 'required'],\n message:\n `field entry \"${entry.name}\" has initialValue \"${seed}\" — ` +\n `\\`required\\` applies only to \\`input\\`-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 names: (entries ?? []).map((entry, n) => ({name: entry.name, path: [...path, n, 'name']})),\n what: `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,\n groq,\n names,\n issues,\n}: {\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 effects: t.effects,\n path: ['stages', i, 'transitions', k, 'effects'],\n label: `transition \"${t.name}\"`,\n sites,\n })\n collectOpWhereSites({\n ops: t.ops,\n path: ['stages', i, 'transitions', k, 'ops'],\n label: `transition \"${t.name}\"`,\n sites,\n })\n }\n for (const [j, activity] of (stage.activities ?? []).entries()) {\n collectActivityConditionSites({activity, path: ['stages', i, 'activities', j], sites})\n }\n }\n return sites\n}\n\n/** A where-op's `where` never binds `$can` — not even on an action's ops (the\n * op scope is the mutation's, not the firing filter's) — so it is a `$can`\n * rejection site wherever ops appear: activities, actions, transitions. */\nfunction collectOpWhereSites({\n ops,\n path,\n label,\n sites,\n}: {\n ops: readonly {type: string; where?: string}[] | undefined\n path: IssuePath\n label: string\n sites: ConditionSite[]\n}): void {\n for (const [o, op] of (ops ?? []).entries()) {\n if (op.where !== undefined) {\n sites.push({\n groq: op.where,\n path: [...path, o, 'where'],\n label: `${label} ${op.type} where`,\n })\n }\n }\n}\n\nfunction collectActivityConditionSites({\n activity,\n path,\n sites,\n}: {\n activity: Activity\n path: IssuePath\n sites: ConditionSite[]\n}): void {\n for (const field of ['filter', 'completeWhen', 'failWhen'] as const) {\n const groq = activity[field]\n if (groq !== undefined) {\n sites.push({groq, path: [...path, field], label: `activity \"${activity.name}\".${field}`})\n }\n }\n collectBindingSites({\n effects: activity.effects,\n path: [...path, 'effects'],\n label: `activity \"${activity.name}\"`,\n sites,\n })\n collectOpWhereSites({\n ops: activity.ops,\n path: [...path, 'ops'],\n label: `activity \"${activity.name}\"`,\n sites,\n })\n for (const [a, action] of (activity.actions ?? []).entries()) {\n collectBindingSites({\n effects: action.effects,\n path: [...path, 'actions', a, 'effects'],\n label: `action \"${action.name}\"`,\n sites,\n })\n collectOpWhereSites({\n ops: action.ops,\n path: [...path, 'actions', a, 'ops'],\n label: `action \"${action.name}\"`,\n sites,\n })\n }\n collectSubworkflowSites({activity, path, sites})\n}\n\nfunction collectSubworkflowSites({\n activity,\n path,\n sites,\n}: {\n activity: Activity\n path: IssuePath\n sites: ConditionSite[]\n}): void {\n const sub = activity.subworkflows\n if (sub === undefined) return\n const subPath = [...path, 'subworkflows']\n sites.push({\n groq: sub.forEach,\n path: [...subPath, 'forEach'],\n label: `activity \"${activity.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: `activity \"${activity.name}\".subworkflows.${group} \"${key}\"`,\n })\n }\n }\n}\n\nfunction collectBindingSites({\n effects,\n path,\n label,\n sites,\n}: {\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 ActivityShape {\n hasActions: boolean\n hasEffects: boolean\n hasCompleteWhen: boolean\n hasSubworkflows: boolean\n}\n\nfunction activityShape(activity: Activity): ActivityShape {\n return {\n hasActions: (activity.actions ?? []).length > 0,\n hasEffects: (activity.effects ?? []).length > 0,\n hasCompleteWhen: activity.completeWhen !== undefined,\n hasSubworkflows: activity.subworkflows !== undefined,\n }\n}\n\n/**\n * Per-kind shape contract: each rule returns one fragment per way the declared\n * kind contradicts the activity's actual shape, so an activity 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 activity that\n * silently auto-resolves as a machine step. Keyed exhaustively by\n * {@link ActivityKind}, 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<ActivityKind, (s: ActivityShape) => 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 activity'\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 activity's EXPLICIT {@link Activity.kind} against its shape, and that a\n * `target` only rides a `manual` activity. 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 checkActivityKinds(def: WorkflowDefinition, issues: ValidationIssue[]): void {\n for (const [i, stage] of def.stages.entries()) {\n for (const [j, activity] of (stage.activities ?? []).entries()) {\n const path: IssuePath = ['stages', i, 'activities', j]\n if (activity.target !== undefined && activity.kind !== 'manual') {\n issues.push({\n path: [...path, 'target'],\n message: `activity \"${activity.name}\" has a \\`target\\` but is not \\`kind: \"manual\"\\` — a target is the deep-link for off-system manual work`,\n })\n }\n if (activity.kind === undefined) continue\n for (const fault of KIND_SHAPE_RULES[activity.kind](activityShape(activity))) {\n issues.push({\n path: [...path, 'kind'],\n message: `activity \"${activity.name}\" declares kind \"${activity.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 checkActivityKinds(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 {WorkflowConfigSchema, type WorkflowConfig} from './config.ts'\nimport {desugarWorkflow} from './desugar.ts'\nimport {checkWorkflowInvariants} from './invariants.ts'\nimport {\n AuthoringActionSchema,\n AuthoringOpSchema,\n AuthoringStageSchema,\n AuthoringFieldEntrySchema,\n AuthoringActivitySchema,\n AuthoringTransitionSchema,\n AuthoringWorkflowSchema,\n AuthoringGuardSchema,\n EffectSchema,\n formatValidationError,\n issuesFromValibot,\n type AuthoringAction,\n type AuthoringOp,\n type AuthoringStage,\n type AuthoringFieldEntry,\n type AuthoringActivity,\n type AuthoringTransition,\n type AuthoringGuard,\n type AuthoringWorkflow,\n type Effect,\n type ValidationIssue,\n type WorkflowDefinition,\n} from './schema.ts'\n\nexport {groq} from './groq.ts'\n\nexport {\n CONDITION_VARS,\n FILTER_SCOPE_VARS,\n GUARD_PREDICATE_VARS,\n RESERVED_CONDITION_VARS,\n type ConditionVar,\n type ConditionVarBinding,\n} from './condition-scope.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.allActivitiesDone: predicate \"allActivitiesDone\" shadows the built-in $allActivitiesDone — 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({schema: AuthoringWorkflowSchema, input: 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/**\n * Validate a deploy config — the binding of each definition's logical resource\n * handles to physical resources, per environment (tag). Throws a formatted,\n * path-prefixed error if the shape is invalid. The CLI hands the selected\n * deployment's {@link resourceAliasesToMap} map to {@link deployDefinitions}.\n */\nexport function defineWorkflowConfig(config: WorkflowConfig): WorkflowConfig {\n return parseOrThrow({schema: WorkflowConfigSchema, input: config, label: 'defineWorkflowConfig'})\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({\n schema: AuthoringStageSchema,\n input: stage,\n label: labelFor('defineStage', stage),\n })\n}\n\nexport function defineActivity(activity: AuthoringActivity): AuthoringActivity {\n return parseOrThrow({\n schema: AuthoringActivitySchema,\n input: activity,\n label: labelFor('defineActivity', activity),\n })\n}\n\nexport function defineAction(action: AuthoringAction): AuthoringAction {\n return parseOrThrow({\n schema: AuthoringActionSchema,\n input: action,\n label: labelFor('defineAction', action),\n })\n}\n\nexport function defineTransition(transition: AuthoringTransition): AuthoringTransition {\n return parseOrThrow({\n schema: AuthoringTransitionSchema,\n input: transition,\n label: transitionLabel(transition),\n })\n}\n\nexport function defineField(entry: AuthoringFieldEntry): AuthoringFieldEntry {\n return parseOrThrow({\n schema: AuthoringFieldEntrySchema,\n input: entry,\n label: labelFor('defineField', entry),\n })\n}\n\nexport function defineOp(op: AuthoringOp): AuthoringOp {\n return parseOrThrow({schema: AuthoringOpSchema, input: op, label: 'defineOp'})\n}\n\nexport function defineGuard(guard: AuthoringGuard): AuthoringGuard {\n return parseOrThrow({\n schema: AuthoringGuardSchema,\n input: guard,\n label: labelFor('defineGuard', guard),\n })\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({\n schema: EffectSchema,\n input: effect,\n label: labelFor('defineEffect', effect),\n })\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>({\n schema,\n input,\n label,\n}: {\n schema: v.GenericSchema<unknown, T>\n input: T\n label: string\n}): 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":["normalizeRoleAliases","andConditions","printGuardRead","expandRequiredRoles","CONDITION_VARS","v","RESERVED_CONDITION_VARS","groq","GROQ_IDENTIFIER","AuthoringWorkflowSchema","formatValidationError","WorkflowConfigSchema","AuthoringStageSchema","AuthoringActivitySchema","AuthoringActionSchema","AuthoringTransitionSchema","AuthoringFieldEntrySchema","AuthoringOpSchema","AuthoringGuardSchema","EffectSchema","schema","issuesFromValibot"],"mappings":";;;;;;;;;;;;;;;;;;;AAeO,SAAS,KAAK,YAAkC,QAA2B;AAEhF,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;ACwDO,SAAS,gBAAgB,WAA6C;AAC3E,QAAM,SAA4B,CAAA;AAClC,6BAA2B,UAAU,aAAa,MAAM;AACxD,QAAM,cAAcA,OAAAA,qBAAqB,UAAU,WAAW,GACxD,MAAW;AAAA,IACf;AAAA,IACA,iCAAiB,IAAA;AAAA,IACjB,mCAAmB,IAAA;AAAA,IACnB;AAAA,EAAA,GAGI,iBAAiB,oBAAoB,EAAC,SAAS,UAAU,QAAQ,MAAM,CAAC,QAAQ,GAAG,IAAA,CAAI,GACvF,gBAAgB,QAAQ,cAAc,GAEtC,SAAS,UAAU,OAAO,IAAI,CAAC,OAAO,MAAM;AAChD,UAAM,OAAkB,CA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