import * as v from "valibot";

/**
 * A stored action. `semantics` is engine-owned advisory meaning, independent
 * of execution and presentation — an array so the vocabulary can grow without
 * reshaping this field. `when`'s presence makes the action CASCADE-FIRED: the
 * engine fires it the moment the condition turns true, at most once per stage
 * visit, and it is never invocable via `fireAction`; absent, the action must
 * be invoked via `fireAction` by any caller holding a token (fire-on-entry is
 * `when: 'true'`). `filter` is existence with GROQ semantics — a non-matching
 * action might as well not exist (invisible to UI and LLMs, never merely
 * disabled); on a `when` action it composes: `filter` scopes whether the
 * automation exists, `when` is its firing trigger. `roles` is kept VERBATIM
 * only when cascade-fired (the pin on which identities may execute the
 * trigger); a fireAction-fired action's `roles` folds into `filter` at
 * desugar instead.
 *
 * @interface
 */
declare type Action = ActionFields<Op, string[], Effect> & {
  roles?: string[] | undefined;
};

/** @inline */
declare type ActionFields<TOp, TGroup, TEffect> = {
  name: string;
  semantics?: ActionSemantic[] | undefined;
  title?: string | undefined;
  description?: string | undefined;
  group?: TGroup | undefined;
  when?: string | undefined;
  filter?: string | undefined;
  params?: ActionParam[] | undefined;
  ops?: TOp[] | undefined;
  effects?: TEffect[] | undefined;
  spawn?: Subworkflows | undefined;
};

/**
 * Caller-supplied params declared on an action, validated before running ops
 * or queuing effects: a missing required param throws
 * `ActionParamsInvalidError` and the action does not commit. Resolved values
 * feed `ValueExpr.param` lookups.
 *
 * @interface
 */
declare type ActionParam = v.InferOutput<typeof ActionParamSchema>;

declare const ActionParamSchema: v.SchemaWithPipe<
  readonly [
    v.StrictObjectSchema<
      {
        readonly type: v.PicklistSchema<
          readonly [
            "string",
            "number",
            "boolean",
            "url",
            "dateTime",
            "actor",
            "doc.ref",
            "doc.refs",
            "json",
          ],
          string
        >;
        readonly name: v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >;
        readonly title: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
        readonly description: v.OptionalSchema<
          v.StringSchema<undefined>,
          undefined
        >;
        readonly required: v.OptionalSchema<
          v.BooleanSchema<undefined>,
          undefined
        >;
        readonly options: v.OptionalSchema<
          v.GenericSchema<ChoiceOptions>,
          undefined
        >;
        readonly validation: v.OptionalSchema<
          v.GenericSchema<ScalarValidation>,
          undefined
        >;
      },
      undefined
    >,
    v.CheckAction<
      {
        type:
          | "string"
          | "number"
          | "boolean"
          | "doc.ref"
          | "doc.refs"
          | "url"
          | "actor"
          | "dateTime"
          | "json";
        name: string;
        title?: string | undefined;
        description?: string | undefined;
        required?: boolean | undefined;
        options?: ChoiceOptions | undefined;
        validation?: ScalarValidation | undefined;
      },
      (
        issue: v.CheckIssue<{
          type:
            | "string"
            | "number"
            | "boolean"
            | "doc.ref"
            | "doc.refs"
            | "url"
            | "actor"
            | "dateTime"
            | "json";
          name: string;
          title?: string | undefined;
          description?: string | undefined;
          required?: boolean | undefined;
          options?: ChoiceOptions | undefined;
          validation?: ScalarValidation | undefined;
        }>,
      ) => string
    >,
    v.CheckAction<
      {
        type:
          | "string"
          | "number"
          | "boolean"
          | "doc.ref"
          | "doc.refs"
          | "url"
          | "actor"
          | "dateTime"
          | "json";
        name: string;
        title?: string | undefined;
        description?: string | undefined;
        required?: boolean | undefined;
        options?: ChoiceOptions | undefined;
        validation?: ScalarValidation | undefined;
      },
      (
        issue: v.CheckIssue<{
          type:
            | "string"
            | "number"
            | "boolean"
            | "doc.ref"
            | "doc.refs"
            | "url"
            | "actor"
            | "dateTime"
            | "json";
          name: string;
          title?: string | undefined;
          description?: string | undefined;
          required?: boolean | undefined;
          options?: ChoiceOptions | undefined;
          validation?: ScalarValidation | undefined;
        }>,
      ) => string
    >,
  ]
>;

declare type ActionSemantic = DecisionSemantic | Semantic;

/**
 * A unit of work carrying no payload of its own — every op, effect, and
 * spawn lives on an action; an activity contributes scoped `fields`
 * (resolved at stage entry), existence (`filter`), advisory readiness
 * (`requirements`), and the off-system marker (`target`, a BPMN Manual Task
 * deep-link, render-only and never gating). All in-scope activities are
 * ACTIVE from stage entry until an action's terminal `status` resolves them —
 * there is no activation moment. `filter` is existence with GROQ semantics,
 * evaluated once against the stage's entry state: a definite `false`
 * excludes the activity from UI, LLMs, and `$allActivitiesDone`.
 * `requirements` are readiness gates orthogonal to `filter` — an unmet one
 * keeps the activity visible but disables its actions with a
 * `requirements-unmet` verdict; distinct from ACL and guards.
 *
 * @interface
 */
declare type Activity = ActivityFields<
  FieldEntry,
  Action,
  ManualTarget,
  string[]
>;

/** @inline */
declare type ActivityFields<TField, TAction, TTarget, TGroup> = {
  name: string;
  semantics?: Semantic[] | undefined;
  title?: string | undefined;
  description?: string | undefined;
  groups?: Group[] | undefined;
  group?: TGroup | undefined;
  target?: TTarget | undefined;
  filter?: string | undefined;
  requirements?: GroqRequirement[] | undefined;
  actions?: TAction[] | undefined;
  fields?: TField[] | undefined;
};

/**
 * An activity is `active` from stage entry (or `skipped` when its `filter`
 * excluded it) until a terminal status resolves it — there is no pre-active
 * state. The authored action `status:` sugar (and the `status.set` op it
 * desugars to) is constrained to {@link TerminalActivityStatus}.
 */
declare type ActivityStatus = "active" | "done" | "skipped" | "failed";

/**
 * The stored action fields plus authoring sugar. `roles`: on a fireAction-fired action (no
 * `when`) it desugars into a `count($actor.roles[@ in [...]]) > 0` condition
 * ANDed with `filter`; on a CASCADE-FIRED action it stores VERBATIM instead —
 * the pin on which identities may execute the trigger, since folding it into
 * `filter` would make the action's existence depend on whose token cascades.
 * `roleAliases` widens the membership either way. `status` compiles to a
 * `status.set` op on the firing activity, appended AFTER the authored ops —
 * deliberately never implied, so a forgotten `status` is a visible stall
 * rather than a silently completed action.
 */
declare type AuthoringAction = AuthoringRawAction;

/** @interface */
declare type AuthoringActivity = ActivityFields<
  AuthoringFieldEntry,
  AuthoringAction,
  AuthoringManualTarget,
  GroupMembership
>;

/**
 * Authoring editability adds the `role[]` convenience: a non-empty role list
 * desugars to the same `count($actor.roles[@ in [...]]) > 0` membership
 * predicate `action.roles` produces. `true` opens the field to anyone in its
 * window; a bare string is a raw predicate.
 */
declare type AuthoringEditable = true | string[] | string;

/**
 * An {@link Effect} whose `retry` block may omit its `kind`, plus the
 * authoring-only `runtime` block that says where the generated runtime hosts
 * this handler. `retry` is stored; `runtime` is stripped before the deploy
 * writes the definition.
 *
 * @interface
 */
declare type AuthoringEffect = EffectFields<AuthoringEffectRetry> & {
  runtime?: EffectRuntimeBlock | undefined;
};

/** An {@link EffectRetry} whose omitted `kind` defaults to `engine`. */
declare type AuthoringEffectRetry = EffectRetryFields & {
  kind?: EffectRetryKind | undefined;
};

/**
 * A raw field entry or one of the authoring-only field sugars. `todoList`
 * expands to an array of objects with `label`, `status`, optional `assignee`,
 * and optional `dueDate`; that due date remains an ordinary date field.
 * `notes` expands to an array of audit-shaped objects with `body`, `actor`,
 * and `at` fields. Sugar type names are compiled away and never become stored
 * field kinds.
 * See {@link FieldEntry} for scope, required-input, and field-type constraints.
 */
declare type AuthoringFieldEntry =
  | AuthoringRawFieldEntry
  | TodoListField
  | NotesField;

/**
 * A field reference with `scope` optional; desugar resolves it lexically
 * (activity → stage → workflow) into {@link StoredFieldRef}.
 *
 * @interface
 */
declare type AuthoringFieldRef = v.InferOutput<typeof AuthoringFieldRefSchema>;

declare const AuthoringFieldRefSchema: v.StrictObjectSchema<
  {
    readonly scope: v.OptionalSchema<
      v.PicklistSchema<readonly ["workflow", "stage", "activity"], string>,
      undefined
    >;
    readonly field: v.SchemaWithPipe<
      readonly [
        v.StringSchema<undefined>,
        v.MinLengthAction<string, 1, "must be a non-empty string">,
      ]
    >;
  },
  undefined
>;

/**
 * A stage's content mutation guard. Its name must be unique across the whole
 * definition and use lowercase letters, digits, and dashes, starting with a
 * letter or digit. `match.actions` must contain at least one action.
 *
 * `match.types` intersects the ID criteria. Within the ID criteria, matching
 * either `idRefs` or `idPatterns` is sufficient. Omitted or empty optional
 * criteria do not constrain the match. `idRefs` uses typed {@link GuardRead}s.
 * Patterns use resource-local document-ID characters and `*` wildcards.
 * A release-version pattern is rejected if translating it for a lifecycle
 * action would broaden it to every document.
 *
 * `predicate` is delta-mode GROQ over `document`, `guard`, and `mutation`;
 * see {@link GUARD_PREDICATE_VARS}. Only a strict `true` allows a matching
 * mutation. An omitted or empty predicate denies it. `metadata` resolves
 * {@link GuardRead}s into values available as `guard.metadata` in the predicate.
 * Engine evaluations are advisory; the Content Lake is the enforcement point.
 *
 * @interface
 */
declare type AuthoringGuard = v.InferOutput<typeof AuthoringGuardSchema>;

declare const AuthoringGuardSchema: v.StrictObjectSchema<
  {
    name: v.SchemaWithPipe<
      readonly [
        v.StringSchema<undefined>,
        v.MinLengthAction<string, 1, "must be a non-empty string">,
      ]
    >;
    title: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    match: v.StrictObjectSchema<
      {
        types: v.OptionalSchema<
          v.ArraySchema<
            v.SchemaWithPipe<
              readonly [
                v.StringSchema<undefined>,
                v.MinLengthAction<string, 1, "must be a non-empty string">,
              ]
            >,
            undefined
          >,
          undefined
        >;
        idRefs: v.OptionalSchema<
          v.ArraySchema<v.GenericSchema<GuardRead>, undefined>,
          undefined
        >;
        idPatterns: v.OptionalSchema<
          v.ArraySchema<
            v.SchemaWithPipe<
              readonly [
                v.StringSchema<undefined>,
                v.MinLengthAction<string, 1, "must be a non-empty string">,
              ]
            >,
            undefined
          >,
          undefined
        >;
        actions: v.SchemaWithPipe<
          readonly [
            v.ArraySchema<
              v.PicklistSchema<
                readonly ["create", "update", "delete", "publish", "unpublish"],
                string
              >,
              undefined
            >,
            v.MinLengthAction<
              ("create" | "update" | "delete" | "publish" | "unpublish")[],
              1,
              "a guard must match at least one action"
            >,
          ]
        >;
      },
      undefined
    >;
    predicate: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    metadata: v.OptionalSchema<
      v.RecordSchema<
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        v.GenericSchema<GuardRead>,
        undefined
      >,
      undefined
    >;
  },
  undefined
>;

/** Like {@link ManualTarget}, but the `field` variant also accepts a bare
 *  field name; desugar normalises it into {@link AuthoringFieldRef}. */
declare type AuthoringManualTarget =
  | {
      type: "url";
      url: string;
    }
  | {
      type: "field";
      field: string | AuthoringFieldRef;
    };

/** Like {@link Op}, plus: `status.set`'s `activity` is optional (desugar fills
 *  the firing activity), and the `audit` sugar — a stamped append merging
 *  `actor`/`at` {@link ValueExpr} fields into its own value.
 */
declare type AuthoringOp =
  | FieldMutationOp<AuthoringFieldRef>
  | {
      type: "status.set";
      activity?: string | undefined;
      status: ActivityStatus;
    }
  | {
      type: "audit";
      target: AuthoringFieldRef;
      value: ValueExpr;
      stampFields?:
        | {
            actor?: string | undefined;
            at?: string | undefined;
          }
        | undefined;
    };

/** @inline */
declare type AuthoringRawAction = ActionFields<
  AuthoringOp,
  GroupMembership,
  AuthoringEffect
> & {
  roles?: string[] | undefined;
  status?: TerminalActivityStatus | undefined;
};

/** @inline */
declare type AuthoringRawFieldEntry = FieldEntryFields<
  AuthoringEditable,
  GroupMembership
>;

/**
 * A {@link Stage} accepting authoring fields, activities, transitions, guards,
 * and role-list editability. The same terminal-stage constraints apply.
 *
 * @interface
 */
declare type AuthoringStage = StageFields<
  AuthoringFieldEntry,
  AuthoringActivity,
  AuthoringTransition,
  AuthoringGuard,
  AuthoringEditable
>;

/** A {@link StartBlock} whose omitted `kind` defaults to `interactive`. */
declare type AuthoringStartBlock = StartFields & {
  kind?: StartKind | undefined;
};

/**
 * A {@link Transition} whose `when` may be omitted, defaulting to
 * `$allActivitiesDone`. Use `when: 'true'` for an unconditional route.
 */
declare type AuthoringTransition = TransitionFields & {
  when?: string | undefined;
};

/**
 * The authoring surface: stored primitives plus the define-time sugar. `runtime`
 * says where the generated unattended runtime hosts this workflow, overriding
 * its deployment's kind; an effect node overrides it in turn.
 *
 * @interface
 */
declare type AuthoringWorkflow = WorkflowFields<
  AuthoringFieldEntry,
  AuthoringStage,
  AuthoringStartBlock
> & {
  runtime?: RuntimeBlock | undefined;
};

declare interface ChoiceOption {
  title: string;
  value: ChoiceValue;
}

/**
 * A closed list of allowed non-null scalar values. The list must be nonempty,
 * with unique values and nonempty titles. Each value must satisfy the
 * receiving type and its validation bounds.
 *
 * Fields accept choices on `string`, `text`, `number`, `url`, `date`,
 * `dueDate`, `datetime`, and `dueDatetime`. Action parameters accept choices
 * on `string`, `number`, `url`, and `dateTime`.
 */
declare interface ChoiceOptions {
  list: ChoiceOption[];
}

declare type ChoiceValue = string | number;

/**
 * A raw GROQ string evaluated over the rendered scope: the engine-bound
 * variables inventoried in {@link CONDITION_VARS} (each annotated with the
 * context that binds it) plus the author's nullary `predicates` as `$<name>`
 * booleans. Evaluation runs against the instance's in-memory snapshot —
 * never a `_type` scan over the lake (rejected at deploy).
 *
 * There is no `{ref, args}` wrapper: parameterized reuse is a define-time
 * TypeScript function producing a condition string (see the {@link define.groq | groq} tag).
 */
declare type Condition = string;

/**
 * Every variable the engine binds for the RENDERED condition scope (every
 * condition site: transition `when`s, activity filters, action
 * `when`s/filters, effect bindings, `spawn` reads, where-op `where`s,
 * editability predicates, author predicates) — the deploy-time shadow check
 * ({@link RESERVED_CONDITION_VARS}) and the docs on {@link Condition} derive
 * from this list; extend it here when the engine grows a binding, never in
 * a comment elsewhere.
 *
 * Three other GROQ contexts read a definition and do NOT share this
 * inventory: cascade gates (transition/activity/cascade-action gates, which
 * must resolve identically regardless of caller — only the `'always'`-bound
 * subset carries values, {@link FILTER_SCOPE_VARS}); the start contexts
 * (`start.filter` is browse-time-pure over a candidate document,
 * {@link START_FILTER_VARS}; a start `groq` requirement binds `$fields`
 * instead, {@link START_REQUIREMENT_VARS}); and lake guard predicates, which
 * are not conditions at all — delta-mode GROQ over a mutation, binding
 * {@link GUARD_PREDICATE_VARS} instead.
 */
export declare const CONDITION_VARS: readonly ConditionVar[];

export declare interface ConditionVar {
  /** The GROQ param name, read as `$<name>`. */
  name: string;
  binding: ConditionVarBinding;
  description: string;
  /** Short human phrase for rendered explanations ("all activities in this
   *  stage are finished") — consumer-facing, unlike `description`. */
  label: string;
}

/**
 * When a condition var holds a value:
 *
 * - `'always'` — bound in every condition evaluation, derived from the
 *   instance and its snapshot.
 * - `'caller'` — rides the acting caller; without one the var is `undefined`
 *   (conditions referencing it fail closed). Author predicates may not read
 *   these — they pre-evaluate caller-free, per evaluation context.
 * - `'spawn'` — bound only at spawn sites (the per-row `$row`).
 */
export declare type ConditionVarBinding = "always" | "caller" | "spawn";

/** A define-time validated `custom.<camelCaseMeaning>` value. */
declare type CustomSemantic = `custom.${string}`;

declare const DECISION_SEMANTICS: readonly [
  "decision.accept",
  "decision.decline",
];

declare type DecisionSemantic = (typeof DECISION_SEMANTICS)[number];

export declare function defineAction(action: AuthoringAction): AuthoringAction;

export declare function defineActivity(
  activity: AuthoringActivity,
): AuthoringActivity;

/**
 * What `defineWorkflow` returns: the stored definition, plus `runtime` when the
 * workflow or one of its effects declared a hosting kind. Generation and the
 * blueprint tooling read `runtime`; the deploy drops it, so it never reaches the
 * Content Lake and never affects a definition's content fingerprint.
 */
declare type DefinedWorkflow = WorkflowDefinition & {
  runtime?: DefinitionRuntime | undefined;
};

/**
 * Validate and return an effect declaration — the registry model: `name` is
 * the effect's only identity; the host app registers a handler against it.
 */
export declare function defineEffect(effect: AuthoringEffect): AuthoringEffect;

export declare function defineEffectDescriptor(
  descriptor: EffectDescriptor,
): EffectDescriptor;

export declare function defineField(
  entry: AuthoringFieldEntry,
): AuthoringFieldEntry;

/**
 * Validate and return a group declaration — advisory "what belongs together"
 * metadata. Declared in a `groups` array (workflow root, stage, or activity);
 * fields, activities, and actions join via `group`. The engine stores and
 * deploy-checks groups but never acts on them.
 */
export declare function defineGroup(group: Group): Group;

export declare function defineGuard(guard: AuthoringGuard): AuthoringGuard;

export declare function defineOp(op: AuthoringOp): AuthoringOp;

export declare function defineStage(stage: AuthoringStage): AuthoringStage;

export declare function defineTransition(
  transition: AuthoringTransition,
): AuthoringTransition;

/**
 * Validate, desugar, and return a workflow definition in its stored shape, plus
 * the `runtime` hosting the workflow or its effects declared. Throws with a
 * formatted, path-prefixed error message if validation fails.
 *
 * Example error:
 *
 * ```
 * defineWorkflow("article-review") failed validation (2 issues):
 *   - stages[1].transitions[0].to: transition target "ready" is not a declared stage. Known stages: "drafting", "review", "approved"
 *   - predicates.allActivitiesDone: predicate "allActivitiesDone" shadows the built-in $allActivitiesDone — pick another name
 * ```
 */
export declare function defineWorkflow(
  definition: AuthoringWorkflow,
): DefinedWorkflow;

/**
 * Validate a deploy config — the binding of each definition's logical resource
 * handles to physical resources, per environment (tag). Throws a formatted,
 * path-prefixed error if the shape is invalid. The CLI collapses the selected
 * deployment's bindings via {@link index.resourceAliasesToMap | resourceAliasesToMap} into the
 * `resourceAliases` map `deployDefinitions` expands against.
 *
 * Validates shape only; reader-floor acknowledgement belongs to paths that
 * submit definitions (`deployDefinitions`, the CLI deploy and definition-diff
 * commands, and blueprint provision). Other commands may load a selected
 * deployment with a missing floor.
 *
 * Each `WorkflowDeploymentInput` carries an acknowledgement; definition-submission
 * paths compare it with the submitted definitions. The returned {@link WorkflowConfig}
 * is the looser parsed shape.
 */
export declare function defineWorkflowConfig(
  config: WorkflowConfigInput,
): WorkflowConfig;

/**
 * The hosting declarations {@link DefinedWorkflow} carries for the generator,
 * collected out of the authored tree. `kind` is present only when the workflow
 * declared one, so an absent `kind` inherits the deployment's. `effects` holds
 * one entry per effect that declared a block, keyed by effect name.
 */
declare interface DefinitionRuntime {
  kind?: RuntimeKind | undefined;
  effects?: Record<string, EffectRuntimeBlock> | undefined;
}

/**
 * Declared editability of a field — the generic edit seam's gate. Default
 * (absent) is NOT editable: a field is op-only engine working memory unless the
 * modeler opens it. The stored form is `true` (editable by anyone within the
 * field's scope window) or an EDIT CONDITION — rendered-scope GROQ (`$actor`,
 * `$can`, `$attributes`, `$fields`, `$assigned`), checked like an action filter
 * to decide who-may-edit. ADVISORY like every engine gate — it disables the
 * inline field and explains; a {@link Guard} declares the intended write-lock.
 */
declare type Editable = true | string;

/**
 * External work queued for the handler registered under `name`. Names are
 * unique within a definition; completed outputs are read as `$effects['<name>']`.
 *
 * `bindings` resolves GROQ expressions against the action's rendered scope
 * when the effect is queued. The handler receives one parameter bag combining
 * those values with static `input`. An `input` key overrides a same-named
 * binding, including when its value is null.
 *
 * `outputs` declares the allowed result keys and their {@link FieldShape}s.
 * An undeclared key or invalid value rejects the completion without storing
 * it. Omitting `outputs` allows no output keys.
 *
 * `retry` ({@link EffectRetry}) bounds how many times a failing handler is
 * attempted. Omitting it completes the effect as failed on the first failure.
 *
 * @interface
 */
declare type Effect = EffectFields<EffectRetry>;

/**
 * Effect handler descriptor, registered by the runtime against an effect
 * `name` (1:1 — the stored definition never references code). The description
 * and param shape live in the registry, which the SDK snapshots into
 * `pendingEffects[]` at queue time.
 */
export declare interface EffectDescriptor {
  name: string;
  description?: string;
  params?: EffectDescriptorParam[];
}

export declare interface EffectDescriptorParam {
  name: string;
  type: "string" | "number" | "boolean" | "object" | "string[]";
  required?: boolean;
  description?: string;
}

/** @inline */
declare type EffectFields<TRetry> = {
  name: string;
  title?: string | undefined;
  description?: string | undefined;
  bindings?: Record<string, string> | undefined;
  input?: Record<string, unknown> | undefined;
  outputs?: FieldShape[] | undefined;
  retry?: TRetry | undefined;
};

/**
 * A bounded retry policy for one effect. Both bounds govern one drain's run of
 * the policy, not the effect's lifetime: a drainer that dies mid-run leaves the
 * entry for the next drain, which starts a fresh run with the full budget, so
 * an effect can see more handler calls in total than `attempts`.
 *
 * `attempts` is the total number of attempts in a run, the first included, so
 * `1` means "never retry".
 *
 * `expiryMs` and the backoff a policy accumulates are each capped at 366 days
 * (`31_622_400_000` ms), inclusive. Deploy refuses a policy declaring more,
 * and one whose accumulated backoff reaches its own `expiryMs` before its
 * `attempts` are spent. Those checks weigh the declared waits alone. At
 * runtime every elapsed millisecond counts against `expiryMs`, handler time
 * included, so a slow handler can leave attempts unused. `backoff` paces
 * them; omitting it retries with no wait. Every duration is a whole number of
 * milliseconds above zero, and `attempts` a whole count above zero; deploy
 * rejects anything else.
 *
 * `expiryMs` decides whether a further attempt may start, measured from the
 * moment this run dispatched its first attempt. The window closes
 * on reaching it, so an attempt is admitted only while less than `expiryMs`
 * has elapsed. It is not a handler timeout. An attempt already running is
 * never interrupted, so a run can finish after the window, and a success then
 * still counts. Omitting it leaves `attempts` as the only bound.
 *
 * A policy that runs out of attempts, or that `expiryMs` stops, completes the
 * effect as failed, and `$effectStatus['<name>'] == 'failed'` routes the
 * instance. A successful attempt completes it as done, whichever attempt
 * succeeded. An effect with no `retry` completes as failed on its handler's
 * first failure.
 */
declare type EffectRetry = EffectRetryFields & {
  kind: EffectRetryKind;
};

/**
 * How long the engine waits between two attempts. `delayMs` is that wait in
 * milliseconds: `'fixed'` waits it every time, `'exponential'` doubles it per
 * attempt already made (`delayMs`, then `2 × delayMs`, then `4 × delayMs`).
 */
declare type EffectRetryBackoff = {
  kind: "fixed" | "exponential";
  delayMs: number;
};

/** @inline */
declare type EffectRetryFields = {
  attempts: number;
  backoff?: EffectRetryBackoff | undefined;
  expiryMs?: number | undefined;
};

/**
 * Who runs a retry policy. `'engine'` is the only member: the engine loops
 * inside the `drainEffects` call that picked the effect up, holding the claim
 * across the waits.
 */
declare type EffectRetryKind = "engine";

/**
 * The `runtime` block on an effect node, overriding its workflow's kind.
 * `timeout` is the seconds and `memory` the gigabytes the platform gives the
 * function that runs this handler. Each is a whole number inside the range
 * Sanity Functions accepts: `timeout` from 1 to 900 seconds, `memory` from 1 to
 * 10 gigabytes. A value outside its range fails at `defineWorkflow` rather than
 * at blueprint deploy. An effect declaring either gets its own drain function
 * instead of sharing the deployment's. Both are the function budget, so both
 * are accepted only under `'function'`.
 */
declare type EffectRuntimeBlock =
  | {
      kind: "function";
      timeout?: number | undefined;
      memory?: number | undefined;
    }
  | {
      kind: "durableFunction";
    }
  | {
      kind: "selfHosted";
    };

/**
 * The kinds a VALUE can take — scalars aligned to Sanity's names, the
 * reference kinds, the actor/assignee identities, and the two compositional
 * kinds (`object` with named `fields`, `array` of objects shaped by `of`).
 * This is also the set a nested {@link FieldShape} sub-field may use. Kinds
 * are bare (unique within their union); namespacing lives only on
 * engine-owned lake document `_type`s ({@link WORKFLOW_DEFINITION_TYPE}, the
 * instance type).
 *
 * Exported (module-level, not package API) for the model-surface gate's
 * enum-value coverage test.
 */
declare const FIELD_VALUE_KINDS: readonly [
  "doc.ref",
  "doc.refs",
  "subject",
  "release.ref",
  "string",
  "text",
  "number",
  "progress",
  "boolean",
  "date",
  "dueDate",
  "datetime",
  "dueDatetime",
  "url",
  "actor",
  "assignee",
  "assignees",
  "object",
  "array",
];

/** @inline */
declare type FieldBase<TEditable, TGroup> = {
  name: string;
  title?: string | undefined;
  description?: string | undefined;
  group?: TGroup | undefined;
  required?: boolean | undefined;
  initialValue?: FieldSource | undefined;
  editable?: TEditable | undefined;
};

/**
 * A field declaration whose location determines its scope and lifetime.
 * Workflow fields initialize at start; stage and activity fields initialize
 * on each stage visit. {@link FieldSource} controls initialization;
 * {@link Editable} controls direct edits independently.
 *
 * `required: true` is valid only on workflow-scope fields with an `input`
 * source. It requires a non-null value at start or spawn. On `subject`,
 * `doc.ref`, and `doc.refs`, selected targets must also remain readable in the
 * workflow perspective after initialization. Missing targets block normal
 * actions, triggered actions, and transitions. Abort and permitted field edits remain available.
 * `subject` is also
 * workflow-scope-only, with at most one subject per definition. Each scope
 * may declare at most one `dueDate` or `dueDatetime` field, always top-level.
 *
 * `types` is a nonempty list of accepted document types on `subject`,
 * `doc.ref`, or `doc.refs`; omit it to accept any document type. On
 * `subject`, `types` instead governs which documents the definition's
 * applicability read matches: an unscoped `subject` never matches a system
 * document ({@link isSystemDocumentType}), and naming a reserved-namespace
 * type in `types` matches it. Naming an engine-owned type fails
 * `defineWorkflow` and deploy validation; to run a workflow from another
 * workflow, use `spawn`. A stored definition that names one never matches it.
 * `roles` constrains assignment eligibility only on `assignee` and `assignees`.
 * {@link FieldShape}, {@link ChoiceOptions}, and {@link ScalarValidation}
 * define the nested-shape and scalar constraints. Authoring conveniences are
 * accepted by {@link AuthoringFieldEntry}.
 *
 * @interface
 */
declare type FieldEntry = FieldEntryFields<Editable, string[]>;

/** @inline */
declare type FieldEntryFields<TEditable, TGroup> = FieldBase<
  TEditable,
  TGroup
> & {
  type: FieldValueKind;
  options?: ChoiceOptions | undefined;
  validation?: ScalarValidation | undefined;
  types?: string[] | undefined;
  /** Non-empty assignment eligibility constraint. User roles apply aliases; collective roles match literally. */
  roles?: string[] | undefined;
  fields?: FieldShape[] | undefined;
  of?: FieldShape[] | undefined;
};

/**
 * A field mutation targeting a declared field. Resolved values must satisfy
 * that field's shape, choices, validation, and assignment constraints.
 *
 * `field.setIfMissing` supports nullable fields only. If a value exists, it
 * leaves the value unchanged and records no `opApplied` history event.
 * `field.inc` and `field.dec` require an initialized `number` field; their
 * delta defaults to `1`. Both the delta and resulting value must be finite,
 * and the result must satisfy the field's validation bounds.
 *
 * `field.append` adds one valid list member. `field.updateWhere` accepts only
 * `array` fields and merges an object into matching rows. The merge cannot
 * write `_key` or `_type`, and each resulting row must satisfy its declared
 * shape. `field.removeWhere` supports list fields. See {@link Op} for row
 * selection and history behavior.
 */
declare type FieldMutationOp<
  TTarget extends {
    field: string;
  },
> =
  | {
      type: "field.set";
      target: TTarget;
      value: ValueExpr;
    }
  | {
      type: "field.setIfMissing";
      target: TTarget;
      value: ValueExpr;
    }
  | {
      type: "field.unset";
      target: TTarget;
    }
  | {
      type: "field.append";
      target: TTarget;
      value: ValueExpr;
    }
  | {
      type: "field.inc";
      target: TTarget;
      value?: ValueExpr | undefined;
    }
  | {
      type: "field.dec";
      target: TTarget;
      value?: ValueExpr | undefined;
    }
  | {
      type: "field.updateWhere";
      target: TTarget;
      where: Condition;
      value: ValueExpr;
    }
  | {
      type: "field.removeWhere";
      target: TTarget;
      where: Condition;
    };

/**
 * A {@link FieldMutationOp} whose target scope is explicit. Actions can write
 * fields in their activity, stage, or workflow. Effect completions accept only
 * workflow- or stage-scoped field operations, never activity status changes.
 */
declare type FieldOp = FieldMutationOp<StoredFieldRef>;

/** @inline */
declare type FieldReadExpr = {
  type: "fieldRead";
  scope?: "workflow" | "stage" | undefined;
  field: string;
  path?: string | undefined;
};

/**
 * A nested field shape inside an object's `fields`, an array's `of`, or an
 * effect's `outputs`. It has no initialization, direct editability, or required
 * setting; those belong to {@link FieldEntry}.
 *
 * An `object` requires nonempty `fields` and no `of`. An `array` requires
 * nonempty `of` and no `fields`. Other types accept neither. Sibling names
 * must be unique. Use ordinary `date` and `datetime` here; `dueDate` and
 * `dueDatetime` are not valid nested fields or effect outputs.
 * {@link ChoiceOptions} and {@link ScalarValidation} constrain supported
 * scalar types. `roles` is valid only on `assignee` and `assignees` shapes.
 */
declare interface FieldShape {
  type: FieldValueKind;
  name: string;
  title?: string | undefined;
  description?: string | undefined;
  options?: ChoiceOptions | undefined;
  validation?: ScalarValidation | undefined;
  /** Non-empty assignment eligibility constraint. User roles apply aliases; collective roles match literally. */
  roles?: string[] | undefined;
  fields?: FieldShape[] | undefined;
  of?: FieldShape[] | undefined;
}

/**
 * Supplies a field's `initialValue` once, when the field is initialized.
 * Omitting the source starts the field empty; an operation can fill it later.
 * The source does not grant permission to edit. Direct editing requires an
 * {@link Editable | editable} declaration.
 *
 * Distinct from {@link ValueExpr}, which supplies an operation's write value.
 * Only the literal and field-read forms are shared.
 *
 * `input` reads workflow inputs supplied at start or spawn. Stage and activity
 * input seeds receive no caller value; activity input seeds produce a deploy
 * warning. `literal` supplies a fixed value. `query` runs against the Content
 * Lake with earlier fields in the same scope available as `$fields`.
 * Reference normalization can omit unrecognized values without recording
 * `fieldQueryDiscarded`. A result that fails validation after normalization
 * uses the field's empty value (`null` or `[]`) and records that event.
 * A failed query throws.
 *
 * A `fieldRead` seed reads earlier fields in its own scope when `scope` is
 * omitted. A stage or activity seed can read workflow fields with
 * `scope: 'workflow'`. An activity seed cannot read stage fields. At workflow
 * scope, omit `scope` to read an earlier workflow field. `path` selects a
 * nested value; these reads do not load referenced documents.
 */
declare type FieldSource = FieldSourceInternal;

/** @inline */
declare type FieldSourceInternal =
  | {
      type: "input";
    }
  | {
      type: "query";
      query: string;
    }
  | LiteralExpr
  | FieldReadExpr;

/** The union a value (or nested {@link FieldShape}) kind may take — see {@link FIELD_VALUE_KINDS}. */
declare type FieldValueKind = (typeof FIELD_VALUE_KINDS)[number];

/**
 * The subset that holds a value in the cascade gates (transition `when`s,
 * activity filters, a cascade-fired action's `when`/`filter`).
 */
export declare const FILTER_SCOPE_VARS: readonly string[];

/**
 * Hygienic GROQ interpolation for define-time condition building.
 *
 * Parameterized predicate reuse lives in the host language — a TypeScript
 * function producing a condition string — and this tag is its safe splice:
 * interpolated *values* serialize as GROQ literals (JSON literal syntax is
 * valid GROQ), never as raw query text, so quoting and precedence cannot
 * break. The produced string is stored as a plain condition and validated at
 * deploy like any other.
 *
 * ```ts
 * const regulated = (kinds: string[]) => groq`$fields.subject.category in ${kinds}`
 * defineActivity({ name: "legal", filter: regulated(["finance", "health"]), … })
 * ```
 */
export declare function groq(
  strings: TemplateStringsArray,
  ...values: unknown[]
): string;

/**
 * A named GROQ readiness condition. Its name must be unique in the containing
 * requirements array. Activity requirements use instance and caller variables;
 * workflow requirements use the input and projected dataset in {@link StartBlock}.
 * Every requirement must pass before the corresponding caller action or fresh
 * standalone start can commit.
 */
declare type GroqRequirement = RequirementBase & {
  type: "groq";
  query: string;
};

/**
 * A declared "what belongs together" tag: the workflow root, a stage, or an
 * activity declares named groups, and field entries, activities, and actions
 * opt in via `group`. Purely advisory — the engine stores and validates names
 * (unique per level, every reference resolves) and never acts on them; a
 * consumer decides what a group means for its medium. The same name declared
 * at several levels is intentional nesting, addressed per level; the engine
 * never merges them.
 */
declare type Group = {
  name: string;
  title?: string | undefined;
  description?: string | undefined;
  kind?: GroupKind | undefined;
};

/**
 * Advisory classification of a declared {@link Group} by its informational
 * ROLE, never a rendering treatment: `'core'` marks content central to
 * understanding the workflow (condensed views include these first);
 * `'details'` marks depth on demand. Unset = a plain group. Consumers
 * reading a definition as data MUST treat an unknown kind as unset — growing
 * this list is an engine version bump, like every stored enum.
 */
declare const GROUP_KINDS: readonly ["core", "details"];

declare type GroupKind = (typeof GROUP_KINDS)[number];

/**
 * Group membership — the declared group(s) a node belongs to. A reference
 * resolves lexically up the node's enclosing chain (host activity → stage →
 * workflow; an activity's OWN membership sees stage → workflow — a node is
 * never a member of a group only it declares). An empty list is an author
 * error (it would name no groups) — omit `group` instead, and each group is
 * listed once. Authoring accepts a bare name as convenience; the STORED form
 * is always a list, so `'seo'` and `['seo']` hash identically under content
 * addressing and lake-side reads see one shape.
 */
declare type GroupMembership = string | string[];

/**
 * A stored workflow guard. Its string reads and authored lifecycle actions
 * remain unresolved until stage entry produces the Lake-shaped documents
 * deployed for that stage.
 *
 * @interface
 */
declare type Guard = v.InferOutput<typeof GuardSchema>;

/**
 * The identifiers a lake mutation guard's `predicate` reads — the wire
 * dialect, not the condition scope (so no {@link ConditionVarBinding}: these
 * bind only when a guard evaluates a mutation). `before()`/`after()`/
 * `identity()` are groq-js delta-mode natives on top of these. The guard
 * evaluator must bind every entry here at the predicate root.
 */
export declare const GUARD_PREDICATE_VARS: readonly {
  name: string;
  description: string;
}[];

/**
 * A value read for a guard's `match.idRefs` or `metadata`, resolved when the
 * guard is created or refreshed. `fieldRead` reads workflow fields only;
 * stage and activity fields are unavailable. `effectsRead` reads a completed
 * effect's output. `self` supplies the instance's GDR URI and `now` its ISO
 * clock value.
 * Paths cannot contain line breaks, and effect names cannot contain `'`.
 * Stored {@link Guard} declarations carry string forms of these reads.
 */
declare type GuardRead =
  | {
      type: "self";
    }
  | {
      type: "now";
    }
  | {
      type: "fieldRead";
      field: string;
      path?: string | undefined;
    }
  | {
      type: "effectsRead";
      effect: string;
      path?: string | undefined;
    };

declare const GuardSchema: v.StrictObjectSchema<
  {
    name: v.SchemaWithPipe<
      readonly [
        v.StringSchema<undefined>,
        v.MinLengthAction<string, 1, "must be a non-empty string">,
      ]
    >;
    title: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    match: v.StrictObjectSchema<
      {
        types: v.OptionalSchema<
          v.ArraySchema<
            v.SchemaWithPipe<
              readonly [
                v.StringSchema<undefined>,
                v.MinLengthAction<string, 1, "must be a non-empty string">,
              ]
            >,
            undefined
          >,
          undefined
        >;
        idRefs: v.OptionalSchema<
          v.ArraySchema<
            v.SchemaWithPipe<
              readonly [
                v.StringSchema<undefined>,
                v.MinLengthAction<string, 1, "must be a non-empty string">,
              ]
            >,
            undefined
          >,
          undefined
        >;
        idPatterns: v.OptionalSchema<
          v.ArraySchema<
            v.SchemaWithPipe<
              readonly [
                v.StringSchema<undefined>,
                v.MinLengthAction<string, 1, "must be a non-empty string">,
              ]
            >,
            undefined
          >,
          undefined
        >;
        actions: v.ArraySchema<
          v.PicklistSchema<
            readonly ["create", "update", "delete", "publish", "unpublish"],
            string
          >,
          undefined
        >;
      },
      undefined
    >;
    predicate: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
    metadata: v.OptionalSchema<
      v.RecordSchema<
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        undefined
      >,
      undefined
    >;
  },
  undefined
>;

/** @inline */
declare type LiteralExpr = {
  type: "literal";
  value: unknown;
};

/**
 * Off-system deep-link target — render-only metadata whose presence marks an
 * activity as off-system (BPMN Manual Task). Either a static URL, or a field
 * reference whose resolved document the consumer opens; deploy checks the
 * `field` variant points at a doc-valued entry.
 */
declare type ManualTarget =
  | {
      type: "url";
      url: string;
    }
  | {
      type: "field";
      field: StoredFieldRef;
    };

/** @inline */
declare type NotesField = FieldBase<AuthoringEditable, GroupMembership> & {
  type: "notes";
};

/**
 * An action operation: a {@link FieldOp} or a status change on an activity in
 * the current stage.
 *
 * For `field.updateWhere` and `field.removeWhere`, `where` evaluates each row
 * as `$row`. Caller-fired actions also supply `$params`. Referenced document
 * content is not loaded for row selection, and an unevaluable row never
 * matches. An operation matching no rows still records `opApplied` history.
 */
declare type Op =
  | FieldOp
  | {
      type: "status.set";
      activity: string;
      status: ActivityStatus;
    };

/** @inline */
declare type RequirementBase = {
  name: string;
  title?: string | undefined;
  description?: string | undefined;
};

/**
 * Names an author's predicate may not use — engine-owned and author names
 * share one namespace, so a predicate redefining a binding would silently
 * shadow engine behaviour. Rejected at deploy; derived from the condition
 * inventory.
 */
export declare const RESERVED_CONDITION_VARS: readonly string[];

/**
 * Roles that may fulfil each authored role. Aliases widen action gates,
 * `$assigned`, and assignment-field user eligibility by expanding the required
 * side; they never alter an actor's roles. Collective role assignees remain
 * literal ownership values and are not widened by this map. The authored `"*"`
 * key lists universal fulfillers and is normalized before persistence.
 */
declare type RoleAliases = Record<string, string[]>;

/**
 * The `runtime` block on a deployment and on `defineWorkflow`. A workflow that
 * declares none inherits its deployment's kind, and a deployment that declares
 * none hosts on `'function'`. Authoring-only: the deploy strips it and stores
 * nothing.
 *
 * It is a hint to the generator and to callers, never a rule the engine
 * enforces. The engine never sees it: any engine built anywhere with a handler
 * for an effect drains that effect when it calls `drainEffects`, whatever kind
 * the node declares, so a `'selfHosted'` effect is drained by whoever registers
 * its handler, the Studio included.
 */
declare interface RuntimeBlock {
  kind: RuntimeKind;
}

/**
 * Where the generated unattended runtime hosts a workflow or an effect.
 * `'function'` is a plain Sanity Function, `'durableFunction'` a durable one,
 * and `'selfHosted'` a process you run yourself.
 */
declare type RuntimeKind = "function" | "durableFunction" | "selfHosted";

/**
 * Inclusive bounds for `string`, `text`, `number`, or `progress` values.
 * String/text bounds count characters and must be non-negative integers.
 * Number bounds are finite numeric values. Progress bounds may only narrow
 * its inclusive 0–100 range.
 *
 * Supply at least one bound. When both are present, `min` must not exceed
 * `max`. Null values remain allowed unless an input is required separately.
 */
declare interface ScalarValidation {
  min?: number | undefined;
  max?: number | undefined;
}

declare type Semantic = SignalSemantic | CustomSemantic;

declare const SIGNAL_SEMANTICS: readonly [
  "signal.positive",
  "signal.caution",
  "signal.critical",
];

declare type SignalSemantic = (typeof SIGNAL_SEMANTICS)[number];

/**
 * A start requirement that rejects a fresh start when an unfinished run of
 * this definition holds the same subject, across deployed versions.
 * The workflow must declare an input-sourced `subject` field. Names are unique
 * within the requirements array. Like other engine checks, this is advisory;
 * it is not Content Lake enforcement.
 */
declare type SingleSubjectRequirement = RequirementBase & {
  type: "singleSubject";
};

/**
 * The fields, activities, guards, and outgoing routes for one stage visit.
 * A stage with no transitions is terminal: entering it completes the instance,
 * and it cannot declare activities. Put completion work in the source stage
 * or give the working stage an outgoing transition.
 *
 * Guards are registered on entry and retracted on exit. `editable` overrides
 * are keyed by in-scope field name and apply while the stage is current.
 * Each combines with the field's own edit condition using AND, so an override
 * can restrict editing but cannot open a field whose baseline is closed.
 * An unlisted field inherits its baseline.
 *
 * @interface
 */
declare type Stage = StageFields<
  FieldEntry,
  Activity,
  Transition,
  Guard,
  Editable
>;

/** @inline */
declare type StageFields<TField, TActivity, TTransition, TGuard, TEditable> = {
  name: string;
  semantics?: Semantic[] | undefined;
  title?: string | undefined;
  description?: string | undefined;
  groups?: Group[] | undefined;
  activities?: TActivity[] | undefined;
  transitions?: TTransition[] | undefined;
  guards?: TGuard[] | undefined;
  fields?: TField[] | undefined;
  editable?: Record<string, TEditable> | undefined;
};

/**
 * Discovery and readiness rules for standalone starts.
 * `filter` evaluates against a candidate document with `$tag`, `$definition`,
 * and `$now`. It controls discovery and never gates `startInstance`.
 * It cannot read `$fields` or caller variables.
 *
 * `requirements` evaluates named checks in declaration order before a fresh
 * standalone start. All must pass. Resuming an existing start and spawning
 * children do not rerun these checks. A GROQ requirement binds `$tag`,
 * `$definition`, `$now`, and `$fields`, with no candidate document root.
 * `$fields` contains supplied input values, including GDR reference envelopes;
 * it excludes computed defaults and hydrated document content.
 *
 * At both sites, `*` scans projected instances in the engine's tag. Each row
 * contains only `definition` (name), `subject` (GDR URI or null), and
 * `completedAt` (ISO timestamp or null). Completed and aborted runs are
 * included. Raw fields such as `_type`, `tag`, and `fields` are unavailable.
 * Use {@link SingleSubjectRequirement} for one unfinished run per subject.
 * These checks are advisory; the Content Lake remains the enforcement point.
 */
declare type StartBlock = StartFields & {
  kind: StartKind;
};

/** @inline */
declare type StartFields = {
  filter?: string | undefined;
  requirements?: StartRequirement[] | undefined;
};

/**
 * Who initiates a standalone run of this workflow: a person picking it from a
 * start surface (`'interactive'`, the default) or a system reacting to a
 * document event (`'autonomous'`). PURE CLASSIFICATION — consumers use it to
 * shape their surfaces (hide autonomous workflows from human pickers, list
 * interactive ones for editors); `startInstance` is one verb and one code
 * path for every kind, and an interactive start of an autonomous workflow is
 * legal.
 */
declare type StartKind = "interactive" | "autonomous";

/** Every named readiness requirement accepted by workflow `start.requirements`. */
declare type StartRequirement = GroqRequirement | SingleSubjectRequirement;

/**
 * A field reference with `scope` already resolved — the form every op target carries.
 *
 * @interface
 */
declare type StoredFieldRef = v.InferOutput<typeof StoredFieldRefSchema>;

declare const StoredFieldRefSchema: v.StrictObjectSchema<
  {
    readonly scope: v.PicklistSchema<
      readonly ["workflow", "stage", "activity"],
      string
    >;
    readonly field: v.SchemaWithPipe<
      readonly [
        v.StringSchema<undefined>,
        v.MinLengthAction<string, 1, "must be a non-empty string">,
      ]
    >;
  },
  undefined
>;

/**
 * Child workflows created by an action's `spawn`, exposed as `$subworkflows`.
 * `definition` selects the highest deployed version unless a version is pinned.
 *
 * `forEach` evaluates with workflow fields only and no caller variables, even
 * for a caller-fired action. Rows need unique identities: a nonempty `_key`,
 * then `_id`, then a GDR's `id`, or a scalar's string representation.
 * Missing or duplicate identities reject the spawn. Re-entry adopts matching
 * live children from the same activity, action, and definition instead of
 * duplicating them.
 *
 * `with` maps child input-field names to expressions evaluated with `$row`.
 * `context` evaluates once without `$row` and supplies the child's `$context`.
 * Both use the parent activity's field scope and the acting identity when
 * available. Neither binds `$can`, `$attributes`, or `$params`.
 * Context results must be strings, numbers, booleans, or full GDRs; null and
 * undefined omit the entry. Other objects and arrays reject the spawn.
 *
 * `onExit` governs live children when their cohort leaves scope: `detach`
 * (the default) leaves them running; `abort` stops them recursively. Aborting
 * the parent always stops its children. Parent transitions must separately
 * declare whether they wait for the cohort to settle.
 *
 * @interface
 */
declare type Subworkflows = v.InferOutput<typeof SubworkflowsSchema>;

declare const SubworkflowsSchema: v.StrictObjectSchema<
  {
    readonly forEach: v.SchemaWithPipe<
      readonly [
        v.StringSchema<undefined>,
        v.MinLengthAction<string, 1, "must be a non-empty string">,
      ]
    >;
    readonly definition: v.StrictObjectSchema<
      {
        readonly name: v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >;
        readonly version: v.OptionalSchema<
          v.UnionSchema<
            [
              v.SchemaWithPipe<
                readonly [
                  v.NumberSchema<undefined>,
                  v.IntegerAction<number, undefined>,
                  v.MinValueAction<number, 1, undefined>,
                ]
              >,
              v.LiteralSchema<"latest", undefined>,
            ],
            undefined
          >,
          undefined
        >;
      },
      undefined
    >;
    readonly with: v.OptionalSchema<
      v.RecordSchema<
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        undefined
      >,
      undefined
    >;
    readonly context: v.OptionalSchema<
      v.RecordSchema<
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        v.SchemaWithPipe<
          readonly [
            v.StringSchema<undefined>,
            v.MinLengthAction<string, 1, "must be a non-empty string">,
          ]
        >,
        undefined
      >,
      undefined
    >;
    readonly onExit: v.OptionalSchema<
      v.PicklistSchema<readonly ["detach", "abort"], string>,
      undefined
    >;
  },
  undefined
>;

/**
 * The statuses an activity can be resolved INTO — what `status.set` accepts.
 * A health axis, not a decision axis: a routine decision (decline, send back,
 * hold) resolves `done` and routes via a field write; `failed` means the work
 * genuinely could not complete. Only `done`/`skipped` satisfy
 * `$allActivitiesDone` — a `failed` activity blocks it permanently, surfacing
 * via `$anyActivityFailed`.
 */
declare type TerminalActivityStatus = "done" | "skipped" | "failed";

/** @inline */
declare type TodoListField = FieldBase<AuthoringEditable, GroupMembership> & {
  type: "todoList";
};

/**
 * A one-way route to another stage, without operations or effects. Selection
 * checks `when` conditions in declaration order. The first satisfied condition
 * fires; an earlier unevaluable condition, such as GROQ null, stops selection
 * without considering later routes. A false condition permits the next route.
 *
 * Actions write routing decisions into fields; transitions read that state.
 * Source-stage triggered actions run before transition selection. Arrival work
 * belongs to a triggered action in a nonterminal destination stage.
 */
declare type Transition = TransitionFields & {
  when: string;
};

/** @inline */
declare type TransitionFields = {
  name: string;
  title?: string | undefined;
  description?: string | undefined;
  to: string;
};

/**
 * An operation's write value, resolved when the operation applies.
 * `param` reads a caller-supplied action argument; `actor` records the acting
 * identity. `now` supplies the operation's ISO timestamp, `self` its instance's
 * GDR URI, and `stage` the current stage name. `object` resolves its fields
 * recursively.
 *
 * A `fieldRead` with no scope searches activity, stage, then workflow fields.
 * An explicit scope searches only that scope. A pathless read from a subject
 * or `doc.ref` into another subject or `doc.ref` preserves the stored reference.
 * Other reads use the referenced snapshot document, or only its `_id` and
 * `_type` when it is not loaded. No additional documents are fetched.
 * Initialization uses {@link FieldSource}, whose field-read scope rules differ.
 */
declare type ValueExpr = ValueExprInternal;

/** @inline */
declare type ValueExprInternal =
  | LiteralExpr
  | FieldReadExpr
  | {
      type: "param";
      param: string;
    }
  | {
      type: "actor";
    }
  | {
      type: "now";
    }
  | {
      type: "self";
    }
  | {
      type: "stage";
    }
  | {
      type: "object";
      fields: Record<string, ValueExprInternal>;
    };

/**
 * `deployments` names must be unique (the selector deployment-targeted
 * commands resolve by), and each `(workflowResource, tag)` pair must be
 * unique — that pair is the storage partition, so two deployments sharing
 * both would fight over definition versions. `telemetry`, when set, replaces
 * the CLI's built-in Sanity-intake shell entirely: every event flows to this
 * logger unconditionally (CI and `DO_NOT_TRACK` included), and consent,
 * environment suppression, and transport become this implementation's
 * business.
 *
 * @interface
 */
declare type WorkflowConfig = v.InferOutput<typeof WorkflowConfigSchema>;

/**
 * What an author writes for a whole config: every deployment is a
 * {@link WorkflowDeploymentInput}. `defineWorkflowConfig` accepts this and
 * returns the looser {@link WorkflowConfig}.
 */
declare type WorkflowConfigInput = Omit<WorkflowConfig, "deployments"> & {
  deployments: WorkflowDeploymentInput[];
};

declare const WorkflowConfigSchema: v.ObjectSchema<
  {
    readonly deployments: v.SchemaWithPipe<
      readonly [
        v.ArraySchema<
          v.ObjectSchema<
            {
              readonly name: v.SchemaWithPipe<
                readonly [
                  v.StringSchema<undefined>,
                  v.NonEmptyAction<string, undefined>,
                  v.CheckAction<
                    string,
                    `invalid ${string} \u2014 ASCII lowercase + digits + dashes, no leading dash, no dots`
                  >,
                ]
              >;
              readonly expectedMinReaderModel: v.OptionalSchema<
                v.CustomSchema<number, undefined>,
                undefined
              >;
              readonly tag: v.SchemaWithPipe<
                readonly [
                  v.StringSchema<undefined>,
                  v.NonEmptyAction<string, undefined>,
                  v.CheckAction<
                    string,
                    `invalid ${string} \u2014 ASCII lowercase + digits + dashes, no leading dash, no dots`
                  >,
                ]
              >;
              readonly workflowResource: v.VariantSchema<
                "type",
                [
                  v.ObjectSchema<
                    {
                      readonly type: v.LiteralSchema<"dataset", undefined>;
                      readonly id: v.SchemaWithPipe<
                        readonly [
                          v.SchemaWithPipe<
                            readonly [
                              v.StringSchema<undefined>,
                              v.NonEmptyAction<string, "must not be empty">,
                            ]
                          >,
                          v.CheckAction<
                            string,
                            'invalid dataset resource id — expected "<projectId>.<dataset>"'
                          >,
                        ]
                      >;
                    },
                    undefined
                  >,
                  v.ObjectSchema<
                    {
                      readonly type: v.LiteralSchema<"canvas", undefined>;
                      readonly id: v.SchemaWithPipe<
                        readonly [
                          v.StringSchema<undefined>,
                          v.NonEmptyAction<string, "must not be empty">,
                        ]
                      >;
                    },
                    undefined
                  >,
                  v.ObjectSchema<
                    {
                      readonly type: v.LiteralSchema<
                        "media-library",
                        undefined
                      >;
                      readonly id: v.SchemaWithPipe<
                        readonly [
                          v.StringSchema<undefined>,
                          v.NonEmptyAction<string, "must not be empty">,
                        ]
                      >;
                    },
                    undefined
                  >,
                  v.ObjectSchema<
                    {
                      readonly type: v.LiteralSchema<"dashboard", undefined>;
                      readonly id: v.SchemaWithPipe<
                        readonly [
                          v.StringSchema<undefined>,
                          v.NonEmptyAction<string, "must not be empty">,
                        ]
                      >;
                    },
                    undefined
                  >,
                ],
                undefined
              >;
              readonly resourceAliases: v.OptionalSchema<
                v.SchemaWithPipe<
                  readonly [
                    v.ArraySchema<
                      v.ObjectSchema<
                        {
                          readonly name: v.SchemaWithPipe<
                            readonly [
                              v.SchemaWithPipe<
                                readonly [
                                  v.StringSchema<undefined>,
                                  v.NonEmptyAction<string, "must not be empty">,
                                ]
                              >,
                              v.CheckAction<
                                string,
                                "invalid resource handle name — lowercase letters, digits and dashes only, no leading dash"
                              >,
                            ]
                          >;
                          readonly resource: v.VariantSchema<
                            "type",
                            [
                              v.ObjectSchema<
                                {
                                  readonly type: v.LiteralSchema<
                                    "dataset",
                                    undefined
                                  >;
                                  readonly id: v.SchemaWithPipe<
                                    readonly [
                                      v.SchemaWithPipe<
                                        readonly [
                                          v.StringSchema<undefined>,
                                          v.NonEmptyAction<
                                            string,
                                            "must not be empty"
                                          >,
                                        ]
                                      >,
                                      v.CheckAction<
                                        string,
                                        'invalid dataset resource id — expected "<projectId>.<dataset>"'
                                      >,
                                    ]
                                  >;
                                },
                                undefined
                              >,
                              v.ObjectSchema<
                                {
                                  readonly type: v.LiteralSchema<
                                    "canvas",
                                    undefined
                                  >;
                                  readonly id: v.SchemaWithPipe<
                                    readonly [
                                      v.StringSchema<undefined>,
                                      v.NonEmptyAction<
                                        string,
                                        "must not be empty"
                                      >,
                                    ]
                                  >;
                                },
                                undefined
                              >,
                              v.ObjectSchema<
                                {
                                  readonly type: v.LiteralSchema<
                                    "media-library",
                                    undefined
                                  >;
                                  readonly id: v.SchemaWithPipe<
                                    readonly [
                                      v.StringSchema<undefined>,
                                      v.NonEmptyAction<
                                        string,
                                        "must not be empty"
                                      >,
                                    ]
                                  >;
                                },
                                undefined
                              >,
                              v.ObjectSchema<
                                {
                                  readonly type: v.LiteralSchema<
                                    "dashboard",
                                    undefined
                                  >;
                                  readonly id: v.SchemaWithPipe<
                                    readonly [
                                      v.StringSchema<undefined>,
                                      v.NonEmptyAction<
                                        string,
                                        "must not be empty"
                                      >,
                                    ]
                                  >;
                                },
                                undefined
                              >,
                            ],
                            undefined
                          >;
                        },
                        undefined
                      >,
                      undefined
                    >,
                    v.CheckAction<
                      {
                        name: string;
                        resource:
                          | {
                              type: "dataset";
                              id: string;
                            }
                          | {
                              type: "canvas";
                              id: string;
                            }
                          | {
                              type: "media-library";
                              id: string;
                            }
                          | {
                              type: "dashboard";
                              id: string;
                            };
                      }[],
                      (
                        issue: v.CheckIssue<
                          {
                            name: string;
                            resource:
                              | {
                                  type: "dataset";
                                  id: string;
                                }
                              | {
                                  type: "canvas";
                                  id: string;
                                }
                              | {
                                  type: "media-library";
                                  id: string;
                                }
                              | {
                                  type: "dashboard";
                                  id: string;
                                };
                          }[]
                        >,
                      ) => string
                    >,
                  ]
                >,
                undefined
              >;
              readonly definitions: v.SchemaWithPipe<
                readonly [
                  v.ArraySchema<
                    v.CustomSchema<
                      DefinedWorkflow,
                      v.ErrorMessage<v.CustomIssue> | undefined
                    >,
                    undefined
                  >,
                  v.MinLengthAction<
                    DefinedWorkflow[],
                    1,
                    "a deployment needs at least one definition"
                  >,
                ]
              >;
              readonly runtime: v.OptionalSchema<
                v.GenericSchema<RuntimeBlock>,
                undefined
              >;
            },
            undefined
          >,
          undefined
        >,
        v.MinLengthAction<
          {
            name: string;
            expectedMinReaderModel?: number | undefined;
            tag: string;
            workflowResource:
              | {
                  type: "dataset";
                  id: string;
                }
              | {
                  type: "canvas";
                  id: string;
                }
              | {
                  type: "media-library";
                  id: string;
                }
              | {
                  type: "dashboard";
                  id: string;
                };
            resourceAliases?:
              | {
                  name: string;
                  resource:
                    | {
                        type: "dataset";
                        id: string;
                      }
                    | {
                        type: "canvas";
                        id: string;
                      }
                    | {
                        type: "media-library";
                        id: string;
                      }
                    | {
                        type: "dashboard";
                        id: string;
                      };
                }[]
              | undefined;
            definitions: DefinedWorkflow[];
            runtime?: RuntimeBlock | undefined;
          }[],
          1,
          "a config needs at least one deployment"
        >,
        v.CheckAction<
          {
            name: string;
            expectedMinReaderModel?: number | undefined;
            tag: string;
            workflowResource:
              | {
                  type: "dataset";
                  id: string;
                }
              | {
                  type: "canvas";
                  id: string;
                }
              | {
                  type: "media-library";
                  id: string;
                }
              | {
                  type: "dashboard";
                  id: string;
                };
            resourceAliases?:
              | {
                  name: string;
                  resource:
                    | {
                        type: "dataset";
                        id: string;
                      }
                    | {
                        type: "canvas";
                        id: string;
                      }
                    | {
                        type: "media-library";
                        id: string;
                      }
                    | {
                        type: "dashboard";
                        id: string;
                      };
                }[]
              | undefined;
            definitions: DefinedWorkflow[];
            runtime?: RuntimeBlock | undefined;
          }[],
          (
            issue: v.CheckIssue<
              {
                name: string;
                expectedMinReaderModel?: number | undefined;
                tag: string;
                workflowResource:
                  | {
                      type: "dataset";
                      id: string;
                    }
                  | {
                      type: "canvas";
                      id: string;
                    }
                  | {
                      type: "media-library";
                      id: string;
                    }
                  | {
                      type: "dashboard";
                      id: string;
                    };
                resourceAliases?:
                  | {
                      name: string;
                      resource:
                        | {
                            type: "dataset";
                            id: string;
                          }
                        | {
                            type: "canvas";
                            id: string;
                          }
                        | {
                            type: "media-library";
                            id: string;
                          }
                        | {
                            type: "dashboard";
                            id: string;
                          };
                    }[]
                  | undefined;
                definitions: DefinedWorkflow[];
                runtime?: RuntimeBlock | undefined;
              }[]
            >,
          ) => string
        >,
        v.CheckAction<
          {
            name: string;
            expectedMinReaderModel?: number | undefined;
            tag: string;
            workflowResource:
              | {
                  type: "dataset";
                  id: string;
                }
              | {
                  type: "canvas";
                  id: string;
                }
              | {
                  type: "media-library";
                  id: string;
                }
              | {
                  type: "dashboard";
                  id: string;
                };
            resourceAliases?:
              | {
                  name: string;
                  resource:
                    | {
                        type: "dataset";
                        id: string;
                      }
                    | {
                        type: "canvas";
                        id: string;
                      }
                    | {
                        type: "media-library";
                        id: string;
                      }
                    | {
                        type: "dashboard";
                        id: string;
                      };
                }[]
              | undefined;
            definitions: DefinedWorkflow[];
            runtime?: RuntimeBlock | undefined;
          }[],
          (
            issue: v.CheckIssue<
              {
                name: string;
                expectedMinReaderModel?: number | undefined;
                tag: string;
                workflowResource:
                  | {
                      type: "dataset";
                      id: string;
                    }
                  | {
                      type: "canvas";
                      id: string;
                    }
                  | {
                      type: "media-library";
                      id: string;
                    }
                  | {
                      type: "dashboard";
                      id: string;
                    };
                resourceAliases?:
                  | {
                      name: string;
                      resource:
                        | {
                            type: "dataset";
                            id: string;
                          }
                        | {
                            type: "canvas";
                            id: string;
                          }
                        | {
                            type: "media-library";
                            id: string;
                          }
                        | {
                            type: "dashboard";
                            id: string;
                          };
                    }[]
                  | undefined;
                definitions: DefinedWorkflow[];
                runtime?: RuntimeBlock | undefined;
              }[]
            >,
          ) => string
        >,
      ]
    >;
    readonly telemetry: v.OptionalSchema<
      v.CustomSchema<
        WorkflowTelemetryLogger,
        v.ErrorMessage<v.CustomIssue> | undefined
      >,
      undefined
    >;
  },
  undefined
>;

/**
 * `name` is a lake-id-segment (`^[a-z0-9][a-z0-9-]*$`) that interpolates into
 * every deployed document id (`<tag>.<name>.v<version>`) — stable identity
 * that instances pin to and subworkflows resolve by. `lifecycle: 'child'`
 * marks a spawn-only definition, instantiated by a parent via an action's
 * `spawn`, never started cold from a picker (omitted ⇒ `'standalone'`,
 * startable); advisory only — consumers filter start pickers on it (see
 * {@link isStartableDefinition}), the engine does not itself refuse a
 * `startInstance` on a `'child'` definition. `start` is meaningless
 * (deploy-rejected) on a spawn-only definition; omitted, it means
 * interactive semantics with no predicates. `predicates` are nullary named
 * conditions — each `name: groq` entry is pre-evaluated and bound as the
 * boolean `$name` var; redefining a built-in var is a deploy error, never a
 * silent shadow.
 *
 * @interface
 */
declare type WorkflowDefinition = v.InferOutput<
  typeof WorkflowDefinitionSchema
>;

declare const WorkflowDefinitionSchema: v.GenericSchema<
  WorkflowFields<FieldEntry, Stage, StartBlock>
>;

/** One deployment as loaded from a config: the floor is optional/unverified so
 *  commands that do not submit definitions can hold a missing acknowledgement.
 *  Definition-submission paths compare it with their selected definitions; authors write
 *  {@link WorkflowDeploymentInput}. */
declare type WorkflowDeployment = WorkflowConfig["deployments"][number];

/**
 * Author one deployment with a nonempty `definitions` array and a
 * {@link WorkflowResource}. Dataset resource IDs use `<projectId>.<dataset>`.
 *
 * `name` and `tag` must contain only ASCII lowercase letters, digits, and dashes,
 * starting with a letter or digit. Deployment names and `(workflowResource, tag)`
 * pairs must be unique across the config. Optional `resourceAliases` use the same
 * name grammar, with unique names within this deployment.
 *
 * `expectedMinReaderModel` is the highest reader model you have verified across
 * runtimes sharing the workflow resource. Supply a reviewed numeric literal.
 * Definition submission checks it against the required reader floor; upgrading
 * a dependency alone does not require changing it.
 *
 * `runtime` is the default hosting kind for this deployment's workflows, which
 * each workflow and effect may override. Omitted, its workflows host on
 * `'function'`.
 */
declare type WorkflowDeploymentInput = Omit<
  WorkflowDeployment,
  "expectedMinReaderModel"
> & {
  expectedMinReaderModel: number;
};

/** @inline */
declare type WorkflowFields<TField, TStage, TStart> = {
  name: string;
  semantics?: Semantic[] | undefined;
  title: string;
  description?: string | undefined;
  groups?: Group[] | undefined;
  lifecycle?: WorkflowLifecycle | undefined;
  start?: TStart | undefined;
  initialStage: string;
  fields?: TField[] | undefined;
  stages: TStage[];
  predicates?: Record<string, string> | undefined;
  roleAliases?: RoleAliases | undefined;
};

/** How instances of a definition come to exist: started standalone (the
 *  default) or spawned by a parent. `'child'` is spawn-only — see
 *  {@link isStartableDefinition}. */
declare type WorkflowLifecycle = "standalone" | "child";

/**
 * A telemetry event descriptor — a structural mirror of `@sanity/telemetry`'s
 * `DefinedTelemetryLog`, so shells hand these straight to their store logger.
 */
declare interface WorkflowTelemetryEvent<Data = void> {
  type: "log";
  /** Matched verbatim downstream — frozen once shipped. */
  name: string;
  /** Bumped on any payload shape change; the name never changes. */
  version: number;
  /** Optional to match the real package's event shape, so an event built
   *  with the real `defineEvent` flows into this seam; the engine's own
   *  vocabulary always sets it. */
  description?: string;
  /** Advisory volume cap enforced by the shell's store — at most one
   *  submission per interval (ms). */
  maxSampleRate?: number;
  /** Type-level payload carrier — never set at runtime (the real package's
   *  `defineEvent` leaves it unset the same way). */
  schema: Data;
}

/**
 * The logger surface the engine emits through — the `log` subset of
 * `@sanity/telemetry`'s `TelemetryLogger`, so any real logger satisfies it.
 */
declare interface WorkflowTelemetryLogger {
  log<Data>(event: WorkflowTelemetryEvent<Data>, data: Data): void;
  log(event: WorkflowTelemetryEvent<void>): void;
}

export {};
