import { analyzeCondition } from "@sanity/groq-condition-describe";
import { AtomInsight } from "@sanity/groq-condition-describe";
import { atomReadsDataset } from "@sanity/groq-condition-describe";
import { AtomRequirement } from "@sanity/groq-condition-describe";
import { checklistLines as checklistLines_2 } from "@sanity/groq-condition-describe";
import { ComparisonOp } from "@sanity/groq-condition-describe";
import { Condition as Condition_2 } from "@sanity/groq-condition-describe";
import { ConditionAnalysis } from "@sanity/groq-condition-describe";
import { ConditionAtom } from "@sanity/groq-condition-describe";
import { ConditionClause } from "@sanity/groq-condition-describe";
import { ConditionDescription } from "@sanity/groq-condition-describe";
import { ConditionInsight } from "@sanity/groq-condition-describe";
import { ConditionOutcome } from "@sanity/groq-condition-describe";
import { ConditionRead } from "@sanity/groq-condition-describe";
import { DescribedClause } from "@sanity/groq-condition-describe";
import { explainCondition } from "@sanity/groq-condition-describe";
import { ExplainConditionArgs } from "@sanity/groq-condition-describe";
import { formatRead } from "@sanity/groq-condition-describe";
import { guillemets } from "@sanity/groq-condition-describe";
import { humanize } from "@sanity/groq-condition-describe";
import { InsightPhrase } from "@sanity/groq-condition-describe";
import { isComparisonOp } from "@sanity/groq-condition-describe";
import { MAX_COUNTERFACTUAL_INDEX } from "@sanity/groq-condition-describe";
import { NEUTRAL_MARK } from "@sanity/groq-condition-describe";
import { OUTCOME_MARKS } from "@sanity/groq-condition-describe";
import { quoted } from "@sanity/groq-condition-describe";
import type { SanityDocument } from "@sanity/types";
import { ScopeAssignment } from "@sanity/groq-condition-describe";
import { sentenceCase } from "@sanity/groq-condition-describe";
import * as v from "valibot";
import { whatIfCondition } from "@sanity/groq-condition-describe";
import { WhatIfOutcome } from "@sanity/groq-condition-describe";
import { withAssignment } from "@sanity/groq-condition-describe";

export declare interface AbortInstanceArgs extends DedupableOperationArgs {
  /** Free-text reason — surfaces on the `workflow.history.aborted` entry for audit. */
  reason?: string;
}

/** The free-text reason recorded on the aborted history entry, if any. */
export declare function abortReason(
  instance: Pick<WorkflowInstance, "history">,
): string | undefined;

/**
 * The structured half of applicability: does the definition's subject entry
 * ({@link isSubjectEntry} — the `subject` kind, workflow scope, at most one
 * by deploy invariant) accept `documentType`? The kind is the discriminator,
 * so a definition surfaces from its SUBJECT's document picker and nowhere
 * else; the start dialog collects the remaining required entries (their
 * fail-hard validation backstops). A definition with no subject entry takes no
 * subject and never matches. A subject without `types` accepts any type that is
 * not a system document ({@link isSystemDocumentType}). Naming a reserved
 * `sanity.` or `system.` type in `types` accepts it, but naming a type the engine
 * owns and writes for itself never does.
 * Cheap and indexable — no GROQ evaluation — so a consumer can pre-filter
 * before loading document content.
 */
export declare function acceptsDocumentType(
  definition: Pick<ApplicabilitySource, "fields">,
  documentType: string,
): boolean;

/** A parsed deployment after its reader-model acknowledgement has been
 *  validated against the definitions a command will submit. */
export declare type AcknowledgedWorkflowDeployment = WorkflowDeployment & {
  expectedMinReaderModel: number;
};

/**
 * The URL path a resource's ACL is served at — where the engine fetches an
 * actor's grants for that resource (and the canonical encoding of the shape
 * a caller passes as `grantsFromPath`). Known for `dataset`
 * (`/projects/<id>/datasets/<ds>/acl`) and `canvas`
 * (`/canvases/<resourceId>/acl`); `undefined` for resource types without a
 * known grants endpoint, so a caller can degrade open (no grants → no
 * advisory forecast) instead of guessing a path.
 */
export declare function aclPathForResource(
  res: Extract<
    WorkflowResource,
    {
      type: "dataset" | "canvas";
    }
  >,
): string;

export declare function aclPathForResource(
  res: WorkflowResource,
): string | undefined;

/**
 * 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
 */
export declare type Action = ActionFields<Op, string[], Effect> & {
  roles?: string[] | undefined;
};

export declare const ACTION_SEMANTICS: readonly [
  "decision.accept",
  "decision.decline",
  "signal.positive",
  "signal.caution",
  "signal.critical",
];

/**
 * The engine's per-reason detail fragment — the same wording
 * {@link ActionDisabledError} embeds in its message. Exported so a dev-facing
 * host (the CLI) renders the one canonical detail instead of maintaining a
 * parallel per-kind copy. Covers every reason but `mutation-guard-denied`,
 * which escalates to {@link MutationGuardDeniedError} and renders through
 * {@link deniedGuardLabels}.
 */
export declare function actionDisabledDetail(
  reason: ActionDisabledReason,
): string;

/**
 * Thrown by `fireAction` when the requested action's verdict is
 * `allowed: false` for any reason other than a guard denial (that one is
 * {@link MutationGuardDeniedError} across all verbs). Carries the structured
 * verdict so UIs render the same reason they would have shown on the
 * disabled control, instead of parsing a string.
 */
export declare class ActionDisabledError extends WorkflowError<"action-disabled"> {
  readonly reason: ActionDisabledReason;
  readonly activity: ActivityName;
  readonly action: ActionName;
  constructor(args: {
    activity: ActivityName;
    action: ActionName;
    reason: ActionDisabledReason;
  });
}

/** The verdicts {@link ActionDisabledError} can carry — every {@link DisabledReason}
 *  except `mutation-guard-denied`, which escalates to {@link MutationGuardDeniedError}. */
export declare type ActionDisabledReason = Exclude<
  DisabledReason,
  {
    kind: "mutation-guard-denied";
  }
>;

export declare interface ActionEvaluation {
  action: Action;
  /** The action's advisory workflow meaning, unchanged from its definition. */
  semantics?: ActionSemantic[] | undefined;
  allowed: boolean;
  /**
   * The action is cascade-fired (`when`): the engine fires it on truth, it
   * is never fireAction-able, and a consumer must not render it as a
   * button — narrate it ("will escalate when overdue") via `whenInsight`.
   * Always set together with the `cascade-fired` `disabledReason` — either
   * check suffices; the flag is the ergonomic spelling.
   */
  triggered?: true;
  /** Present iff `allowed === false`. The first failing gate wins. */
  disabledReason?: DisabledReason;
  /**
   * What firing this action would do to the flow RIGHT NOW — the fire
   * replayed in memory on the engine's own machinery (ops, the triggered
   * fixpoint, transition selection) against this projection's state, and
   * conditional on the commit landing (rejectability is `allowed` /
   * `disabledReason`'s story). Omitted when the consequence depends on
   * inputs the projection doesn't hold — caller params, a spawn's
   * dataset-driven fan-out, a terminal instance, a stage visit whose
   * entries have diverged from the pinned definition — and on cascade-fired
   * actions, which are never a caller's to fire. Advisory like every
   * derived verdict: a placement/phrasing hint, never a gate.
   */
  firing?: FiringConsequence;
  /** Derived state of the action's `filter` gate — why it holds or fails,
   *  atom by atom. Present iff the action declares a filter. */
  insight?: ConditionInsight;
  /** Derived state of a cascade-fired action's `when` trigger — what would
   *  fire it. Present iff the action declares `when`. */
  whenInsight?: ConditionInsight;
  /** A canonical `$assigned` filter leg withheld this absent action. The
   *  action still follows filter-existence semantics; this metadata lets the
   *  owning activity explain who currently holds the work. */
  holderGate?: {
    holders: Assignee[];
  };
}

/** @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;
};

export declare type ActionName = string;

/**
 * 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
 */
export 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
    >,
  ]
>;

/**
 * Thrown when caller-supplied params don't satisfy the action's
 * declared `params[]` — missing required fields or wrong primitive
 * type. The action does not commit; the engine has not mutated state.
 */
export declare class ActionParamsInvalidError extends WorkflowError<"action-params-invalid"> {
  readonly action: string;
  readonly activity: ActivityName;
  readonly issues: {
    param: string;
    reason: string;
  }[];
  constructor(args: {
    action: string;
    activity: ActivityName;
    issues: {
      param: string;
      reason: string;
    }[];
  });
}

/**
 * The three-way rendering verdict every surface applies to an action:
 * `absent` — its `filter` failed, so it does not exist for this actor/visit
 * (GROQ existence semantics; never even a disabled affordance). `automation` —
 * cascade-fired, so the engine's cascade is its only firing path (narrate it,
 * never render a fire affordance). `button` — fireable: enabled when
 * `allowed`, otherwise disabled WITH its {@link DisabledReason} shown.
 * Structural over the shared verdict fields so {@link ActionEvaluation} and
 * `AvailableAction` both qualify; filter-existence dominates automation, the
 * same order the engine's own verdicts apply.
 */
export declare function actionRendering(action: {
  triggered?: true;
  disabledReason?:
    | {
        kind: DisabledReason["kind"];
      }
    | undefined;
}): "absent" | "automation" | "button";

export declare type ActionSemantic = DecisionSemantic | Semantic;

/** The per-action verdict shape shared by every projection: {@link availableActions} flattens it, a per-activity consumer (e.g. the MCP) maps it directly — both must stay on this one builder. */
export declare function actionVerdict(
  activity: ActivityEvaluation,
  action: ActionEvaluation,
): AvailableAction;

/** The members that own work after direct-user membership shadows every role route. */
export declare function activeAssignmentMembers(
  members: readonly Assignee[],
): readonly Assignee[];

/**
 * 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
 */
export declare type Activity = ActivityFields<
  FieldEntry,
  Action,
  ManualTarget,
  string[]
>;

/**
 * Activity-kind labels — the per-kind renderer's heading + tooltip. Kept OUT of
 * the combined {@link DISPLAY} map: kinds are a classification axis a consumer
 * looks up deliberately, not a `_type`, and `"service"` collides with the
 * same-named {@link DRIVER_KIND_DISPLAY} key.
 */
export declare const ACTIVITY_KIND_DISPLAY: {
  user: {
    title: string;
    description: string;
  };
  service: {
    title: string;
    description: string;
  };
  script: {
    title: string;
    description: string;
  };
  manual: {
    title: string;
    description: string;
  };
  receive: {
    title: string;
    description: string;
  };
};

/**
 * BPMN-aligned classification of an activity by its EXECUTOR. Purely
 * advisory and always DERIVED from the activity's shape (`target` marks
 * off-system manual work, action shapes decide the rest) — it changes no
 * gating or runtime.
 */
export declare const ACTIVITY_KINDS: readonly [
  "user",
  "service",
  "script",
  "manual",
  "receive",
];

/** The activity slice of a stage rollup — total by construction, like
 *  {@link stageAutonomyOf}. */
export declare function activityAutonomyOf(
  stageAutonomy: StageAutonomy,
  activityName: string,
): AutonomyAnswer;

/** An activity's gates, each described — absent keys mirror undeclared gates. */
export declare interface ActivityDescription {
  requirements?: Record<string, ConditionDescription>;
  filter?: ConditionDescription;
}

export declare interface ActivityEntry {
  _key: string;
  /** Matches the authoring `Activity.name`. */
  name: ActivityName;
  status: ActivityStatus;
  startedAt?: string;
  completedAt?: string;
  completedBy?: string;
  /**
   * Names of this activity's cascade-fired actions that have fired during
   * THIS stage visit — the once-per-visit ledger. Level-triggered: a name
   * lands here on the first evaluation that finds its `when` true and never
   * re-fires within the visit; stage re-entry rebuilds entries, so re-arming
   * on a new visit is structural. Absent until the first trigger fires.
   */
  firedActions?: string[];
  filterEvaluation?: {
    at: string;
    truthy: boolean;
    /**
     * The filter evaluated to GROQ `null` — a referenced operand was missing
     * or incomparable, so it couldn't be decided. The engine fails closed
     * (keeps the activity in scope) rather than reading this as a deliberate
     * `false`; `truthy` is `false` here but the activity is NOT skipped.
     */
    unevaluable?: boolean;
    detail?: string;
  };
  /** Activity-scoped resolved field entries. Absent until the engine writes to it. */
  fields?: ResolvedFieldEntry[];
}

export declare interface ActivityEvaluation {
  activity: Activity;
  /** The activity's advisory workflow meaning, unchanged from its definition. */
  semantics?: Semantic[] | undefined;
  status: ActivityStatus;
  /**
   * The activity's shape-derived {@link ActivityKind}. Advisory: a label so a
   * consumer can render each activity as what it is (`user` / `service` /
   * `script` / `manual` / `receive`).
   */
  kind: ActivityKind;
  /**
   * Who, if anyone, fires the activity's actions — derived from its shape
   * alone: `autonomous` (every action cascade-fired), `interactive` (only
   * fireAction-fired actions), `off-system` (`target` present), or `hybrid`.
   */
  classification: ExecutorClassification;
  /**
   * The causal refinement of {@link ActivityEvaluation.classification}:
   * whether this activity completes without a caller, derived by
   * {@link deriveWorkflowAutonomy}'s dataflow over the definition — a
   * mechanically `autonomous` activity whose triggers only read
   * caller-written state still reports the caller it waits on.
   */
  autonomy: AutonomyAnswer;
  /** Whether this activity is the current actor's responsibility right now. */
  pendingOnActor: boolean;
  /**
   * The stage-entry `filter` scoped this activity out of the current visit:
   * its entry is `skipped` and never started, so it does not exist for this
   * visit — surfaces hide it entirely (an action-resolved `skipped` was real,
   * started work and stays visible). Derived via {@link isFilterScopedOut},
   * stamped here so consumers never re-join entry state to compute it.
   */
  scopedOut: boolean;
  /**
   * Unmet authored activity requirements and required-reference readability checks.
   * Present when at least one is unmet. Required-reference descriptors use
   * `field:<name>` and the field's declared title when available.
   */
  unmetRequirements?: RequirementDescriptor[];
  /** Derived state per authored requirement, keyed by its declared name.
   * Present when the activity declares requirements. Unmet authored requirements
   * appear in `unmetRequirements`; required-reference checks have no insight entry. */
  requirementInsights?: Record<string, ConditionInsight>;
  /** Derived state of the activity's `filter` existence gate. Present iff
   *  declared. Advisory read: the engine's stage entry owns the gate itself. */
  filterInsight?: ConditionInsight;
  actions: ActionEvaluation[];
}

/** @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;
};

export declare type ActivityKind = (typeof ACTIVITY_KINDS)[number];

export declare type ActivityName = string;

/**
 * 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}.
 */
export declare type ActivityStatus = "active" | "done" | "skipped" | "failed";

/**
 * Who is acting — advisory provenance, not an authenticated principal. The
 * engine always resolves it from the client's token; there is no way to pass
 * or synthesize one. The stamp is still advisory: nothing re-verifies it at
 * read time, and only the lake's own token identity is authenticated — hard
 * enforcement lives there.
 *
 * `id` is the account-global user id — the one identity namespace that is
 * stable across projects and org-level resources. The engine takes it from the
 * first route that can answer for the token: an id either host's `/users/me`
 * already carries in account-global form (the id itself, or the one embedded in
 * an `e-` principal), and otherwise the project's own user directory
 * (`sanityUserId`) — the route a session scoped to a single project depends on,
 * since no global record exists for it. Robot tokens carry a single universal
 * id, so for them `id` equals what every host returns. Instances written before
 * ids were namespace-classified carry the workflow resource's local principal id
 * in `id` instead; readers interpret those through the prefix classifier in
 * `core/identity.ts` with the document's home resource as the implied scope.
 */
export declare interface Actor {
  kind: ActorKind;
  id: string;
  /**
   * Free-form role names — typically a copy of Sanity's `user.roles[].name`
   * for the token behind the call, as the workflow resource's host reports
   * them (project roles for dataset resources). The engine treats these as
   * opaque strings, matched by literal membership: `Action.roles` and
   * `assignees` roles OR-match against this list. There is no actor-side
   * wildcard — a `"*"` here is just a literal string and matches nothing on
   * its own.
   *
   * To let one role satisfy a gate it doesn't literally name — e.g. an
   * `administrator` satisfying a narrower gate, or one deployment's role
   * standing in for another's — declare the definition's `roleAliases`
   * "can be fulfilled by" map; it widens the REQUIRED side, never the
   * actor's roles.
   */
  roles?: string[];
  onBehalfOf?: string;
}

/**
 * WHO is acting: a human, an LLM, or automated machinery. The `system` kind
 * covers both the engine's own housekeeping and external services;
 * {@link DriverKind} splits that for the audit-trail glyph.
 */
export declare const ACTOR_KINDS: readonly ["person", "agent", "system"];

/**
 * Checks whether an actor role fulfills `required`, directly or through one
 * level of aliases. Pass `roleAliases` from a definition returned by
 * {@link define.defineWorkflow | defineWorkflow}; its universal aliases are
 * normalized. A raw authored `"*"` entry is not expanded here.
 * This role check is advisory.
 */
export declare function actorFulfillsRole({
  actorRoles,
  required,
  aliases,
}: {
  actorRoles: readonly string[] | undefined;
  required: string;
  aliases: RoleAliases | undefined;
}): boolean;

export declare type ActorKind = (typeof ACTOR_KINDS)[number];

/** Assignment ownership for runtime actors, with authorization aliases applied to role members. */
export declare function actorMatchesAssignment(args: {
  actor: Actor | undefined;
  members: readonly Assignee[];
  roleAliases?: RoleAliases | undefined;
}): boolean;

export declare type ActorResolution<User> =
  | {
      readonly status: "resolved";
      readonly actor: PersonActor;
      readonly user: User;
    }
  | {
      readonly status: "missing";
      readonly actor: PersonActor;
    }
  | {
      readonly status: "inaccessible";
      readonly actor: PersonActor;
      readonly cause?: unknown;
    }
  | {
      readonly status: "not-person";
      readonly actor: Actor;
    };

/** Missing-reference evidence accompanying another primary fault, for workspace renderers only.
 * @internal
 */
export declare function _additionalMissingDocuments(
  diagnosis: Diagnosis,
  documents: MissingDocument[] | undefined,
): MissingDocument[];

/**
 * @internal `instant` shifted by `ms`, normalised to UTC ISO-8601. Shared with
 * the Blueprints runtime; not a supported consumer API.
 */
export declare function _addMs(instant: string, ms: number): string;

export { analyzeCondition };

/** Lake `identity()` sentinel for unauthenticated callers. */
export declare const ANONYMOUS_IDENTITY = "<anonymous>";

/** The definition surface the start contexts read — structural, so authored,
 *  stored, and deployed definition shapes all fit. `name` binds
 *  `$definition` and names the definition in a broken-predicate error. */
export declare interface ApplicabilitySource {
  name?: string | undefined;
  lifecycle?: WorkflowLifecycle | undefined;
  fields?: FieldEntry[] | undefined;
  start?:
    | {
        kind?: StartKind | undefined;
        filter?: string | undefined;
        requirements?: StartRequirement[] | undefined;
      }
    | undefined;
}

/**
 * Filter `definitions` to the ones applicable to `document`, preserving
 * input order — surface ALL matches; the engine ranks nothing.
 */
export declare function applicableDefinitions<
  T extends ApplicabilitySource,
>(args: {
  definitions: readonly T[];
  document: CandidateDocument;
  /** Caller-side filter bindings, shared by every definition's evaluation. */
  scope?: StartScope;
}): Promise<T[]>;

/**
 * Throws {@link ModelVersionAheadError} only when the document's reader floor exceeds
 * {@link DATA_MODEL_VERSION}. A doc from a NEWER engine whose changes were purely additive
 * keeps its old (lower) floor and still reads fine — only reader-floor-raising changes block a read.
 */
export declare function assertReadableModel<
  T extends {
    _id: string;
  },
>(doc: T): T;

export declare function assertReaderModelAcknowledgement(
  expectedMinReaderModel: unknown,
  options: {
    requiredMinReaderModel: number;
    context?: string;
  },
): asserts expectedMinReaderModel is number;

/**
 * One member of an `assignee` or `assignees` field. For a user member, pass a
 * human's account-global `sanityUserId`, not a project-scoped user ID. Robot
 * IDs are rejected.
 *
 * A role member identifies a project role, not an individual {@link Actor}.
 * Direct user members take ownership ahead of role members. Role aliases apply
 * to `$assigned` authorization, but inbox routing uses literal project roles.
 */
export declare type Assignee =
  | {
      type: "user";
      id: string;
    }
  | {
      type: "role";
      role: string;
    };

export declare interface AssignmentIdentity {
  readonly userId: string;
  readonly roles: readonly string[];
}

/** @inline */
declare type AssignmentInstance = Pick<
  WorkflowInstance,
  "currentStage" | "stages"
>;

export declare type AssignmentMatch = "user" | "role" | undefined;

/** Whether an identity owns the assignment directly or through a literal project role. */
export declare function assignmentMatch(
  members: readonly Assignee[],
  identity: AssignmentIdentity,
): AssignmentMatch;

/** Every member stored in assignment entries, preserving field and member order. */
export declare function assignmentMembers(
  entries: readonly ResolvedFieldEntry[],
): readonly Assignee[];

export declare function assignmentPrefilter(
  assignment: NonNullable<InstancesQueryFilter["assignment"]>,
  params: Record<string, string | string[]>,
): string;

export declare type AssignmentState = "unrouted" | "routed" | "held";

/** Classify one assignment slot by whether it has no route, role routes, or a user holder. */
export declare function assignmentState(
  members: readonly Assignee[],
): AssignmentState;

export declare interface AssignmentStateCounts {
  readonly unrouted: number;
  readonly routed: number;
  readonly held: number;
}

/** Viewer-scoped assignment counts at assignment-slot grain. Unrouted work is
 *  visible to every viewer; routed and held count only work offered to or
 *  held by the supplied identity. */
export declare function assignmentStateCounts(
  assignments: readonly (readonly Assignee[])[],
  identity: AssignmentIdentity,
): AssignmentStateCounts;

export { AtomInsight };

export { atomReadsDataset };

export { AtomRequirement };

/**
 * Persisted document and effect-queue `_type` discriminators.
 */
export declare const AUTHORING_DISPLAY: {
  pendingEffect: {
    title: string;
    description: string;
  };
  "pendingEffect.claim": {
    title: string;
    description: string;
  };
  "sanity.workflow.definition": {
    title: string;
    description: string;
  };
  "sanity.workflow.instance": {
    title: string;
    description: string;
  };
};

/**
 * 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.
 */
export declare type AuthoringAction = AuthoringRawAction;

/** @interface */
export 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.
 */
export 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
 */
export declare type AuthoringEffect = EffectFields<AuthoringEffectRetry> & {
  runtime?: EffectRuntimeBlock | undefined;
};

/** An {@link EffectRetry} whose omitted `kind` defaults to `engine`. */
export 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.
 */
export declare type AuthoringFieldEntry =
  | AuthoringRawFieldEntry
  | TodoListField
  | NotesField;

/**
 * A field reference with `scope` optional; desugar resolves it lexically
 * (activity → stage → workflow) into {@link StoredFieldRef}.
 *
 * @interface
 */
export 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
 */
export 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}. */
export 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.
 */
export 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
>;

/** @inline */
declare type AuthoringRuntimeKey = "runtime";

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

/** A {@link StartBlock} whose omitted `kind` defaults to `interactive`. */
export 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.
 */
export 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
 */
export declare type AuthoringWorkflow = WorkflowFields<
  AuthoringFieldEntry,
  AuthoringStage,
  AuthoringStartBlock
> & {
  runtime?: RuntimeBlock | undefined;
};

/** The narratable answer at one rollup level: the verdict plus what it waits
 *  on. `waitsOn` may be non-empty on a `yes` verdict (an effect settle is a
 *  wait the engine resolves itself) — consumers choose what to surface. */
export declare interface AutonomyAnswer {
  completesWithoutCaller: AutonomyVerdict;
  waitsOn: AutonomyWait[];
}

/** The workflow-level autonomy narrative: fully self-running, or the stages
 *  where a run is held. */
export declare function autonomySummary(
  autonomy: WorkflowAutonomy,
  ctx: DescribeContext,
): InsightPhrase;

/**
 * Whether a node resolves without a caller: `yes` — engine machinery alone
 * (the cascade plus the host's effect drain/ticker) gets it there; `no` —
 * someone outside the engine must act (a caller fires an action, an editor
 * writes a field or content); `conditional` — it may resolve either way
 * depending on values the analysis can't see (start-time seeds, mixed
 * alternative routes, unresolvable children, cyclic gates).
 *
 * `yes` still leans on the host: effects settle only if a drain runs, and
 * time only passes for a ticker. A cascade-fired action's `roles` pin is a
 * DEPENDENCY, not an assumption — the runtime leaves a pinned trigger armed
 * until a capable token cascades, and whether the deployment's tokens fulfil
 * the pin is configuration the analysis can't see, so a pinned trigger
 * reports `conditional` with the pin as its wait.
 */
export declare type AutonomyVerdict = "yes" | "no" | "conditional";

/** One narratable dependency a non-`yes` verdict rests on. */
export declare type AutonomyWait =
  | {
      kind: "caller-action";
      stage: string;
      activity: string;
      action: string;
      roles?: string[];
    }
  | {
      kind: "execute-pin";
      stage: string;
      activity: string;
      action: string;
      roles: string[];
    }
  | {
      kind: "editor-field";
      field: string;
    }
  | {
      kind: "editor-content";
      condition: Condition;
    }
  | {
      kind: "effect";
      effect: string;
    }
  | {
      kind: "start-input";
      field: string;
    }
  | {
      kind: "context";
      key?: string;
    }
  | {
      kind: "subworkflow";
      definition: string;
      resolved: boolean;
    }
  | {
      kind: "unwritten-field";
      field: string;
      handlerPossible: boolean;
    };

export declare interface AvailableAction {
  activity: string;
  activityStatus: ActivityStatus;
  action: string;
  title: string | undefined;
  allowed: boolean;
  disabledReason: DisabledReason | undefined;
  params: ActionParam[];
}

/** Excludes a `scopedOut` activity's actions, matching the same split every other surface applies to filter-scoped-out activities. */
export declare function availableActions(
  activities: ActivityEvaluation[],
): AvailableAction[];

/** Pairs the projected actions with the evaluation they came from, so a consumer reads instance/stage context without a second call. */
export declare interface AvailableActionsResult {
  evaluation: WorkflowEvaluation;
  actions: AvailableAction[];
}

/** Builds the start payload's field rows from caller values: accepts only
 *  declared `input`-sourced entries and throws on an unknown or non-input
 *  name. Structural validation only — the engine repeats value-kind
 *  validation at its own start boundary, not here. */
export declare function buildInitialFields({
  declared,
  values,
}: {
  declared: Pick<FieldEntry, "type" | "name" | "initialValue">[];
  values: Record<string, unknown>;
}): InitialFieldValue[];

/**
 * Rewrites each doc's `_id` and every nested `_ref` field to GDR URI form,
 * recursing through objects/arrays; already-URI `_ref`s pass through unchanged.
 */
export declare function buildSnapshot(args: {
  docs: LoadedDoc[];
}): HydratedSnapshot;

/**
 * A LOADED candidate document. Applicability evaluates content, so a ref or
 * bare id is not enough: the doc must carry its schema `_type` plus whatever
 * attributes `start.filter` predicates read — under whatever perspective
 * the caller loaded it with.
 */
export declare interface CandidateDocument {
  _type: string;
  [key: string]: unknown;
}

/**
 * Thrown when hops on an instance fail to stabilise within
 * {@link CascadeLimitError.limit} moves — the signature of a runaway
 * cascade. The classic cause is two stages whose transition `when`s
 * stay simultaneously satisfied (e.g. an `op.field.set` lands a value
 * that trips the very trigger that fired, and nothing ever clears it),
 * so the engine flip-flops and would otherwise write revisions forever.
 *
 * The cascade aborts at the limit rather than the engine hanging; the
 * instance is left at whatever stage the last completed pass reached.
 */
export declare class CascadeLimitError extends WorkflowError<"cascade-limit"> {
  readonly instanceId: string;
  readonly limit: number;
  constructor(args: { instanceId: string; limit: number });
}

/** Flatten a description to indented English lines (✓ / ✗ / ? per outcome). */
export declare const checklistLines: typeof checklistLines_2;

export declare interface ChildrenArgs extends InstanceRefArgs {
  /** Restrict to children spawned by this activity on the parent. */
  activity?: string;
}

export 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`.
 */
export declare interface ChoiceOptions {
  list: ChoiceOption[];
}

export declare type ChoiceValue = string | number;

export declare interface ClassifiedPrincipal {
  namespace: PrincipalNamespace;
  /**
   * The account-global id when the string itself carries it: the id verbatim
   * for `global` and `robot` (a robot's single id IS its universal identity),
   * the embedded global id for `e-` project ids. Absent for plain `project`
   * ids (resolving those needs the project-users directory), sentinels, and
   * unknowns.
   */
  globalId?: string;
}

/**
 * Classify a bare principal-id string by its namespace. Total — never
 * throws; ids that fit no known form come back `unknown` so the caller
 * decides how loud to be.
 */
export declare function classifyPrincipalId(id: string): ClassifiedPrincipal;

/**
 * The `@sanity/client`-config fragment that addresses a {@link WorkflowResource}
 * — the one home for the dataset-vs-resource branch every client-building host
 * (CLI, MCP) would otherwise reimplement. A dataset addresses via the classic
 * `{projectId, dataset}` config (the proven path, and it keeps
 * `client.listen()` on well-trodden ground); the other resource types have no
 * projectId/dataset split, so they pass through as a `resource` directly.
 *
 * Returns a plain fragment (not a client) so the engine stays free of a
 * runtime `@sanity/client` dependency — callers spread it into their own
 * `createClient` call alongside their auth/host params.
 */
export declare function clientConfigFromResource(res: WorkflowResource):
  | {
      projectId: string;
      dataset: string;
    }
  | {
      resource: WorkflowResource;
    };

/** The total GDR router — every parsed GDR
 *  resolves to a client, or the router throws. */
export declare type ClientForGdr = (parsed: ParsedGdr) => WorkflowClient;

/** Stored-resource dereferencing for write pre-flights and host previews. */
export declare function clientGuardDereference(
  client: Pick<WorkflowClient, "getDocument">,
): GuardDereference;

/** @internal Shared member rows for workspace adapters; not a supported consumer API. */
export declare interface _ClientProjectMember {
  readonly id: string;
  readonly isRobot?: boolean;
  readonly roles?: unknown;
  readonly [key: string]: unknown;
}

/** Native project-user response returned by Sanity's project API. */
export declare interface ClientProjectUser {
  readonly id: string;
  /**
   * The person's account-global user id — the canonical identity every
   * workflow value stores. This is the sanctioned bridge between a
   * project's local principal namespace and the global one; surfaces use
   * it to emit assignment values from project-member displays.
   */
  readonly sanityUserId?: string;
  readonly displayName?: string;
  readonly email?: string;
  readonly imageUrl?: string | null;
  /**
   * Display only. Both spellings exist because the two project-user
   * endpoints disagree on which they answer — read through
   * {@link userLoginProvider} rather than picking one.
   */
  readonly provider?: string;
  readonly loginProvider?: string;
  readonly [key: string]: unknown;
}

/** Project-user directory served straight from the engine's own client — the
 *  project API's user endpoints, no host adapter. */
export declare function clientProjectUserDirectory(
  client: WorkflowClient,
  projectId: string,
): ProjectUserDirectory<ClientProjectUser>;

/**
 * The engine's single source of "now".
 *
 * A {@link Clock} returns the current time as an ISO-8601 string. Each
 * verb-driven operation takes ONE reading and threads it everywhere —
 * `$now` in filters, the `now` op-source, every history `at` stamp,
 * `completedAt`, `enteredAt`, `lastChangedAt` — so an eval pass agrees on
 * the time and a frozen clock produces a deterministic instance.
 *
 * A clock is injected ONCE, never per call: production omits it entirely
 * (defaults to {@link wallClock}); deterministic harnesses pass
 * `createEngine({ clock })`, and tests use `@sanity/workflow-engine-test`'s
 * `setNow` / `advance` (the bench wraps the same seam). It is deliberately
 * NOT a field on the public per-verb `*Args` — the raw `workflow.*` verbs
 * accept it only through the {@link Clocked} composition seam, so prod code
 * can't trivially override engine time by accident.
 *
 * `drainEffects` and `sweepStaleClaims` read the same engine clock for
 * their claim / lease-expiry stamps, so lease timing is deterministic
 * under a pinned clock too.
 */
export declare type Clock = () => string;

/**
 * Optional clock-injection field on the raw `workflow.*` verbs. It is
 * exported because those verbs expose this composition helper in their
 * public signatures, but production normally injects a clock once via
 * `createEngine({ clock })`, and the test bench controls it through
 * `setNow` / `advance`. The documented `*Args` interfaces omit `clock`
 * because it is infrastructure context, not an everyday per-call option.
 */
export declare type Clocked<T> = T & {
  clock?: Clock;
};

export declare interface CommitEffectOpsArgs extends DedupableOperationArgs {
  /** The `_key` of the pending effect being reported on. */
  effectKey: string;
  /**
   * Required here, unlike the other dedupable verbs: the engine cannot
   * assume a supplied field op is idempotent, so every mid-dispatch report
   * must be retry-safe. (The runtime check remains for untyped callers.)
   */
  idempotencyKey: string;
  /**
   * The exact-claim identity handed to the reporting dispatch. The commit
   * re-reads the instance and rejects (writing nothing) unless the entry's
   * live claim carries this token unexpired — so an expired, released, or
   * superseded handler cannot update state. A successful commit renews the
   * claim's lease.
   */
  claimToken: string;
  /**
   * Mid-dispatch field state, `field.*` ops only — validated and applied
   * exactly like completion ops (same applier, same target resolution
   * against the current open stage, workflow-/stage-scope only, never
   * `status.set`). Must be non-empty. Completion ops remain the final
   * atomic result committed when the handler returns; these are separately
   * committed and observable before it.
   */
  ops: FieldOp[];
  /** Lease duration the successful commit renews the claim to — the
   *  drain's `effects.leaseMs`. Default `DEFAULT_EFFECT_LEASE_MS` (5 min). */
  leaseMs?: number;
}

export declare interface CommitOpsRequest {
  ops: FieldOp[];
  idempotencyKey: string;
}

export { ComparisonOp };

/**
 * A compiled lake read — what the engine's query builders return and what a
 * reactive adapter's live-query store subscribes with, so the stateless and
 * reactive paths run the same GROQ.
 */
export declare interface CompiledQuery {
  query: string;
  params: Record<string, string | string[]>;
}

/**
 * Translate one authored guard into the temporary documents that preview its
 * eventual Content Lake enforcement.
 * Content edits target draft ids, instance updates keep the instance id, and
 * publish or unpublish targets published ids using the Lake operations those
 * lifecycle writes perform. A mixed guard emits one document per id space so
 * its action and id facets never form an unintended cross-product.
 */
export declare function compileGuards(
  args: CompileGuardsArgs,
): [MutationGuardDoc, ...MutationGuardDoc[]];

export declare interface CompileGuardsArgs extends MutationGuardBody {
  id: string;
}

/**
 * Completion is FIRST-WRITER-WINS: reporting on an entry that already
 * settled throws `EffectNotFoundError`, whose `settled` field says how it
 * settled — another party's completion (a lease takeover, a manual
 * recovery), or an abort cancelling the entry before dispatch. A completer
 * on a retrying transport (webhook redelivery, queue, cron) should pass
 * {@link DedupableOperationArgs.idempotencyKey} — its own lost-response
 * retries then replay as `changed: false` instead of throwing.
 */
export declare interface CompleteEffectArgs extends DedupableOperationArgs {
  /** The `_key` of the pending effect being reported on. */
  effectKey: string;
  status: EffectCompletionStatus;
  /**
   * Named values produced by the effect — recorded on the run's
   * `effectHistory` row and read downstream as
   * `$effects['<effect name>'].<output>` (the latest completed run per
   * effect name wins). Validated against the effect's declared `outputs`
   * allowlist; each value may be any JSON.
   */
  outputs?: Record<string, unknown>;
  /**
   * The state half of the effect: `field.*` ops to apply in the completion
   * commit, computed from the effect's real result (e.g. a `field.set` of a
   * created doc's ref, or the screened outcome an activity/stage gate then reads).
   * Run through the same op applier as an action's field ops — a target must
   * resolve in the current open stage and its value must match the field's kind;
   * workflow- and stage-scope targets only. Deliberately NOT `status.set`: an
   * effect is outside the activity's awaiting, so it reports its result as field
   * state and lets the gate decide the activity/stage outcome — it never flips an
   * activity status itself (same boundary a transition draws). Only valid with
   * `status: 'done'` (a failed completion carries no ops). Not actor-gated.
   */
  ops?: FieldOp[];
  detail?: string;
  error?: {
    message: string;
    stack?: string;
  };
  durationMs?: number;
}

/** Compare each definition against the latest deployed version of its name. */
export declare function computeDiffEntries<
  T extends WorkflowDefinitionInput<T>,
>({
  client,
  defs,
  target,
}: {
  client: Pick<WorkflowClient, "fetch">;
  defs: T[];
  target: DeployTarget;
}): Promise<DiffEntry[]>;

/**
 * Thrown when one automatic cascade hop loses every optimistic-locking
 * attempt. An earlier verb commit may already have landed; invoke `tick`
 * after re-reading the instance to resume convergence when contention subsides.
 */
export declare class ConcurrentCascadeError extends WorkflowError<"concurrent-cascade"> {
  readonly instanceId: string;
  readonly attempts: number;
  constructor(args: { instanceId: string; attempts: number });
}

/** {@link ConcurrentCompleteEffectError}'s mid-dispatch sibling: a
 *  `commitEffectOps` commit lost every optimistic-locking attempt. Nothing
 *  was written; the report may be retried under the same idempotency key. */
export declare class ConcurrentCommitEffectOpsError extends WorkflowError<"concurrent-commit-effect-ops"> {
  readonly instanceId: string;
  readonly effectKey: string;
  readonly attempts: number;
  constructor(args: {
    instanceId: string;
    effectKey: string;
    attempts: number;
  });
}

/**
 * Completion twin of {@link ConcurrentFireActionError}: a `completeEffect`
 * commit lost the optimistic-locking race on every attempt. Same contract —
 * nothing committed on the final try, so the pending entry (and its claim)
 * is untouched: the completion can be retried, and a claim whose lease
 * lapses is recovered by a later drain. The handler's reported outcome is
 * NOT applied — a caller that retries must not re-run the side effect,
 * only re-report it.
 */
export declare class ConcurrentCompleteEffectError extends WorkflowError<"concurrent-complete-effect"> {
  readonly instanceId: string;
  readonly effectKey: string;
  readonly attempts: number;
  constructor(args: {
    instanceId: string;
    effectKey: string;
    attempts: number;
  });
}

/**
 * Edit-seam twin of {@link ConcurrentFireActionError}: an `editField` commit
 * lost the optimistic-locking race on every attempt. Same contract — re-read
 * and retry, or investigate a write storm; nothing committed on the final try.
 */
export declare class ConcurrentEditFieldError extends WorkflowError<"concurrent-edit-field"> {
  readonly instanceId: string;
  readonly target: {
    scope: FieldScope;
    field: string;
    activity?: string;
  };
  readonly attempts: number;
  constructor(args: {
    instanceId: string;
    target: {
      scope: FieldScope;
      field: string;
      activity?: string;
    };
    attempts: number;
  });
}

/**
 * Thrown when a `fireAction` commit loses the optimistic-locking race on
 * every commit attempt — each reload +
 * `ifRevisionId` retry was beaten by another writer committing first.
 * Surfacing it (rather than silently overwriting) lets the caller decide
 * whether to retry later or report a write storm; nothing was committed
 * on the final attempt.
 */
export declare class ConcurrentFireActionError extends WorkflowError<"concurrent-fire-action"> {
  readonly instanceId: string;
  readonly activity: ActivityName;
  readonly action: string;
  readonly attempts: number;
  constructor(args: {
    instanceId: string;
    activity: ActivityName;
    action: string;
    attempts: 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).
 */
export 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 { ConditionAnalysis };

export { ConditionAtom };

export { ConditionClause };

export { ConditionDescription };

/** Static `$fields.<name>` / `$fields['<name>']` reads (both normalise to the
 *  same AST node); `$fields[$var]` dynamic access has no static name and is skipped.
 *  A malformed condition reads nothing here rather than throwing — the deploy-time
 *  syntax check owns the parse error. */
export declare function conditionFieldReadNames(
  groq: string,
): ReadonlySet<string>;

export { ConditionInsight };

export { ConditionOutcome };

export { ConditionRead };

/**
 * Every condition a definition declares, in stable order: author predicates,
 * then per stage — transitions, activities (filter, requirements, action
 * filters and `when` triggers), editable gates, tighten-overrides.
 * Editable gates resolve through the same helper the runtime projection uses
 * (entry `editable` ANDed with the stage
 * tighten-override), so every live editable-field address exists here with
 * the same EFFECTIVE predicate the edit insight explains — including
 * override-only gates on `editable: true` entries, and workflow-scope fields
 * once per stage (the effective predicate is per-stage).
 */
export declare function conditionSitesOf(
  definition: WorkflowDefinition,
): DefinitionConditionSite[];

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";

/**
 * The one-doc read a reactive adapter subscribes with to observe a content doc
 * under a perspective stack. It uses the same perspective semantics as
 * `hydrateSnapshot`: draft/version content is projected onto the published
 * id, and a doc that exists only as a draft or release version remains visible.
 */
export declare function contentDocQuery(documentId: string): CompiledQuery;

/**
 * Whether a watched content doc's reactive read may fall back to the DRAFT —
 * the fallback half of the per-doc resolution rule {@link contentReleaseName}
 * starts. Mirrors the engine's own hydration under the instance's effective
 * perspective (`instance.perspective ?? DEFAULT_CONTENT_PERSPECTIVE`): a draft
 * is visible only when that perspective names `'drafts'` — the drafts default,
 * `'drafts'` itself, or a stack like `[release, 'drafts']`. Under `'published'`
 * / `'raw'` and under a stack without a `'drafts'` entry (`[release]`,
 * `['published']`) drafts are invisible, and an adapter feeding one would
 * evaluate content the engine's read can never see.
 *
 * Raw refs ({@link readsRaw}) answer `true` by contract, and it is
 * load-bearing: instance / ancestor / `system.release` docs have no draft
 * form, and the `true` keeps them on the adapters' raw per-doc read path —
 * never a perspective-scoped content read.
 */
export declare function contentDraftFallback(args: {
  ref: {
    type: string;
  };
  perspective: WorkflowPerspective | undefined;
}): boolean;

/**
 * The Content Release a watched doc resolves under, or `undefined` for a raw
 * read — how a reactive adapter turns the watch-set's perspective into the
 * per-doc release its store needs. Instance / ancestor / `system.release` docs
 * read raw ({@link readsRaw}); a content doc resolves under the **leading**
 * release in the stack. The engine never forms the `versions.<release>.<id>`
 * id — the adapter does (Studio's `editState` version arg, the SDK handle
 * `{releaseName}`). A non-array perspective (`raw`/`published`/`drafts`)
 * carries no release, so content falls back to draft/published.
 *
 * Note: this resolves a **single** release — the documented `instance.perspective`
 * shapes (`[release]` / `[release, "drafts"]`). The stores' per-doc reads take
 * one release, so a multi-release stack can't be observed through them; the
 * engine's own fetch path (`hydrateSnapshot`) — and the SDK adapter's
 * query-store route for stacks without a `'drafts'` entry — honour the full
 * stack via `client.fetch({perspective})`.
 */
export declare function contentReleaseName(args: {
  ref: {
    type: string;
  };
  perspective: WorkflowPerspective | undefined;
}): string | undefined;

/**
 * Context-bag entry kinds.
 */
export declare const CONTEXT_ENTRY_DISPLAY: {
  "context.string": {
    title: string;
    description: string;
  };
  "context.number": {
    title: string;
    description: string;
  };
  "context.boolean": {
    title: string;
    description: string;
  };
  "context.ref": {
    title: string;
    description: string;
  };
  "context.json": {
    title: string;
    description: string;
  };
};

/**
 * One entry of the instance's `context` bag, rendered to conditions as
 * `$context.<name>`. **Written exactly twice, both at start**: the
 * `startInstance` seed and a parent's `spawn.context` handoff. Never
 * mutated afterwards — completed effects' outputs live on
 * `effectHistory[].outputs` and render as `$effects`, a separate bag.
 *
 * Critical: `context` is NOT a workflow field container. Transition
 * triggers must NOT read it as fields. The workflow's fields live on
 * `fields[]`; external state lives in the lake (queryable via conditions).
 */
export declare type ContextEntry =
  | {
      _key: string;
      _type: "context.string";
      name: string;
      value: string;
    }
  | {
      _key: string;
      _type: "context.number";
      name: string;
      value: number;
    }
  | {
      _key: string;
      _type: "context.boolean";
      name: string;
      value: boolean;
    }
  | {
      _key: string;
      _type: "context.ref";
      name: string;
      /** GDR — see `../core/refs.ts` */
      value: GlobalDocumentReference;
    }
  | {
      _key: string;
      _type: "context.json";
      name: string;
      value: string;
    };

/** `$context`: the context bag as a map by name; `json` entries decode to their object form. */
export declare function contextMap(
  instance: Pick<WorkflowInstance, "context">,
): Record<string, unknown>;

/**
 * A caller broke a public-API contract — a call the engine rejects
 * without writing anything: an invalid `tag`, a `workflow.query` GROQ that
 * never binds `$tag`, a bare id where a GDR URI is required, an action,
 * activity, or field the definition never declared, or a `startInstance`
 * `instanceId` reused for a different start (or a discarded one). Fix the
 * call site; retrying cannot succeed.
 */
export declare class ContractViolationError extends WorkflowError<"contract-violation"> {
  constructor(message: string);
}

/**
 * Construct an engine bound to a workflow resource + tag. The returned
 * object exposes the `workflow.*` verbs minus the {@link EngineScopeArgs}
 * scope (client / tag / workflowResource / resourceClients), which is
 * pinned at construction. The `tag` is required — see {@link validateTag}
 * for the accepted shape.
 *
 * Parity with the namespace is exact, with these deliberate exceptions:
 *
 * - Engine-only: {@link Engine.session} and
 *   {@link Engine.subscriptionDocumentsForInstance} (need the pinned
 *   binding), {@link Engine.drainEffects} and
 *   {@link Engine.verifyDeployedDefinitions} (need the construction-time
 *   `effects` / `loggerFactory`).
 * - Namespace-only: `workflow.permissions` — pure grant helpers that need
 *   no engine scope.
 *
 * The {@link EngineEffectsArgs} group changes nothing about `fireAction` /
 * `tick` / `completeEffect` — the runtime still decides when to drain, and
 * reports outcomes via `completeEffect`.
 */
export declare function createEngine<Client extends WorkflowClient>(
  args: CreateEngineArgs<Client>,
): Engine;

/**
 * The {@link EngineScopeArgs} scope pinned at construction, plus the
 * engine-only extras (`effects` and `loggerFactory` feed `drainEffects` +
 * `verifyDeployedDefinitions`). The `tag` partition is
 * required and never defaulted — the engine enforces nothing, so the
 * partition is the only thing keeping reads and writes off the wrong
 * environment.
 */
export declare interface CreateEngineArgs<
  Client extends WorkflowClient = WorkflowClient,
> extends EngineScopeArgs {
  client: Client;
  effects?: EngineEffectsArgs<Client>;
  loggerFactory?: LoggerFactory;
  /**
   * Deterministic-time seam, pinned once for this engine and threaded
   * into every verb it drives — `$now`, the `now` op-source, and the
   * timestamps the engine stamps all read from it. Omit (the default) to
   * use real wall-clock time; production never sets this. The test bench
   * (`@sanity/workflow-engine-test`) wraps this same seam as `setNow` /
   * `advance`. Deliberately engine-construction config, NOT a per-verb
   * option.
   */
  clock?: Clock;
  /**
   * How the engine waits out a `retry` policy's backoff between attempts.
   * Pinned once beside {@link CreateEngineArgs.clock}; omit (the default) to
   * spend real time. A deterministic harness passes one that moves its clock
   * forward instead, so a paced policy runs without waiting.
   */
  sleep?: Sleeper;
  /**
   * Product-telemetry seam, pinned once for this engine and threaded into
   * every verb it drives. The core engine ships no metrics pipeline — it
   * cannot know the environment's output rules (consent, transport, data
   * governance), so it only DEFINES events (exported from the package
   * root) and logs them through this logger; the app shell that does know
   * those rules owns store creation, consent resolution, and transport.
   * Omit (the default) to emit nothing. Any `@sanity/telemetry`
   * `TelemetryLogger` satisfies this seam — the engine mirrors the shape
   * rather than depending on the package. Same rule as the clock:
   * engine-construction config, never a per-verb option.
   */
  telemetry?: WorkflowTelemetryLogger;
}

/**
 * Build the consent/transport pair a shell's batched store runs on.
 * Consent is the account-level status from the authenticated client —
 * anything but `granted` (including a fetch error) means the store sends
 * nothing. `denied` short-circuits without a request: process shells
 * resolve their environment denial (see {@link isTelemetryEnvDenied})
 * once and pass it here; browser shells omit it.
 */
export declare function createTelemetryIntake(args: {
  client: TelemetryIntakeClient;
  projectId: string;
  denied?: boolean;
  /** Context merged into every event at send time. These values win on key collisions. */
  context?: Record<string, unknown>;
}): TelemetryIntake;

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

/** Append-only, machine-readable counterpart of the model log in DATAMODEL.md, which keeps the full reasoning. */
export declare const DATA_MODEL_CHANGES: readonly [
  Readonly<{
    id: "governed-model-stamps";
    introducedInModel: 1;
    minReaderModel: 0;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "additive";
    applicability: "unconditional";
    summary: "Definition and instance documents carry model provenance and reader-floor stamps.";
  }>,
  Readonly<{
    id: "subject-field-kind";
    introducedInModel: 2;
    minReaderModel: 0;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "additive";
    applicability: "detectable";
    summary: "A workflow-level subject field identifies the document a workflow is about.";
  }>,
  Readonly<{
    id: "typed-scalar-choice-lists";
    introducedInModel: 2;
    minReaderModel: 2;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "Scalar fields may constrain writes to a persisted typed choice list.";
  }>,
  Readonly<{
    id: "action-semantics";
    introducedInModel: 2;
    minReaderModel: 0;
    documentTypes: readonly ["definition"];
    compatibility: "additive";
    applicability: "detectable";
    summary: "Ordinary actions may carry advisory workflow semantics.";
  }>,
  Readonly<{
    id: "inclusive-scalar-bounds";
    introducedInModel: 2;
    minReaderModel: 2;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "String, text, and number values may carry persisted inclusive bounds.";
  }>,
  Readonly<{
    id: "progress-field-kind";
    introducedInModel: 3;
    minReaderModel: 0;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "additive";
    applicability: "detectable";
    summary: "A progress field kind carries application-defined 0–100 completion.";
  }>,
  Readonly<{
    id: "effect-claim-tokens";
    introducedInModel: 3;
    minReaderModel: 0;
    documentTypes: readonly ["instance"];
    compatibility: "additive";
    applicability: "detectable";
    summary: "Pending-effect claims carry an exact-claim token gating mid-dispatch state reports.";
  }>,
  Readonly<{
    id: "classified-principal-ids";
    introducedInModel: 4;
    minReaderModel: 4;
    documentTypes: readonly ["instance"];
    compatibility: "reader-floor";
    applicability: "unconditional";
    summary: string;
  }>,
  Readonly<{
    id: "readiness-requirements";
    introducedInModel: 4;
    minReaderModel: 4;
    documentTypes: readonly ["definition"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "Start and activity readiness use named polymorphic requirement arrays.";
  }>,
  Readonly<{
    id: "due-date-field-kinds";
    introducedInModel: 5;
    minReaderModel: 0;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "additive";
    applicability: "detectable";
    summary: string;
  }>,
  Readonly<{
    id: "node-semantics";
    introducedInModel: 6;
    minReaderModel: 0;
    documentTypes: readonly ["definition"];
    compatibility: "additive";
    applicability: "detectable";
    summary: "Workflow, stage, activity, and action nodes may carry signal or custom advisory semantics.";
  }>,
  Readonly<{
    id: "field-patch-ops";
    introducedInModel: 6;
    minReaderModel: 0;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "additive";
    applicability: "detectable";
    summary: "Field ops may increment, decrement, or initialize a missing field value.";
  }>,
  Readonly<{
    id: "attributes-condition-var";
    introducedInModel: 7;
    minReaderModel: 0;
    documentTypes: readonly ["definition"];
    compatibility: "additive";
    applicability: "unconditional";
    summary: string;
  }>,
  Readonly<{
    id: "role-constrained-assignment-fields";
    introducedInModel: 8;
    minReaderModel: 8;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "Assignee fields may restrict newly assigned users and collective roles by role.";
  }>,
  Readonly<{
    id: "split-guard-id-spaces";
    introducedInModel: 9;
    minReaderModel: 9;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "Guards spanning edit and lifecycle id spaces emit independently retractable documents.";
  }>,
  Readonly<{
    id: "singular-assignee-lists";
    introducedInModel: 9;
    minReaderModel: 9;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "Singular assignee fields use member lists with at most one user and any number of roles.";
  }>,
  Readonly<{
    id: "required-content-references";
    introducedInModel: 10;
    minReaderModel: 10;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "Required content references must remain readable after initialization before actions or transitions advance.";
  }>,
  Readonly<{
    id: "effect-retry-policy";
    introducedInModel: 10;
    minReaderModel: 10;
    documentTypes: readonly ["definition", "instance"];
    compatibility: "reader-floor";
    applicability: "detectable";
    summary: "An effect node declares a bounded retry policy the engine enforces on every runtime.";
  }>,
];

/** The maximum reader floor this writer can emit for a detectable feature. */
export declare const DATA_MODEL_MAX_READER = 10;

/**
 * The unconditional model-4 reader floor for every engine-owned document.
 * Detectable features may raise an individual document through
 * {@link DATA_MODEL_MAX_READER}.
 */
export declare const DATA_MODEL_MIN_READER = 4;

/**
 * The engine's persisted data-model version — the provenance half of
 * the model stamp, written as `modelVersion` on every engine-owned
 * document at its construction and persist choke-points. Conforms-to
 * semantics: the stamp means "this document conforms to model N now" —
 * instances are re-stamped on every full persist, so mixed-version fleets
 * honestly record whichever engine last shaped a doc.
 *
 * A number is assigned per release, not per change: a declared shape change
 * merged before this model has shipped joins it, and one merged after it has
 * shipped moves the number on. Bumping does NOT by itself lock out older
 * engines — that is the document's derived `minReaderModel` floor. Declare
 * every change in `DATAMODEL.md`; the model-surface snapshot test fails on
 * undeclared drift.
 */
export declare const DATA_MODEL_VERSION = 10;

export declare interface DataModelChange {
  readonly id: string;
  readonly introducedInModel: number;
  readonly minReaderModel: number;
  readonly documentTypes: readonly DataModelDocumentType[];
  readonly compatibility: "additive" | "reader-floor";
  readonly applicability: "unconditional" | "detectable";
  readonly summary: string;
}

export declare type DataModelDocumentType = "definition" | "instance";

/**
 * Split a dataset resource id (`<projectId>.<dataset>`) into its parts — the
 * one parser for the format, shared by {@link gdrFromResource} and the React
 * adapters' store routing. Throws on a malformed id: missing separator, or an
 * empty project / dataset part.
 */
export declare function datasetResourceParts(id: string): {
  projectId: string;
  dataset: string;
};

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

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

/** The declarable half of {@link ExecutionContext} — what `createEngine` accepts. */
export declare type DeclaredExecutionContext = Pick<
  ExecutionContext,
  "kind" | "id"
>;

/**
 * The {@link OperationArgs} of the verbs that own a discrete commit —
 * `fireAction`, `editField`, `completeEffect`, `commitEffectOps`, `setStage`,
 * `abortInstance`. `tick` deliberately takes the plain base: it owns no
 * commit of its own and re-derives everything, so retrying it blind is
 * already safe.
 */
export declare interface DedupableOperationArgs extends OperationArgs {
  /**
   * Caller-supplied key that makes this call safe to retry blind (a network
   * failure ate the response; a queue redelivered the message). The first
   * commit records the key on the instance's `processedRequests[]` ledger —
   * in the same CAS write as the operation itself — and a retry carrying the
   * same key replays instead of double-applying (or, for a completed effect,
   * throwing `EffectNotFoundError`): the operation is NOT re-applied, but
   * the cascade runs to convergence (the original may have died before its
   * own cascade), so `changed` is `false` unless that cascade repaired
   * something. Keys live for the engine's `idempotencyTtlMs` (default 24h);
   * reusing a live key on a different verb throws. The caller owns key
   * uniqueness per logical request.
   *
   * Only a commit records the key: a keyed call that no-ops (a `setStage`
   * already at its target, an abort of a terminal instance) leaves no ledger
   * row, so retrying it later re-evaluates fresh rather than replaying.
   */
  idempotencyKey?: string;
}

/**
 * The perspective a content read falls back to when the instance has no
 * explicit release perspective: `drafts` overlay published (Sanity
 * draft-precedence), so an unpublished or in-flight subject is what the engine
 * — and the reactive adapters — evaluate, never a published-only read that
 * silently misses the draft. The single home for the draft-precedence default;
 * every content read uses `instance.perspective ?? DEFAULT_CONTENT_PERSPECTIVE`.
 */
export declare const DEFAULT_CONTENT_PERSPECTIVE = "drafts";

/** How long a fresh claim's lease runs unless the engine configured
 *  `effects.leaseMs`. */
export declare const DEFAULT_EFFECT_LEASE_MS: number;

/** How long a recorded idempotency key dedupes retries, unless the caller
 *  configured `idempotencyTtlMs`. */
export declare const DEFAULT_IDEMPOTENCY_TTL_MS: number;

/** The condition a transition gets when the author declares none — fire once
 *  the stage's own work settles. Exported so consumers describing transition
 *  conditions can recognize the default's spelling without copying it. */
export declare const DEFAULT_TRANSITION_WHEN = "$allActivitiesDone";

/**
 * Default LoggerFactory — writes through the global `console`. Exposed
 * so callers outside `createEngine` (drive scripts, the
 * drain-effects helper) can use the same logger shape the engine uses
 * internally. Returns a fresh `EngineLogger` per call; the `name`
 * shows up as a `[name]` prefix on every line.
 */
export declare const defaultLoggerFactory: LoggerFactory;

/**
 * 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.
 */
export declare type DefinedWorkflow = WorkflowDefinition & {
  runtime?: DefinitionRuntime | undefined;
};

export declare interface DefinitionConditionSite {
  /** The stage the condition applies in; absent only for author predicates. */
  stage?: string;
  address: DefinitionSiteAddress;
  condition: Condition;
}

/** Derive the deploy event payload from a definition's structure. */
export declare function definitionDeployedData(
  definition: WorkflowDefinition,
  outcome: {
    contentHash: string;
    status: WorkflowDefinitionDeployedData["status"];
    deployId: string;
  },
): DerivedEventData<WorkflowDefinitionDeployedData>;

/** One declared group at one level, with the members lexically attributed to it. */
export declare interface DefinitionGroupSite {
  group: Group;
  /** The declaration level; `stage`/`activity` name the declaring node. */
  level: FieldScope;
  stage?: string;
  activity?: string;
  members: GroupMember[];
}

export declare interface DefinitionGuardsQueryArgs {
  client: WorkflowClient;
  clientForGdr: ClientForGdr;
  workflowResource: WorkflowResource;
  definition: string;
  /** Every deployed version of {@link DefinitionGuardsQueryArgs.definition}. */
  definitions: WorkflowDefinition[];
}

/** What blocks a `deleteDefinition`, so a consumer can render the remediation:
 *  abort-in-place via `cascade`, or delete/redeploy the referrer first. */
export declare type DefinitionInUseBlocker =
  | {
      reason: "non-terminal-instances";
      instanceIds: string[];
    }
  | {
      reason: "spawn-referrers";
      referrers: {
        definition: string;
        version: number;
      }[];
    };

/**
 * `deleteDefinition` refused because the definition is still in use — either
 * non-terminal instances are pinned to it (pass `cascade` to abort them in
 * place first) or a surviving deployed definition still spawn-references a
 * targeted version (delete or redeploy the referrer first). `blockedBy` says
 * which, with the blocking ids, so a consumer can render the remediation.
 */
export declare class DefinitionInUseError extends WorkflowError<"definition-in-use"> {
  readonly definition: string;
  readonly blockedBy: DefinitionInUseBlocker;
  constructor(args: { definition: string; blockedBy: DefinitionInUseBlocker });
}

/**
 * GROQ resolving a single deployed {@link WORKFLOW_DEFINITION_TYPE} for the
 * caller's tag — pinned to `$version` when {@link explicit}, else the highest
 * deployed version. Params: `$definition`, `$tag`, plus `$version` when explicit.
 */
export declare function definitionLookupGroq(explicit: boolean): string;

/** No deployed workflow definition matches the requested name (and version,
 *  when given) under this engine's tag. */
export declare class DefinitionNotFoundError extends WorkflowError<"definition-not-found"> {
  readonly definition: string;
  readonly version?: number;
  constructor(args: { definition: string; version?: number });
}

/** Every literal project role a stored definition references, deduplicated in encounter order. */
export declare function definitionRoleNames(
  definition: WorkflowDefinition,
): readonly string[];

/**
 * 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.
 */
export declare interface DefinitionRuntime {
  kind?: RuntimeKind | undefined;
  effects?: Record<string, EffectRuntimeBlock> | undefined;
}

export declare interface DefinitionsForDocumentArgs {
  /**
   * The LOADED candidate document — unlike {@link InstancesForDocumentArgs},
   * a ref won't do: applicability evaluates content (`_type` against subject
   * entry `types`, `start.filter` against the attributes), under whatever
   * perspective the caller loaded the document with.
   */
  document: CandidateDocument;
}

/** A definition-level site address: every runtime {@link InsightSite}, plus
 *  the two shapes that only exist at the definition level — author
 *  predicates, and stage `editable` tighten-overrides (runtime folds an
 *  override into the field's effective predicate; statically it is also its
 *  own authored gate). */
export declare type DefinitionSiteAddress =
  | InsightSite
  | {
      kind: "predicate";
      predicate: string;
    }
  | {
      kind: "editable-override";
      name: string;
    };

/**
 * GROQ listing EVERY deployed {@link WORKFLOW_DEFINITION_TYPE} visible to the
 * caller's tag, grouped by name. `versionOrder` picks the in-group direction;
 * handler verification uses oldest-first order while inspecting every version.
 *
 * Params: `$tag`.
 */
export declare function definitionsListGroq(
  versionOrder: "asc" | "desc",
): string;

/**
 * GROQ listing every tag partition that holds any version of one definition
 * name — {@link deployedTagsGroq} narrowed from "what exists here" to "where
 * is this".
 *
 * Several hits is ambiguity to refuse, not resolve: version numbers are
 * per-partition, so the highest one may sit in an environment the caller did
 * not mean, and the answer would carry no sign of it.
 *
 * Params: `$definition`.
 */
export declare function definitionTagsGroq(): string;

export declare interface DeleteDefinitionArgs {
  /** The definition's `name` — delete addresses the workflow, not a doc id. */
  definition: string;
  /** Delete only this deployed version. Default: every deployed version. */
  version?: number;
  /**
   * Abort every non-terminal instance pinned to the targeted versions
   * before deleting. Instances are ONLY aborted — instance documents are
   * never deleted; they stay in the lake as the audit record. Without
   * this flag the delete refuses when such instances exist.
   */
  cascade?: boolean;
  /** Free-text reason stamped on each cascade-abort history entry. */
  reason?: string;
  /** URL path for grant resolution — see `StartInstanceArgs.grantsFromPath`. */
  grantsFromPath?: string;
}

export declare interface DeleteDefinitionResult {
  /** The definition's `name`. */
  name: string;
  /** Versions actually removed, newest first. */
  deletedVersions: number[];
  /** Instances hard-stopped by `cascade`, in abort order. Empty without it. */
  abortedInstanceIds: string[];
  /**
   * Orphaned guard docs removed across the definition's statically-named
   * datasources. Only populated when the LAST version goes — guard docs
   * are stamped with the version-less `name`, so they stay while any
   * version remains deployed.
   */
  deletedGuardCount: number;
}

/**
 * Human label per denying guard — the authored `name` when present, else the
 * raw guard id. The one display convention for rendering a denial to a
 * person; the payload keeps the raw ids for operators locating the guard doc.
 */
export declare function deniedGuardLabels(
  denied: readonly DeniedGuardRef[],
): string[];

/**
 * One denying guard, as carried by both the read-side verdict
 * (`mutation-guard-denied` in {@link DisabledReason}) and the thrown
 * {@link MutationGuardDeniedError} — one shape for the same denial, so a
 * consumer renders it once.
 */
export declare interface DeniedGuardRef {
  guardId: string;
  name?: string;
}

/**
 * The one mapping from {@link MutationGuardDoc} to the structured
 * {@link DeniedGuardRef} payload — shared by the thrown error and the
 * read-side `mutation-guard-denied` verdict, so the two can't drift.
 */
export declare function deniedGuardRefs(
  guards: readonly MutationGuardDoc[],
): DeniedGuardRef[];

/**
 * Run every guard whose `match` applies and collect those that DENY. Empty
 * result ⇒ allowed (optimistically).
 */
export declare function denyingGuards(args: {
  guards: MutationGuardDoc[];
  doc: {
    id: string;
    type?: string;
  };
  context: MutationContext;
  dereference?: GuardDereference;
}): Promise<MutationGuardDoc[]>;

export declare interface DeployDefinitionResult {
  /** The definition's `name`. */
  name: string;
  /** The deploy-assigned version this deploy created or matched. */
  version: number;
  status: "created" | "unchanged";
  /**
   * Advisory producer/consumer warnings from the effect-output lint — a
   * `$effects['<name>'].<key>` read of a key a declared effect does not produce.
   * Non-blocking: deploy still succeeds. Absent when the definition is clean.
   * See {@link lintEffectOutputs}.
   */
  warnings?: string[];
}

export declare interface DeployDefinitionsArgs<
  T extends WorkflowDefinitionInput<T> = WorkflowDefinition,
> {
  /**
   * Highest reader model verified across runtimes sharing the workflow resource. The deploy gate
   * compares this reviewed numeric literal with the submitted definitions; do not import
   * either exported reader constant, because a dependency upgrade must not change it automatically.
   */
  expectedMinReaderModel: number;
  /**
   * Resource-alias bindings for this deploy (alias name → physical resource).
   * A deploy-time abstraction ONLY: every `@<alias>:` reference in a
   * definition is expanded to its bound physical resource before the
   * deployed definition is fingerprinted and stored, and deploy fails closed
   * on an unbound alias. Aliases never exist past deploy — no stored
   * document carries one, the runtime never sees the map, and an
   * alias-shaped ref reaching a runtime boundary is rejected as malformed.
   * Omit for single-resource workflows (definitions referencing no aliases).
   */
  resourceAliases?: ResourceAliases;
  /** Authored definitions (the default — full compile-time checking) or
   *  loosely-typed fetched definition documents — the boundary parse
   *  normalizes either ({@link WorkflowDefinitionInput}). */
  definitions: T[];
}

export declare interface DeployDefinitionsResult {
  /** Per-definition outcome, ordered by the resolved deploy order (children first). */
  results: DeployDefinitionResult[];
  /**
   * Random id grouping this call's per-definition deploy telemetry events.
   * Returned so a caller reporting on the same deploy (e.g. definition
   * sharing) can carry the id the events already minted.
   */
  deployId: string;
}

/** A definition as fetched back from the lake. The document carries `_id` plus
 *  the deploy-stamped envelope the authored {@link WorkflowDefinition} never
 *  had: the assigned `version` and the content fingerprint it was minted from
 *  ({@link hashDefinitionContent}). */
export declare type DeployedDefinition = WorkflowDefinition & {
  _id: string;
  tag?: string;
  version: number;
  /** Optional: a document deployed before content-addressing has none. Every
   *  version this engine deploys carries one. */
  contentHash?: string;
  /** Engine data-model stamp (see {@link DATA_MODEL_VERSION}) — absent on
   *  documents deployed before the stamp existed (model 0). */
  modelVersion?: number;
  /** The oldest engine data model that can safely interpret this document,
   *  derived from its persisted features and the retained model-4 baseline. */
  minReaderModel?: number;
};

/**
 * GROQ listing every tag partition holding a deployed
 * {@link WORKFLOW_DEFINITION_TYPE} in the resource. The un-scoped
 * inverse of {@link tagScopeFilter}, this deliberately spans partitions.
 */
export declare function deployedTagsGroq(): string;

/**
 * Deploy every guard for a stage being entered (idempotent upsert), but only
 * while the instance is still committed to that stage. A deploy that lost the
 * race to a newer transition would otherwise re-lock a stage the instance
 * already left — a stale lock the newer transition's retract can't see. A
 * vanished instance (`undefined`) likewise no-ops: `undefined !== stageName`.
 *
 * An aborted instance also no-ops: it parks on its stage forever, so a stale
 * deploy landing after abort's retract would re-lock the subjects with no
 * remaining path to delete them. The gate is `abortedAt`, not `completedAt` —
 * a normal move *into* a terminal stage stamps `completedAt` in the same
 * persist and must still deploy that stage's guards.
 */
export declare function deployStageGuards(args: StageGuardArgs): Promise<void>;

/** Structurally what `deployDefinitions` receives, minus the definitions; carrying `resourceAliases` here keeps a diff's fingerprint matching what deploy would produce. */
export declare interface DeployTarget {
  /** Highest reader model verified across runtimes sharing this workflow resource. */
  expectedMinReaderModel: number;
  tag: string;
  workflowResource: WorkflowResource;
  resourceAliases?: ResourceAliases;
}

/** Classifies an activity from its shape: `target` marks off-system work
 *  (`manual`), the one bit action shapes alone can't otherwise show. Then:
 *  any caller-fireable action → `user`; effects or spawns → `service`;
 *  cascade-only actions → `receive`; no actions at all → `script`. */
export declare function deriveActivityKind(activity: Activity): ActivityKind;

export declare interface DeriveAutonomyOptions {
  /** Child definitions for `spawn` recursion, by definition `name` — the
   *  deploy batch or the already-deployed set. An unresolvable child reports
   *  `conditional` with an unresolved wait. */
  children?: ReadonlyMap<string, WorkflowDefinition>;
}

/**
 * A payload builder's half: everything the event carries except the
 * {@link ExecutionScopedEventData} stamp, which the emit site supplies. A
 * caller assembling an event payload itself has to add those fields.
 */
export declare type DerivedEventData<Data extends ExecutionScopedEventData> =
  Omit<Data, keyof ExecutionScopedEventData>;

/** Who fires the activity's actions, from shape alone — a separate causal
 *  check decides whether it actually resolves without a caller. A `target`
 *  is `off-system`; all-cascade actions are `autonomous`, none are
 *  `interactive`, a mix is `hybrid`. */
export declare function deriveExecutorClassification(
  activity: Activity,
): ExecutorClassification;

/**
 * Derive the causal autonomy of a stored definition. Pure and instance-free;
 * conditions must parse (they did at define/deploy time — an unparseable one
 * throws groq-js's syntax error rather than guessing).
 */
export declare function deriveWorkflowAutonomy(
  definition: WorkflowDefinition,
  options?: DeriveAutonomyOptions,
): WorkflowAutonomy;

export declare type Describable =
  | ConditionInsight
  | FieldInsight
  | TransitionEvaluation
  | ActionEvaluation
  | ActivityEvaluation
  | EditableFieldEvaluation;

/** One atom as a phrase in the workflow vocabulary. */
export declare function describeAtom(
  atom: AtomInsight,
  ctx: DescribeContext,
): {
  phrase: InsightPhrase;
  fallback: boolean;
};

/** One {@link AutonomyWait} as a phrase in the workflow vocabulary. */
export declare function describeAutonomyWait(
  wait: AutonomyWait,
  ctx: DescribeContext,
): InsightPhrase;

/** Render one condition's insight as a checklist + frontier summary, in the
 *  workflow vocabulary. */
export declare function describeCondition(
  insight: ConditionInsight,
  ctx: DescribeContext,
): ConditionDescription;

/** The engine's rendering context: everything phrases resolve titles and
 *  vocabulary from is on the definition. */
export declare interface DescribeContext {
  definition: WorkflowDefinition;
}

/** The return shape {@link describeNode} owes each input — conditional on the node. */
export declare type Described<T extends Describable> = T extends FieldInsight
  ? FieldDescription
  : T extends ActivityEvaluation
    ? ActivityDescription
    : T extends ConditionInsight | TransitionEvaluation
      ? ConditionDescription
      : ConditionDescription | undefined;

export { DescribedClause };

/** One described definition site: the address plus its phrased checklist. */
export declare type DescribedDefinitionSite = DefinitionConditionSite & {
  description: ConditionDescription;
};

/**
 * Explain the whole workflow in human language, without an instance: every
 * condition site phrased against an EMPTY scope, in the workflow vocabulary.
 * Outcome marks are placeholders (no values to judge) — the checklists and
 * summaries carry the "what this needs" story; live verdicts come from
 * evaluation insight where a run's current stage overlaps these addresses.
 */
export declare function describeDefinition(
  definition: WorkflowDefinition,
): Promise<DescribedDefinitionSite[]>;

/** A field's insight as phrases: involvement plus verified proposals. */
export declare function describeFieldInsight(
  field: FieldInsight,
  ctx: DescribeContext,
): FieldDescription;

/**
 * The one front door: feed it any insight-bearing node off an evaluation and
 * get its description — a checklist for gate nodes (undefined when the node
 * declares no gate), every declared gate for an activity, involvement +
 * proposals for a field. For an action node the firing gate wins: a
 * cascade-fired action describes its `when` trigger; a fireAction action
 * its `filter`. Dispatch is by each node's defining property, which is
 * unambiguous across the union.
 */
export declare function describeNode<T extends Describable>(
  node: T,
  ctx: DescribeContext,
): Described<T>;

/** A site address as a noun phrase, using declared titles where present. */
export declare function describeSite(
  site: InsightSite,
  ctx: DescribeContext,
): InsightPhrase;

/**
 * A site address as a checklist lead-in that flows into the atom lines —
 * "«Approval» completes automatically when:" over "✗ «Approved» must be
 * true". The connective mood for tooltips/panels; {@link describeSite} is
 * the noun-phrase mood for mid-sentence composition. Accepts the
 * definition-level address superset so the static tier heads the same way.
 */
export declare function describeSiteHeading(
  address: DefinitionSiteAddress,
  ctx: DescribeContext,
): InsightPhrase;

/**
 * The activity slice the document-derivable stuck causes read: its runtime
 * status, and the declared actions whose effects a failure is matched against.
 * Narrowed to exactly this, so one set of cause functions serves both a full
 * {@link WorkflowEvaluation} and {@link documentStuckCause}'s snapshot-derived
 * rows.
 */
declare interface DiagnosedActivity {
  status: ActivityStatus;
  activity: Pick<Activity, "name" | "actions">;
}

/** The slice of a {@link TransitionEvaluation} the classifier reads — narrowed
 *  so a hand-crafted stuck permutation doesn't have to fabricate insights. */
export declare type DiagnosedTransition = Pick<
  TransitionEvaluation,
  "transition" | "whenSatisfied" | "unevaluable"
>;

/**
 * The slice of an instance + its {@link WorkflowEvaluation} the classifier
 * reads. Narrowed so callers (and tests) can craft an exact stuck permutation
 * without standing up a full evaluation; {@link diagnoseInputFromEvaluation}
 * builds it from a real {@link WorkflowEvaluation}.
 */
export declare interface DiagnoseInput extends DocumentStuckInput {
  /** Missing references read by unmet requirements or transition conditions; omit when not checked. */
  missingDocuments?: MissingDocument[];
  instance: Pick<
    WorkflowInstance,
    | "currentStage"
    | "completedAt"
    | "abortedAt"
    | "effectHistory"
    | "pendingEffects"
    | "history"
    | "subworkflows"
  >;
  activities: ActivityEvaluation[];
  transitions: DiagnosedTransition[];
  assignees: Record<string, Assignee[]>;
}

/** Narrow a full {@link WorkflowEvaluation} to the {@link DiagnoseInput} the
 *  classifier reads. Throws when populated missing-reference evidence lacks
 *  its blocking subset. */
export declare function diagnoseInputFromEvaluation(
  evaluation: WorkflowEvaluation,
): DiagnoseInput;

/**
 * Classify an instance. Terminal states win first; then effect or activity
 * faults; then missing references read by unmet conditions; then transition faults; then `waiting`
 * (an action is available — healthy); then `blocked` (an active activity held by
 * an unmet requirement — healthy, not yet actionable); else `progressing` (a
 * transition is already satisfied and will cascade).
 */
export declare function diagnoseInstance(input: DiagnoseInput): Diagnosis;

/** The `workflow.diagnose` result — the verdict, the structured remediations
 *  that would unstick it (empty unless `stuck`), and the evaluation it was
 *  derived from, so a consumer can render the supporting evidence (current
 *  stage activities + transitions) without a second projection. */
export declare interface DiagnoseResult {
  evaluation: WorkflowEvaluation;
  diagnosis: Diagnosis;
  remediations: SuggestedRemediation[];
}

/**
 * How an instance reads right now. `waiting` and `blocked` are both healthy,
 * not stuck. A `waiting` result says whether the activity awaits an
 * action available to this caller (`caller`), a manual action that this caller
 * cannot currently take (`manual-action`), or a cascade-fired action
 * (`automation`). How long a workflow is "allowed" to wait is workflow- and
 * team-specific, not this classifier's call. `blocked` means an active
 * activity's declared requirements aren't all met
 * yet, and flips to `waiting` once they hold (typically a sibling activity
 * completing, or content landing). Completed and aborted results include
 * `liveChildren` while detached spawned work remains active; consumers should
 * surface it prominently.
 */
export declare type Diagnosis =
  | {
      state: "progressing";
    }
  | {
      state: "waiting";
      activity: string;
      assignees: Assignee[];
      actions: string[];
      waitingFor: "automation" | "caller" | "manual-action";
    }
  | {
      state: "blocked";
      activity: string;
      requirements: string[];
      assignees: Assignee[];
    }
  | {
      state: "completed";
      at: string;
      liveChildren?: number;
    }
  | {
      state: "aborted";
      at: string;
      reason?: string;
      liveChildren?: number;
    }
  | {
      state: "stuck";
      cause: StuckCause;
    };

export declare interface DiffEntry {
  name: string;
  /** The version this deploy WOULD write, or the matched version when unchanged. */
  version: number;
  status: "create" | "unchanged";
  docId: string;
  /** The document deploy would write — including the stamped `version` and
   *  `contentHash`. */
  expected: Record<string, unknown>;
  /** The latest deployed document, system fields stripped — the prior shape to
   *  diff against. Absent when nothing is deployed yet. */
  existing?: Record<string, unknown>;
}

/**
 * Classifies `def` against the latest deployed version of its name via
 * the deploy planner — a content change is always a new version,
 * never an in-place update. `def` passes the same boundary parse deploy uses
 * ({@link parseDefinitionInput}), so diff and deploy accept and reject the
 * same input shape.
 */
export declare function diffEntry<T extends WorkflowDefinitionInput<T>>({
  def: rawDef,
  latestRaw,
  target,
}: {
  def: T;
  latestRaw: Record<string, unknown> | undefined;
  target: DeployTarget;
}): DiffEntry;

/**
 * Why an action is disabled for this actor right now — the read-side verdict.
 *
 * Verdict↔exception mapping (what `fireAction` throws when the verdict says
 * no): the `mutation-guard-denied` arm escalates to
 * {@link MutationGuardDeniedError} — the one guard-denial error, shared by
 * every verb; every other arm is thrown as {@link ActionDisabledError}
 * carrying the verdict as `reason`. The edit seam mirrors this: see
 * {@link EditDisabledReason} and {@link EditFieldDeniedError}.
 */
export declare type DisabledReason =
  | {
      /**
       * The action's condition evaluated falsy for this actor — the ONE
       * engine-side gate (advisory, like every engine check). Sugar like
       * `roles` desugared into this condition, so a role miss surfaces
       * here too. Under filter-existence semantics a consumer renders the
       * action ABSENT, never disabled.
       */
      kind: "filter-failed";
      filter: string;
      detail?: string;
    }
  | {
      /** The action is cascade-fired (`when`) — the engine's cascade is its
       *  only firing path; `fireAction` rejects it for every caller. */
      kind: "cascade-fired";
      when: string;
    }
  | {
      kind: "activity-not-active";
      status: TerminalActivityStatus;
    }
  | {
      kind: "stage-terminal";
      stage: StageName;
    }
  | {
      /**
       * A deployed mutation guard denies the instance write every action
       * commit performs. Advisory pre-flight — the engine's optimistic
       * evaluation; `denied` is the same {@link DeniedGuardRef} shape the
       * thrown {@link MutationGuardDeniedError} carries.
       */
      kind: "mutation-guard-denied";
      denied: DeniedGuardRef[];
    }
  | {
      kind: "instance-completed";
      completedAt: string;
    }
  | {
      /** The instance was hard-stopped via `abortInstance`. Aborted instances
       *  carry `completedAt` too, so this arm wins over `instance-completed`
       *  (the {@link terminalState} precedence). */
      kind: "instance-aborted";
      abortedAt: string;
    }
  | {
      /**
       * An authored activity requirement is unmet, or a selected target of a
       * required reference field cannot be read. Use `unmetRequirements` to
       * explain what blocks the action. Required-reference descriptors use
       * `field:<name>`; they have no entry in `requirementInsights`.
       */
      kind: "requirements-unmet";
      unmetRequirements: RequirementDescriptor[];
    }
  | {
      /**
       * The actor's grants on an involved subject's resource don't allow the
       * content write the action's effects would perform there. Forecast
       * per-resource: each subject named by a `doc.ref`/`subject`/`doc.refs`/`release.ref`
       * field entry outside the workflow's own resource is checked against
       * THAT resource's ACL. Advisory like every engine verdict — the subject's
       * lake still enforces; and it degrades open: a resource whose grants
       * can't be fetched is simply not forecast.
       */
      kind: "subject-permission-denied";
      denied: SubjectPermissionDenial[];
    };

/**
 * Single combined map for callers that don't care which family the
 * key belongs to (e.g. an audit row showing any `_type`).
 */
export declare const DISPLAY: Record<string, DisplayMetadata>;

/**
 * Same idea but returns the description, or undefined when unknown.
 */
export declare function displayDescription(
  typeKey: string | undefined,
): string | undefined;

/**
 * Display strings for one persisted discriminator: `title` is a short label
 * for chips, badges, and headings, `description` longer prose for tooltips and
 * inspector panes. A UI rendering an instance audit log looks the raw
 * discriminator up here instead of showing it — `transitionFired` reads as
 * "Transition fired".
 */
export declare interface DisplayMetadata {
  readonly title: string;
  readonly description: string;
}

/**
 * Lookup helper. Returns a friendly title for any known `_type`, or
 * the original key when unknown so UIs degrade gracefully.
 */
export declare function displayTitle(typeKey: string | undefined): string;

/** Document-value permissions. Grants ({@link Grant} in ./authorization.ts) compose most-permissive-wins. */
export declare const DOCUMENT_VALUE_PERMISSIONS: readonly [
  "create",
  "manage",
  "read",
  "update",
];

/**
 * The guards that deny a concrete Lake mutation image. Advisory, like every
 * engine-side guard verdict: the check explains and disables, it never
 * enforces.
 */
export declare function documentActionDenials(
  args: DocumentActionDenialsArgs,
): Promise<MutationGuardDoc[]>;

export declare interface DocumentActionDenialsArgs {
  /** The concrete Lake mutation the action will perform. */
  mutation: MutationContext;
  /** The datasource the document lives in. A guard applies solely within the
   *  datasource it is registered in, so a same-id match from a foreign
   *  datasource can never gate this action and must not flip verdicts. */
  resource: {
    type: string;
    id: string;
  };
  guards: readonly MutationGuardDoc[];
  /** The caller's principal id in the guarded resource's own namespace,
   *  resolved as `identity()` in predicates. */
  identity?: string;
  /** Resource-local stored-document lookup for predicates using `->`. */
  dereference?: GuardDereference;
}

/**
 * Completed evidence for a document absent from the snapshot. `deleted` confirms
 * absence across versions; `outside-perspective` identifies an existing representation.
 * `unreadable` covers denied access and unsuccessful availability checks.
 */
export declare type DocumentAvailability =
  | "deleted"
  | "unreadable"
  | "outside-perspective";

/** Supplies completed availability evidence for references absent from an evaluation snapshot. */
export declare type DocumentAvailabilityReader = (
  documents: readonly MissingDocument[],
) => Promise<ReadonlyMap<string, DocumentAvailability>>;

/** @inline */
declare type DocumentEnvelopeKey =
  | `_${string}`
  | "tag"
  | "version"
  | "contentHash"
  | "modelVersion"
  | "minReaderModel";

/**
 * The document GROQ arm — matches instances whose reactive watch-set
 * references any of `documents`. Binds `$documents` + `$bareIds` into
 * `params`. Exposed for list builders that compose their own conditions
 * (e.g. the CLI's cross-partition list); {@link instancesQuery} consumers get
 * it via the `document`/`documents` filter fields instead.
 */
export declare function documentPrefilter(
  documents: readonly GdrUri[],
  params: Record<string, string | string[]>,
): string;

/**
 * Classify an instance from its document alone — no evaluation, no reads, no
 * actor. Document absence and transition-level causes require an evaluation,
 * so only {@link diagnoseInstance} reaches those.
 *
 * Sound but incomplete, and a consumer must present it that way: `undefined`
 * means "no cause this classifier can see", never "healthy". Flag an instance on
 * a cause; never word an absence as an all-clear.
 */
export declare function documentStuckCause(args: {
  instance: Pick<
    WorkflowInstance,
    "currentStage" | "effectHistory" | "pendingEffects" | "stages"
  >;
  /** The instance's parsed snapshot. Absent, the answer narrows — a failed
   *  effect cannot be tied to the activity it stalls — and never widens. */
  definition: WorkflowDefinition | undefined;
}): StuckCause | undefined;

/**
 * What the document-derivable stuck causes read. Every field is persisted —
 * on the instance itself or in the definition snapshot pinned to it — so a
 * caller holding only a committed instance can classify these without an
 * evaluation.
 */
declare interface DocumentStuckInput {
  instance: Pick<WorkflowInstance, "effectHistory" | "pendingEffects">;
  activities: readonly DiagnosedActivity[];
}

export declare type DocumentValuePermission =
  (typeof DOCUMENT_VALUE_PERMISSIONS)[number];

/** Args for {@link Engine.drainEffects} — the drainer's identity is the
 *  engine client's token, like every other verb. */
export declare interface DrainEffectsArgs extends InstanceRefArgs {
  /**
   * Restrict to specific effect names. At least one name; an empty list
   * throws. Omitted considers every claimable entry, including ones no
   * handler covers, which `missingHandler` then decides.
   */
  names?: readonly string[];
  /**
   * Stop after dispatching this many effect entries, leaving the rest pending
   * for a later call. A whole number, one or more; anything else throws. One
   * entry counts once however many times its `retry` policy re-invokes the
   * handler. An entry skipped for a missing handler, or one another drainer
   * claimed first, does not count at all. Omitted dispatches every claimable
   * entry.
   */
  max?: number;
}

export declare interface DrainEffectsResult {
  /** The drained instance's pinned definition fingerprint — carried so the
   *  drain telemetry event can slice per definition. Absent only for
   *  instances pinned before content fingerprinting. */
  definitionContentHash?: string;
  drained: PendingEffect[];
  failed: PendingEffect[];
  skipped: PendingEffect[];
  /**
   * Entries this drainer dispatched without settling. Either another party
   * settled the entry first (a lease-expiry takeover, a manual recovery, or a
   * completion landing while a `retry` run waited out a backoff), or a `retry`
   * run stopped because the claim could no longer be held, which leaves the
   * entry pending for a later drain. The handler's side effect ran here too:
   * the at-least-once overlap the {@link EffectHandler} contract tells
   * handlers to tolerate.
   */
  lost: PendingEffect[];
}

/**
 * Driver-kind labels — the actor glyph for "who fired this action", recorded
 * on the `actionFired` history entry. Standalone for the same reason as
 * {@link ACTIVITY_KIND_DISPLAY}.
 */
export declare const DRIVER_KIND_DISPLAY: {
  person: {
    title: string;
    description: string;
  };
  agent: {
    title: string;
    description: string;
  };
  service: {
    title: string;
    description: string;
  };
  engine: {
    title: string;
    description: string;
  };
};

/**
 * What KIND of actor drove an action, recorded on the `actionFired` history
 * entry for the audit-trail "who did this?" glyph. Distinct from
 * {@link ActivityKind} (the intended execution lane) — any driver can fire
 * any kind. New entries stamp `'person'`; `'agent'`/`'service'`/`'engine'`
 * remain as read vocabulary for stored entries.
 */
export declare const DRIVER_KINDS: readonly [
  "person",
  "agent",
  "service",
  "engine",
];

export declare type DriverKind = (typeof DRIVER_KINDS)[number];

/** Actor-kind glyph for the audit trail — advisory only, never an
 *  authorization signal. */
export declare function driverKind(actor: Actor): DriverKind;

/**
 * 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.
 */
export declare type Editable = true | string;

/**
 * One declared-editable field in the current scope, projected for an actor: its
 * resolved value, whether this actor may edit it now (advisory), and the
 * provenance of the current value read off `opApplied` history. The reactive
 * surface a consumer renders as an inline field (the field widget itself is
 * out of scope here — see the field-component work).
 */
export declare interface EditableFieldEvaluation {
  scope: FieldScope;
  /** Present iff `scope === "activity"`. */
  activity?: ActivityName;
  name: string;
  type: FieldKind;
  title?: string;
  validation?: ScalarValidation;
  /** Eligible assignment roles for `assignee` / `assignees`; absent means unconstrained. */
  roles?: string[];
  /** The definition aliases used to interpret {@link EditableFieldEvaluation.roles}. */
  roleAliases?: RoleAliases;
  /** Current resolved value; `undefined` until the field is first resolved. */
  value: unknown;
  /** Whether THIS actor may edit the field right now (window + predicate + guard). */
  editable: boolean;
  /** Present iff `editable === false`. */
  disabledReason?: EditDisabledReason;
  /** Actor who last wrote the field (latest `opApplied`); absent if never written. */
  setBy?: Actor;
  /** When the field was last written (ISO); absent if never written. */
  setAt?: string;
  /** Derived state of the who-may-edit predicate. Present iff the effective
   *  editability is a predicate (not the unconditional `true`). */
  insight?: ConditionInsight;
}

/**
 * Why an editable field can't be edited by this actor right now — the edit-seam
 * twin of {@link DisabledReason}. First failing gate wins: the field must be
 * declared editable, its scope window open, no deployed guard denying the
 * instance write, and the who-may-edit predicate satisfied. Reuses the shared
 * `mutation-guard-denied` shape — an edit is the same instance-doc `update` an
 * action commit performs, so the same guard pre-flight applies.
 */
export declare type EditDisabledReason =
  | {
      kind: "not-editable";
    }
  | {
      kind: "instance-completed";
      completedAt: string;
    }
  | {
      /** The instance was hard-stopped via `abortInstance` — wins over
       *  `instance-completed` (aborted instances carry `completedAt` too). */
      kind: "instance-aborted";
      abortedAt: string;
    }
  | {
      /** The field's scope window is closed: an activity-scope field whose activity isn't
       *  active, or otherwise out of its editable window. */
      kind: "edit-window-closed";
      detail: string;
    }
  | {
      /** The field's effective `editable` predicate evaluated falsy for this
       *  actor (a role/predicate miss; the stage tighten-override is folded in). */
      kind: "editor-not-permitted";
      predicate: string;
    }
  | MutationGuardDenial;

export declare interface EditFieldArgs extends DedupableOperationArgs {
  /**
   * Which declared-editable field to write. Omit `scope` to resolve lexically
   * — the nearest declaring scope wins (activity, then stage, then workflow);
   * an explicit `activity` pins the match to that activity's field when the
   * bare name is ambiguous.
   */
  target: EditFieldTarget;
  /**
   * How to write: `set` replaces the value (reassign / reschedule), `append`
   * adds a row to an array field (a running log / todo list), `unset` clears it.
   * Default `set`.
   */
  mode?: EditMode;
  /**
   * The new value (for `set`) or row (for `append`), as plain JSON matching the
   * field's kind. Validated against the field kind in the op path; omit for
   * `unset`.
   */
  value?: unknown;
}

/** Edit-seam twin of {@link ActionDisabledError}: thrown by `editField` when
 *  the field can't be edited by the caller — except a guard denial, which is
 *  {@link MutationGuardDeniedError} across all verbs. Carries the structured reason. */
export declare class EditFieldDeniedError extends WorkflowError<"edit-field-denied"> {
  readonly reason: EditFieldDeniedReason;
  readonly target: {
    scope: FieldScope;
    field: string;
    activity?: string;
  };
  constructor(args: {
    target: {
      scope: FieldScope;
      field: string;
      activity?: string;
    };
    reason: EditFieldDeniedReason;
  });
}

/** The verdicts {@link EditFieldDeniedError} can carry — every {@link EditDisabledReason}
 *  except `mutation-guard-denied`, which escalates to {@link MutationGuardDeniedError}. */
export declare type EditFieldDeniedReason = Exclude<
  EditDisabledReason,
  {
    kind: "mutation-guard-denied";
  }
>;

export declare interface EditFieldTarget {
  /** Omit to resolve lexically — the nearest declaring scope wins (activity, then stage, then workflow). */
  scope?: FieldScope;
  field: string;
  /** Pins the match to that activity's field. A bare name already resolves activity-first; set this to disambiguate. */
  activity?: string;
}

export declare type EditMode = "set" | "append" | "unset";

/**
 * 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
 */
export declare type Effect = EffectFields<EffectRetry>;

/** Total commits one dispatch may make — the runaway-handler bound: without
 *  it, a looping reporter renews its own lease and appends history forever.
 *  2× the ceiling of 1%-granularity progress reporting. */
export declare const EFFECT_COMMIT_DISPATCH_CAP = 200;

/** Pending mid-dispatch commits one dispatch may hold before `commitOps` /
 *  `setProgress` throws synchronously. An awaiting handler never reaches it
 *  (its queue depth stays ≤ 1). */
export declare const EFFECT_COMMIT_QUEUE_DEPTH = 32;

/**
 * A `ctx.commitOps` / `ctx.setProgress` call hit one of the dispatch's
 * bounds. Thrown synchronously at the call site, not as a promise rejection:
 * a tight loop that forgot to `await` dies on its own stack at the bound
 * instead of spraying unhandled rejections invisible to the caller the bound
 * exists for.
 */
export declare class EffectCommitQueueOverflowError extends WorkflowError<"effect-commit-queue-overflow"> {
  readonly effectKey: string;
  readonly bound: "queue-depth" | "dispatch-cap";
  readonly limit: number;
  constructor(args: {
    effectKey: string;
    bound: "queue-depth" | "dispatch-cap";
    limit: number;
  });
}

/** The outcomes a completer may report through `completeEffect` — a run
 *  either succeeded or failed. `cancelled` is not reportable: only an abort
 *  stamps it, on entries that never dispatched. */
export declare type EffectCompletionStatus = Exclude<
  EffectRunStatus,
  "cancelled"
>;

/** @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;
};

/**
 * External effect handler — invoked at drain time with resolved `params` and
 * a context. Returning `outputs` records them on the run's `effectHistory`
 * row, read downstream as `$effects['<name>'].<output>`. Returning `ops`
 * applies the state half of the effect in the completion commit (`field.*`
 * only, never `status.set`) — every returned op must explicitly set
 * `target.scope`, since completion ops have no authoring location to infer
 * one from. Throwing fails the attempt, with no `ops`. Without a
 * {@link EffectRetry} policy on the node, or once one has spent its attempts
 * or closed its window, that failure settles the effect as failed. A policy
 * with attempts left inside its window dispatches again instead, unless the
 * drain finds between two attempts that it no longer holds the claim: then it
 * stops without settling and reports the entry as `lost`. That check happens
 * between attempts only. The completion itself stays first-writer-wins, so a
 * dispatch that runs to its end still reports its outcome and settles the
 * entry if it gets there first.
 *
 * Delivery is at-least-once: a handler MAY run more than once for the same
 * effect. Three causes. A dispatch can die after its side effect but before
 * commit. A lease can expire mid-dispatch and be taken over. And every
 * admitted attempt of a `retry` policy invokes the handler again. Completion
 * is first-writer-wins, and the losing run's completion is reported as `lost`.
 *
 * Write handlers to tolerate repetition. Derive external identifiers from
 * `ctx.effectKey` so the receiving system can dedupe: the key is stable across
 * every repeat, including all attempts of one policy run. Checking
 * `effectHistory[]` for a row keyed by `ctx.effectKey` before irreversible
 * work catches a repeat of an already-completed run, but never a retry
 * attempt, because a policy writes one history row when the whole run ends and
 * nothing records the attempt that just failed.
 *
 * The `bivarianceHack` indirection keeps this readable from the non-generic
 * `Engine` surface; only the typed drain invokes handlers.
 */
export declare type EffectHandler<
  Client extends WorkflowClient = WorkflowClient,
> = {
  bivarianceHack(
    params: Record<string, unknown>,
    ctx: EffectHandlerContext<Client>,
  ): Promise<{
    outputs?: Record<string, unknown>;
    ops?: FieldOp[];
  } | void>;
}["bivarianceHack"];

export declare type EffectHandlerContext<Client extends WorkflowClient> = {
  /** A concrete sibling of the `createEngine` client, bound to the workflow resource with the
   *  same credentials; untagged handler requests carry the `workflow.effect` tag by default. */
  client: Client;
  /** Resolve the client for a subject doc's own resource: a handler patching a foreign subject
   *  routes its write here — {@link client} addresses the instance's. Throws on a bare id. */
  clientFor: (ref: GdrUri | GlobalDocumentReference) => WorkflowClient;
  instanceId: string;
  effectKey: string;
  log: (message: string, extra?: Record<string, unknown>) => void;
  /** Mid-dispatch `field.*` commit gated on THIS dispatch's exact claim — a superseded claim
   *  writes nothing. Runs in call order, never coalesced; `idempotencyKey` is required. */
  commitOps: (req: CommitOpsRequest) => Promise<void>;
  /** Absolute progress, sugar over {@link commitOps}: `field.set`s a number (0–100, enforced at
   *  commit). Unlike `commitOps`, pending sets to one field coalesce — latest value wins. */
  setProgress: (target: ProgressTarget, value: number) => Promise<void>;
};

export declare interface EffectHistoryEntry {
  _key: string;
  name: EffectName;
  title?: string;
  description?: string;
  params: Record<string, unknown>;
  origin: EffectOrigin;
  actor?: Actor;
  /**
   * `_key` of the stage entry the run was queued under, carried from the
   * pending entry — the identity that makes the `$effectStatus` read
   * re-entry-safe (a timestamp tie could not be: same-commit loop-backs and
   * frozen test clocks stamp identical times). Absent only on rows persisted
   * before the engine stamped it; those never count as the current entry's
   * run (fail closed).
   */
  stageEntryKey?: string;
  ranAt: string;
  durationMs?: number;
  status: EffectRunStatus;
  detail?: string;
  error?: {
    message: string;
    stack?: string;
  };
  /**
   * Outputs the runtime reported back — the source the `$effects` read
   * derives from (`$effects['<effect name>'].<output>` is the latest
   * completed run's outputs, by name). Recorded here for audit.
   */
  outputs?: Record<string, unknown>;
}

export declare type EffectName = string;

/**
 * The effect key does not match any pending effect on the instance. When the
 * key matches an `effectHistory` row instead, `settled` carries that row's
 * outcome so a consumer can branch on WHY the entry is gone: a double
 * delivery on an at-least-once runtime (`done`/`failed` — the first
 * completion drained it, treat the retry as already-done), or an abort that
 * cancelled the entry before dispatch (`cancelled` — the reported work was
 * discarded, not recorded). `settled` absent means the key never existed.
 */
export declare class EffectNotFoundError extends WorkflowError<"effect-not-found"> {
  readonly instanceId: string;
  readonly effectKey: string;
  /** The matching `effectHistory` outcome, when the effect settled rather
   *  than never existed. */
  readonly settled?: EffectSettledInfo;
  constructor(args: {
    instanceId: string;
    effectKey: string;
    settled?: EffectSettledInfo;
  });
}

/**
 * Thrown when the ops an effect handler returns from its completion don't
 * parse against the stored op schema — a malformed `field.*` / `status.set`
 * (bad `type`, missing `target`, wrong `value` shape). The completion does not
 * commit; the engine has not mutated state. Mirrors {@link ActionParamsInvalidError}:
 * a handler is external code, so its returned ops are validated at the
 * completion boundary rather than trusted to be well-formed.
 */
export declare class EffectOpsInvalidError extends WorkflowError<"effect-ops-invalid"> {
  readonly effect: string;
  readonly issues: string[];
  constructor(args: { effect: string; issues: string[] });
}

export declare interface EffectOrigin {
  kind: EffectOriginKind;
  name: string;
}

/** The boundary that queued an effect — actions are the only effect
 *  carriers, so the kind is structural (kept on the row for
 *  self-description). */
export declare type EffectOriginKind = "action";

/**
 * Thrown when an effect completes with a returned output its declaration doesn't
 * allow — an undeclared key or a value that doesn't fit the declared shape. The
 * declared `outputs` are a strict allowlist bounding what an effect may persist
 * onto its `effectHistory` entry, so the completion does NOT commit rather than silently
 * storing off-contract data. An effect that declares no `outputs` has an EMPTY
 * allowlist (produces nothing), so any returned output fails here.
 */
export declare class EffectOutputsInvalidError extends WorkflowError<"effect-outputs-invalid"> {
  readonly effect: string;
  readonly issues: string[];
  constructor(args: { effect: string; issues: string[] });
}

/** `$effects`: each effect name → its LATEST completed run's outputs across the whole history. */
export declare function effectOutputsMap(
  instance: Pick<WorkflowInstance, "effectHistory">,
): Record<string, unknown>;

/**
 * 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.
 */
export 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`).
 */
export 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.
 */
export declare type EffectRetryKind = "engine";

/**
 * Every terminal state an effect run can record. `done` and `failed` are
 * reported through completion ({@link EffectCompletionStatus}); `cancelled`
 * is engine-stamped only — an abort cancelling the entry before dispatch.
 * A cancellation is not a failure: anything counting failures (dashboards,
 * retry tooling) must not count aborted-away effects among them.
 */
export declare type EffectRunStatus = "done" | "failed" | "cancelled";

/**
 * 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'`.
 */
export declare type EffectRuntimeBlock =
  | {
      kind: "function";
      timeout?: number | undefined;
      memory?: number | undefined;
    }
  | {
      kind: "durableFunction";
    }
  | {
      kind: "selfHosted";
    };

/** The `effectHistory` outcome {@link EffectNotFoundError} reports when the
 *  missing key belongs to a settled run. `detail` is the row's recorded
 *  detail — for a cancellation, the cause the canceller stamped. */
export declare interface EffectSettledInfo {
  status: EffectRunStatus;
  ranAt: string;
  detail?: string;
}

/** One declared effect plus a structural location string identifying where it
 *  sits in the definition (for diagnostics). */
export declare interface EffectSite {
  effect: Effect;
  location: string;
}

/**
 * Every effect a definition declares, with its location — the single source of
 * "where effects live": action `effects[]` (actions are the only payload
 * carriers). Effect names are unique per definition, so consumers can key by
 * `site.effect.name` cleanly.
 */
export declare function effectSites(def: WorkflowDefinition): EffectSite[];

export declare interface Engine {
  /** Engine-scoped bindings — exposed for the few advanced consumers
   *  (e.g. test bench, drain workers) that need them; the verbs already
   *  thread them through internally. */
  readonly client: WorkflowClient;
  readonly tag: string;
  readonly workflowResource: WorkflowResource;
  readonly effects: ResolvedEngineEffects;
  readonly logger: LoggerFactory;
  /** The resolved telemetry logger ({@link noopTelemetry} unless injected) —
   *  exposed so adapters built on the engine log through the same seam. */
  readonly telemetry: WorkflowTelemetryLogger;
  /** Resolve durable actor provenance through this engine's project client. */
  resolveActor: (
    args: ResolveClientActorArgs,
  ) => Promise<ActorResolution<ClientProjectUser>>;
  /** Validates and stores immutable definition versions. Content matching the
   *  latest deployed version's fingerprint keeps that version; otherwise,
   *  deployment creates the next version. Batch dependencies deploy children first. */
  deployDefinitions: <T extends WorkflowDefinitionInput<T>>(
    args: DeployDefinitionsArgs<T>,
  ) => Promise<DeployDefinitionsResult>;
  /** Starts an instance. `start.filter` is never a gate here — applicability
   *  belongs to `definitionsForDocument`, and an inapplicable definition
   *  starts without complaint. `instanceId` is the idempotency key: reusing
   *  it for the same start resumes; a different start throws. */
  startInstance: (args: StartInstanceArgs) => Promise<OperationResult>;
  /** Commits a caller-fired action and runs the resulting cascade. Actions
   *  declaring `when` cannot be fired through this method. Dispatch queued
   *  effects separately with {@link Engine.drainEffects}. */
  fireAction: (args: FireActionArgs) => Promise<OperationResult>;
  /** Edit a declared-editable field directly (the generic edit seam):
   *  reassign / reschedule / claim-by-hand / append-to-log, then cascade. */
  editField: (args: EditFieldArgs) => Promise<OperationResult>;
  /** Records an effect result, applies its completion field operations, and
   *  runs the resulting cascade. Use {@link Engine.drainEffects} to invoke
   *  registered handlers. */
  completeEffect: (args: CompleteEffectArgs) => Promise<OperationResult>;
  /** Commit mid-dispatch field state from a running effect handler — the
   *  verb behind `ctx.commitOps`. Gated on the dispatch's exact claim token;
   *  a successful commit renews the claim's lease. */
  commitEffectOps: (args: CommitEffectOpsArgs) => Promise<OperationResult>;
  /** Reevaluates an instance and commits enabled triggers and transitions
   *  until progression settles. A successful call reports `changed: false`
   *  when the instance remains unchanged. It does not run effect handlers;
   *  dispatch queued work with {@link Engine.drainEffects}. */
  tick: (args: OperationArgs) => Promise<OperationResult>;
  /** Project the instance from an actor's perspective — per-action verdicts
   *  with structured disabled reasons. Pure read. */
  evaluate: (args: EvaluateArgs) => Promise<WorkflowEvaluation>;
  /** Diagnose why an instance is or isn't progressing — a classified
   *  {@link DiagnoseResult} plus the evaluation it was derived from. */
  diagnose: (args: EvaluateArgs) => Promise<DiagnoseResult>;
  /** The actions firable on the instance's current stage, each flagged
   *  allowed/disabled, plus the evaluation they came from. */
  availableActions: (args: EvaluateArgs) => Promise<AvailableActionsResult>;
  /** Admin override — bypass filters/transitions and force the stage. */
  setStage: (args: SetStageArgs) => Promise<OperationResult>;
  /** Admin override — hard-stop an in-flight instance where it stands. */
  abortInstance: (args: AbortInstanceArgs) => Promise<OperationResult>;
  /** Changes a terminal activity in the current stage to `active` or `skipped`,
   *  then continues the cascade. Already-fired triggers do not fire again
   *  during the same stage visit. */
  resetActivity: (args: ResetActivityArgs) => Promise<OperationResult>;
  /** Admin override — remove a deployed definition (instances are only ever aborted, never deleted). */
  deleteDefinition: (
    args: DeleteDefinitionArgs,
  ) => Promise<DeleteDefinitionResult>;
  /** Fetch a workflow instance by id. */
  getInstance: (args: InstanceRefArgs) => Promise<WorkflowInstance>;
  /** The reactive {@link WatchSet} for an instance — every document whose
   *  change should re-evaluate it (the instance, its ancestors, and the docs
   *  named by `doc.ref`/`subject`/`doc.refs`/`release.ref` field entries on the workflow scope
   *  + current stage) as exploded {@link SubscriptionDocument}s, plus the
   *  instance's read perspective. Fetches the instance, then derives. A
   *  reactive adapter that already holds the live instance calls the pure
   *  `subscriptionDocumentsForInstance` directly instead, to avoid the re-fetch. */
  subscriptionDocumentsForInstance: (
    args: InstanceRefArgs,
  ) => Promise<WatchSet>;
  /** Opt into reactivity: bind the engine to an instance doc and get a stateful
   *  {@link InstanceSession}. Push the docs it lists in `subscriptionDocuments`
   *  via `update`, then `evaluate`/`tick`/`fireAction` against the held state —
   *  pushed content is never refetched. The session never observes or ticks on
   *  its own; the consumer drives it. */
  session: (args: SessionArgs) => InstanceSession;
  /** Every lake mutation guard this instance registered, unioned across the
   *  instance's own resource and the resource of each
   *  `doc.ref`/`subject`/`doc.refs` GDR it holds in state. For coherency
   *  refresh and housekeeping. */
  guardsForInstance: (args: InstanceRefArgs) => Promise<MutationGuardDoc[]>;
  /** Every lake mutation guard a workflow deployed (any version), across the
   *  datasources its guards statically name — the workflow resource plus any
   *  literal-GDR field entries, unioned over all deployed versions.
   *  Needs no live instance. Guards whose resource is only known per-instance
   *  (input/runtime-sourced entries) are not reachable here — use
   *  {@link Engine.guardsForInstance}. For housekeeping. Takes the
   *  definition's `name`. */
  guardsForDefinition: (
    args: GuardsForDefinitionArgs,
  ) => Promise<MutationGuardDoc[]>;
  /** Spawned children of a parent instance, optionally filtered by the
   *  spawning activity. Sorted by `startedAt` asc. */
  children: (args: ChildrenArgs) => Promise<WorkflowInstance[]>;
  /** The reverse of {@link Engine.subscriptionDocumentsForInstance}: every
   *  in-flight instance whose watch-set includes `document` (a resource-qualified
   *  GDR URI). For a non-reactive, content-change-driven runtime deciding which
   *  instances a changed doc should `tick`. Matches the same ref set the forward
   *  watch-set uses (self, ancestors, current-stage `doc.ref`/`subject`/`doc.refs`/`release.ref`)
   *  via the shared `collectWatchRefs`. Sorted by `startedAt` asc. */
  instancesForDocument: (
    args: InstancesForDocumentArgs,
  ) => Promise<WorkflowInstance[]>;
  /** The startable half of {@link Engine.instancesForDocument}: the latest
   *  deployed version of every definition that applies to the LOADED candidate
   *  document — startable, the `subject`-kind entry accepts its `_type`, and
   *  `start.filter` (browse-time-pure — `$fields` never binds) passes. All
   *  matches, name ascending; advisory — a start picker's filter, never
   *  enforcement. */
  definitionsForDocument: (
    args: DefinitionsForDocumentArgs,
  ) => Promise<DeployedDefinition[]>;
  /** Pre-flight `startInstance`'s gates for a definition + the
   *  `initialFields` gathered so far: structurally invalid rows, every
   *  requirement's ordered descriptor/outcome/insight, and still-missing
   *  required inputs. `allowed` is the overall startability signal; `outcome`
   *  aggregates the requirements. Bindability-aware — a requirement reading
   *  a not-yet-supplied entry (including `singleSubject`'s implicit subject
   *  read) reports `'unevaluable'` with the entries named
   *  in `unboundReads`, never a collapsed verdict.
   *  Pure read; the enforcement moment is `startInstance` itself. */
  evaluateStart: (args: EvaluateStartArgs) => Promise<StartEvaluation>;
  /** GROQ query against the engine's workflow resource. `$tag`
   *  is bound for tag-scoped filtering. */
  query: <T = unknown>(args: QueryArgs) => Promise<T>;
  /** Snapshot-aware GROQ — runs against the same in-memory view the
   *  engine's filters see for the supplied instance. The caller-free
   *  rendered scope cascade gates evaluate in is bound — the
   *  instance-derived vars ({@link FILTER_SCOPE_VARS}) with the open
   *  stage's overlay merged into `$fields`, `$assigned` at its caller-free
   *  `false`, plus the author's pre-evaluated `$<predicate>` booleans —
   *  ids in GDR URI form to match the snapshot's keying. */
  queryInScope: <T = unknown>(args: QueryInScopeArgs) => Promise<T>;
  /** List every pending effect on an instance. */
  listPendingEffects: (args: InstanceRefArgs) => Promise<PendingEffect[]>;
  /** Filter pending effects by claimed status and/or effect names. */
  findPendingEffects: (
    args: FindPendingEffectsArgs,
  ) => Promise<PendingEffect[]>;
  /** Dispatch unclaimed effects through registered handlers — including
   *  entries whose claim's lease expired, which are taken over (audit row)
   *  and redispatched. The drainer's identity is the engine client's token —
   *  a drain runtime supplies its own token-bearing client and declares
   *  itself via `executionContext`. Release-without-dispatch housekeeping is
   *  the standalone {@link sweepStaleClaims} export, deliberately off the
   *  engine surface. */
  drainEffects: (args: DrainEffectsArgs) => Promise<DrainEffectsResult>;
  /**
   * Inspect every deployed definition in the engine's tag and apply
   * the configured `effects.missingHandler` policy at `phase: "deploy"` for any
   * effect name without a registered handler. Catches "definition
   * shipped, handler removed" misconfigurations at startup instead of
   * three days later when the effect fires.
   *
   * Returns the list of (definitionId, name, locations) tuples it saw.
   * Throws if `effects.missingHandler` resolved as "fail" for any of them.
   */
  verifyDeployedDefinitions: () => Promise<VerifyDeployedDefinitionsResult>;
}

/**
 * The API surface the engine's reads and writes assume. The engine owns this
 * pin: every entry point — `createEngine`, each raw `workflow.*` verb, the
 * housekeeping exports — derives its working client onto this version via
 * {@link WorkflowClient.withConfig}, and `resourceClients`-resolved clients
 * are rebound the same way. A caller's configured `apiVersion` therefore
 * never reaches engine-owned traffic (the caller's own client instance is
 * untouched). Effect handlers keep the caller's `apiVersion`; their derived
 * clients change only the request-tag prefix. The other exception is a client
 * that lacks `withConfig` and so cannot be rebound — it must be built to serve
 * this version; see {@link WorkflowClient.withConfig}.
 */
export declare const ENGINE_API_VERSION = "2026-04-29";

/**
 * @internal Every lake document type the engine owns and writes for itself.
 * {@link acceptsDocumentType} reports one as unaccepted even by a subject
 * entry naming it explicitly, or one with no `types` at all. Shared with the
 * Studio plugin, which keeps them out of content pickers; not a supported
 * consumer API.
 */
export declare const _ENGINE_OWNED_DOCUMENT_TYPES: readonly string[];

/**
 * Everything this engine needs to run pending effects, in one group.
 * {@link Engine.drainEffects} dispatches through `handlers` under a
 * `leaseMs` claim, and both the drain and
 * {@link Engine.verifyDeployedDefinitions} apply `missingHandler` to an effect
 * name no handler covers.
 */
export declare interface EngineEffectsArgs<
  Client extends WorkflowClient = WorkflowClient,
> {
  /** Effect handlers keyed by the effect name the definition queues. */
  handlers?: Record<string, EffectHandler<Client>>;
  /**
   * Lease duration `drainEffects` stamps on each pending-effect claim.
   * Past the lease the claimer is presumed dead: the entry becomes
   * recoverable by another drain's takeover or by
   * the standalone `sweepStaleClaims` export. Default 5 minutes — size it well above
   * the slowest handler's honest runtime, since a live-but-slow dispatch
   * that outlives its lease can be redispatched (see {@link EffectHandler}).
   */
  leaseMs?: number;
  /** What to do with an effect name `handlers` doesn't cover. Default `fail`. */
  missingHandler?: MissingHandlerPolicy;
}

export declare interface EngineLogger {
  info: (message: string, extra?: Record<string, unknown>) => void;
  warn: (message: string, extra?: Record<string, unknown>) => void;
  error: (message: string, extra?: Record<string, unknown>) => void;
}

/**
 * The engine-scope bindings pinned once by `createEngine` and carried
 * explicitly on every raw `workflow.*` call. `Engine` methods never take
 * these — they were supplied at construction.
 */
export declare interface EngineScopeArgs {
  /**
   * The engine resolves its acting identity from this client's token and
   * caches the resolution per client object — the client's auth must be
   * stable for the engine's lifetime. To act as someone else, construct
   * an engine over a client bound to their token (`withConfig({token})`),
   * never mutate this client's auth in place.
   *
   * Any configured `apiVersion` works: every verb derives its working
   * client onto `ENGINE_API_VERSION`, on the raw namespace as much as
   * through `createEngine` — see {@link WorkflowClient.withConfig}.
   */
  client: WorkflowClient;
  /** Engine-scope environment partition — required. See {@link validateTag} + `tags.ts`. */
  tag: string;
  /**
   * The Sanity resource the engine's own data lives in. Used to mint
   * GDR URIs for every doc the engine writes (definitions, instances,
   * ancestor refs). Mirrors `@sanity/client`'s `ClientConfigResource`.
   */
  workflowResource: WorkflowResource;
  /**
   * Optional routing override for cross-resource reads (subject + ancestor
   * docs that live in a different Sanity resource than the workflow). Called
   * with a parsed GDR; return a client for that resource, or undefined to let
   * the engine route it — `client` for the workflow resource itself, a
   * sibling derived from `client`'s credentials for anything else. A served
   * resource is also part of the declared surface for runtime-supplied refs.
   * Engine-scope configuration — see `CreateEngineArgs`.
   */
  resourceClients?: ResourceClientResolver;
  /**
   * Declared execution context — the advisory "via what" stamped on every
   * history entry alongside the token-resolved actor. Construction-scope
   * configuration, never per-call: the runtime half is always inferred, and
   * the declared `{kind, id}` half labels the host (see `EXECUTION_KINDS`).
   * Omitted ⇒ runtime-only stamps.
   */
  executionContext?: DeclaredExecutionContext;
  /**
   * How long a recorded `idempotencyKey` dedupes retries (the
   * `processedRequests[]` row's lifetime). Default 24 hours. Size it to the
   * caller's longest retry horizon — a retry arriving after the row expired
   * re-executes the operation.
   */
  idempotencyTtlMs?: number;
}

/**
 * Pull the {@link GlobalDocumentReference} values out of `doc.ref` /
 * `subject` / `doc.refs` (content) field entries. Content only — release
 * field entries come from the shared release-ref projection, so guard discovery (which
 * reads this via `collectEntryDocUris`) stays scoped to content docs.
 */
export declare function entryDocRefs(
  entries: unknown,
): GlobalDocumentReference[];

/** The value's message — `Error.message`, else `String(value)` — with
 *  control characters stripped so server-derived error text can't smuggle
 *  terminal escape sequences into consumer output. */
export declare function errorMessage(err: unknown): string;

export declare interface EvaluateArgs {
  instanceId: string;
  /**
   * URL path on the supplied client where the engine should fetch
   * grants. The actor always token-resolves from the supplied client; without
   * a grants path the rendered `$can` is undefined, so conditions
   * referencing it fail closed — and the real Sanity write boundary
   * still enforces.
   *
   * Canvas resource example: `/canvases/<resourceId>/acl`.
   * Project/dataset example: `/projects/<id>/datasets/<dataset>/acl`.
   *
   * Result is cached per `(client, path)` for the lifetime of the
   * process — grants don't change often, and tearing them down per
   * call would mean a network round-trip on every fireAction.
   */
  grantsFromPath?: string;
}

/**
 * Evaluates an
 * instance, its definition, resolved actor/grants, and a snapshot to
 * report available actions and their blocking conditions. The
 * supplied snapshot is never refetched; guards using `->` may call the
 * supplied {@link EvaluateFromSnapshotArgs.guardDereference} resolver. An optional
 * {@link EvaluateFromSnapshotArgs.documentAvailability} reader supplies completed
 * evidence for missing references without replacing held content.
 * Feed it a fresh snapshot (e.g. rebuilt from a live store on change) for
 * reactive re-evaluation. Best-effort by design: verdicts are advisory,
 * not enforcement.
 */
export declare function evaluateFromSnapshot(
  args: EvaluateFromSnapshotArgs,
): Promise<WorkflowEvaluation>;

export declare interface EvaluateFromSnapshotArgs {
  instance: WorkflowInstance;
  definition: WorkflowDefinition;
  actor: Actor;
  /**
   * The actor's principal id in the workflow resource's own identity
   * namespace — the comparand for everything the resource's lake evaluates
   * (`identity()` in guard predicates, the anchor ACL's grant filters).
   * Omitted when it equals {@link Actor.id} (org-level resources, robots).
   */
  localPrincipalId?: string;
  /**
   * Resolved grants for the actor. Omit to leave the rendered `$can`
   * undefined (conditions referencing it fail closed — the real lake
   * write boundary still enforces).
   */
  grants?: Grant[];
  /**
   * Resolved org-level user attributes for the actor. Omit to leave the
   * rendered `$attributes` undefined (conditions referencing it fail
   * closed).
   */
  attributes?: UserAttributes;
  /**
   * The in-memory snapshot to evaluate against. The caller assembles it
   * from whatever source — a fetch-backed evaluation or a
   * live store. Every doc's `_id` must be in GDR-URI form, and `knownIds`
   * must contain exactly those IDs for missing-reference diagnostics.
   * Use {@link buildSnapshot} to construct both consistently.
   */
  snapshot: HydratedSnapshot;
  /** Resolve availability outside the snapshot's perspective. Without a reader, absence is reported without claiming deletion. */
  documentAvailability?: DocumentAvailabilityReader;
  /**
   * The `$now` reading every condition in this projection shares. Omit to
   * use {@link wallClock}; a reactive consumer (or the bench) passes its
   * own clock reading for a stable/deterministic timeline.
   */
  now?: string;
  /**
   * Live mutation guards held for this instance (a reactive adapter's
   * guard stream). Every action commit is an `update` write to the instance
   * doc, so a guard that matches the instance and denies that write disables
   * every action with `mutation-guard-denied`. Omit to skip the gate in this
   * projection — the engine's verb paths load live guards and re-check at
   * commit time (the runtime evaluation path fetches them itself).
   */
  guards?: readonly MutationGuardDoc[];
  /**
   * Stored-resource lookup for guard predicates using `->`. Omit when no
   * guard can dereference; missing lookups resolve `null` and deny fail-closed.
   */
  guardDereference?: GuardDereference;
  /**
   * Per-FOREIGN-subject-resource access — the actor's ACL grants PLUS the
   * actor's principal id in that resource's own namespace — keyed by
   * resource-shaped GDR (`<type>:<id>`); feeds the subject-write forecast on
   * effects-bearing actions ({@link SubjectPermissionDenial}). A resource
   * appears only when both halves resolved; omit it (or the whole map) to
   * skip that resource's forecast (degrade open — the subject's lake still
   * enforces). The runtime evaluation path resolves this through each
   * resource's own client.
   */
  resourceGrants?: ReadonlyMap<string, SubjectResourceAccess>;
}

/**
 * Evaluate a guard predicate against a mutation. Returns `true` only when the
 * predicate is strictly `true` (ALLOW). Empty predicates, parse failures, and
 * non-`true` results deny. A supplied dereference resolver's failure propagates
 * so infrastructure errors cannot masquerade as guard verdicts.
 */
export declare function evaluateMutationGuard(args: {
  guard: MutationGuardDoc;
  context: MutationContext;
  dereference?: GuardDereference;
}): Promise<boolean>;

/** Args for `evaluateStart` — the pre-flight read of `startInstance`'s gates
 *  for a definition + the `initialFields` gathered so far (possibly none). */
export declare interface EvaluateStartArgs {
  /** The definition's `name` — which deployed workflow would be started. */
  definition: string;
  /** Optional explicit version. Defaults to the highest deployed version. */
  version?: number;
  /**
   * The candidate seed, in `StartInstanceArgs.initialFields` shape. Partial
   * mid-form input is expected and safe: the verdict is BINDABILITY-AWARE —
   * when the predicate reads a declared entry these inputs don't supply,
   * `outcome` reports `'unevaluable'` and {@link StartEvaluation.unboundReads}
   * names the entries, instead of the collapsed answer GROQ equality would
   * otherwise produce (`null == x` is false, not null — a definitive-looking
   * verdict one more input could overturn, in either direction).
   */
  initialFields?: InitialFieldValue[];
}

/**
 * Evaluate one `start.filter` in the start-filter context: `document` (may
 * be absent — a root read is then GROQ null, fail-closed or vacuous-pass by
 * shape) as the GROQ root, the {@link StartScope} bindings plus
 * `$definition`, and — when `analyzeCondition` says the filter reads the
 * dataset — the scope's fetched slice as `*`. Cheap pure evaluation otherwise: no I/O rides a
 * filter that needs neither. GROQ null ("can't decide") is `false` — every consumer of
 * this verdict fails closed; a parse/evaluation THROW is a malformed
 * predicate, not an unevaluable one — rethrown loud, naming the definition,
 * so every read surface that evaluates the filter reports the same context.
 * A failed slice FETCH propagates as itself: transport trouble, never
 * definition blame.
 */
export declare function evaluateStartFilter(args: {
  filter: string;
  definition: Pick<ApplicabilitySource, "name">;
  document?: CandidateDocument | undefined;
  scope?: StartScope | undefined;
}): Promise<boolean>;

/**
 * Well-known {@link ExecutionContext.kind} values. The field is a free
 * string — these are the shipped vocabulary, not a closed set. `interactive`
 * is the generic human-session fallback when `studio`/`sdkApp` don't apply;
 * `server` is a proxy acting with a user's token; `drainer` is an
 * effect-drain runtime.
 */
export declare const EXECUTION_KINDS: {
  readonly interactive: "interactive";
  readonly server: "server";
  readonly cli: "cli";
  readonly mcp: "mcp";
  readonly drainer: "drainer";
  readonly script: "script";
  readonly test: "test";
  readonly studio: "studio";
  readonly sdkApp: "sdk";
};

/**
 * The stored stamp: self-asserted advisory provenance — "via what", distinct
 * from the actor's "who". Configured once at `createEngine`, never per call,
 * and never an authorization input. `runtime` is always present; the declared
 * half is optional.
 */
export declare interface ExecutionContext {
  /** Inferred JavaScript runtime: `browser` | `node` | `worker` | `edge` | `deno` | `bun` | `unknown`. */
  runtime: string;
  /** Declared role — free string; see {@link EXECUTION_KINDS} for the shipped vocabulary. */
  kind?: string;
  /** Declared instance label, e.g. `workflow-cli` or `publish-proxy`. */
  id?: string;
}

/**
 * The caller-provenance fields every engine event payload carries: the
 * engine's own view of the host that invoked it. `ExecutionContext.id` is
 * never reported.
 */
export declare interface ExecutionScopedEventData {
  /** The JavaScript runtime the engine inferred for itself, matching the
   *  `executionContext.runtime` the same operation stamps on its history
   *  entries. */
  executionRuntime: string;
  /** Where the operation came from: the host's declared
   *  {@link EXECUTION_KINDS} value projected onto the reported vocabulary,
   *  or `other` for a kind outside it. Absent when the host declared none. */
  executionKind?: ReportedExecutionKind;
}

/**
 * Executor classifications — who, if anyone, fires an activity's actions
 * (shape-derived; see `./activity-kind.ts`).
 */
export declare const EXECUTOR_CLASSIFICATION_DISPLAY: {
  autonomous: {
    title: string;
    description: string;
  };
  interactive: {
    title: string;
    description: string;
  };
  "off-system": {
    title: string;
    description: string;
  };
  hybrid: {
    title: string;
    description: string;
  };
};

/**
 * Who, if anyone, fires an activity's actions, derived ahead-of-time from
 * the activity's shape alone: `'autonomous'` = every action is cascade-fired
 * (no caller fires anything); `'interactive'` = only fireAction-fired
 * actions; `'off-system'` = `target` present; `'hybrid'` = mixed. Advisory,
 * rendered on insight/evaluation nodes — never gating.
 */
export declare const EXECUTOR_CLASSIFICATIONS: readonly [
  "autonomous",
  "interactive",
  "off-system",
  "hybrid",
];

export declare type ExecutorClassification =
  (typeof EXECUTOR_CLASSIFICATIONS)[number];

/**
 * Expand every `@<alias>:` reference in a definition to the physical GDR prefix
 * its alias binds to, returning a definition that carries only physical
 * references. Fails closed — naming the definition + alias — when a referenced
 * alias isn't bound: the check that stops a portable definition from deploying
 * against the wrong (or no) resource.
 *
 * Runs during deploy planning, BEFORE the content
 * fingerprint, so a deployed definition never carries a logical alias. The
 * stored references are physical, and a rebind (same source, a different alias
 * map) surfaces as changed content — a new version, never a silent shift in what
 * the workflow reads. A no-op when the definition references no aliases.
 *
 * Rewrites string VALUES only through a shared deep walk, skipping known prose
 * fields. A reference that stands alone
 * (the whole value is `@<alias>:<id>`, e.g. a literal `doc.ref`) must expand to a
 * well-formed GDR — a malformed one (`@content:a:b`, an empty id) is rejected
 * here rather than failing when an instance later reads it.
 */
export declare function expandResourceAliases(
  definition: WorkflowDefinition,
  resourceAliases: ResourceAliases | undefined,
): WorkflowDefinition;

export { explainCondition };

export { ExplainConditionArgs };

/**
 * Explain one start GROQ requirement in the start-requirement context: no root (the
 * subject rides `$fields.<entry>.id` — deploy rejects a root read), the
 * {@link StartScope} bindings plus `$definition` and the caller's `$fields`
 * map, and the scope's fetched slice as `*` when the predicate reads the
 * dataset. Returns the full {@link ConditionInsight} — `outcome` is the
 * verdict (`'satisfied'` allows; `'unsatisfied'`/`'unevaluable'` refuse,
 * fail-closed) and the atom breakdown is what lets a surface disable its
 * start affordance AND say why. One evaluator serves both moments:
 * `startInstance` enforces the outcome, the `evaluateStart` verb pre-flights
 * it.
 *
 * A dataset-reading predicate with no slice provider THROWS instead of
 * failing closed: unlike a picker that merely hides a row, this verdict
 * refuses starts — evaluating over an empty `*` would let a `count()`-style
 * rule pass vacuously, and a silent "not allowed" would misreport a caller
 * bug as an author verdict. Parse/evaluation throws rethrow naming the
 * definition, like the filter's; a failed slice FETCH propagates as itself.
 */
export declare function explainStartRequirement(args: {
  query: string;
  definition: Pick<ApplicabilitySource, "name" | "fields">;
  /** The caller's input entries as a `$fields` map — the engine verbs build
   *  it with `startFieldsParam` (field resolution's projection), so the
   *  predicate can only see values the resolution would persist. */
  fields: Record<string, unknown>;
  scope?: StartScope | undefined;
}): Promise<ConditionInsight>;

/**
 * Extract the bare document `_id` from a GDR URI — what
 * `*[_id == $docId]` in GROQ needs.
 */
export declare function extractDocumentId(gdrUriString: string): string;

/** `resourcePath` is caller-supplied so this works for both project ACLs and a dedicated workflow-collaboration resource. */
declare function fetchGrants(args: {
  client: {
    request: NonNullable<WorkflowClient["request"]>;
  };
  resourcePath: string;
  signal?: AbortSignal;
}): Promise<Grant[]>;

/**
 * Field-entry `_type` discriminators. The entry's kind defines what
 * shape `value` takes (single GDR vs array, scalar vs notes log).
 */
export declare const FIELD_KIND_DISPLAY: {
  "doc.ref": {
    title: string;
    description: string;
  };
  "doc.refs": {
    title: string;
    description: string;
  };
  subject: {
    title: string;
    description: string;
  };
  "release.ref": {
    title: string;
    description: string;
  };
  string: {
    title: string;
    description: string;
  };
  text: {
    title: string;
    description: string;
  };
  number: {
    title: string;
    description: string;
  };
  progress: {
    title: string;
    description: string;
  };
  boolean: {
    title: string;
    description: string;
  };
  date: {
    title: string;
    description: string;
  };
  dueDate: {
    title: string;
    description: string;
  };
  datetime: {
    title: string;
    description: string;
  };
  dueDatetime: {
    title: string;
    description: string;
  };
  url: {
    title: string;
    description: string;
  };
  actor: {
    title: string;
    description: string;
  };
  assignee: {
    title: string;
    description: string;
  };
  assignees: {
    title: string;
    description: string;
  };
  object: {
    title: string;
    description: string;
  };
  array: {
    title: string;
    description: string;
  };
};

/**
 * 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;
};

export declare interface FieldDescription {
  /** The field's footprint — present even when nothing is proposable. */
  involvement: InsightPhrase;
  /** One phrase per verified proposal. */
  proposals: InsightPhrase[];
}

/**
 * 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
 */
export 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;
};

/**
 * Everything the evaluation derived about one `$fields` entry. `involvedIn`
 * is the field's full footprint — every gate whose condition reads it —
 * independent of whether any single value flips anything. Scope caveat: the
 * name is the RENDERED scope name; a stage-/activity-scope declaration
 * shadows a workflow-scope one lexically, so the same name in two sites'
 * scopes can denote two declarations.
 */
export declare interface FieldInsight {
  /** The field entry name — the head segment of every read below. */
  field: string;
  /** The distinct `$fields` reads naming this field across all sites. */
  reads: ConditionRead[];
  /** Every site whose condition reads this field. */
  involvedIn: InsightSite[];
  /** Verified single-value proposals harvested from blocking atoms; empty
   *  when nothing solvable blocks on this field. */
  proposals: FieldProposal[];
}

export declare type FieldKind = keyof FieldValueMap;

/**
 * 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.
 */
export 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.
 */
export declare type FieldOp = FieldMutationOp<StoredFieldRef>;

/**
 * A concrete value a blocking atom pins for this field, with the verified
 * consequences of assigning it — "setting `legalApproved` to `true` flips
 * transition `to-publish` to satisfied". Verified by re-evaluating every
 * site that reads the field, so a listed consequence is what the engine
 * would actually conclude, not a syntactic guess.
 */
export declare interface FieldProposal {
  assign: ScopeAssignment;
  consequences: SiteConsequence[];
}

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

/**
 * The three field scopes a field entry can live in. Also the
 * group-declaration levels: a `groups` array lives at exactly these three
 * nodes, so `DefinitionGroupSite.level` reuses this vocabulary.
 */
export declare type FieldScope = "workflow" | "stage" | "activity";

/**
 * 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.
 */
export 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.
 */
export declare type FieldSource = FieldSourceInternal;

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

/** Shared diagnostic field-address label for workspace consumers; unsupported outside this workspace.
 * @internal
 */
export declare function _fieldTargetLabel(target: EditFieldTarget): string;

/**
 * Every leaf replaced by its type name (`null` distinct from `object`); keys sorted by
 * UTF-16 code unit, not locale collation, so the shape canonicalises identically on every
 * machine.
 */
export declare function fieldTreeShape(value: unknown): unknown;

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

export declare interface FieldValueMap {
  "doc.ref": GlobalDocumentReference | null;
  "doc.refs": GlobalDocumentReference[];
  /** THE document the workflow is about — same value as
   *  {@link FieldValueMap."doc.ref"}, distinct kind so the runtime and UI
   *  identify the subject deterministically (workflow scope, at most one). */
  subject: GlobalDocumentReference | null;
  "release.ref": ReleaseRef | null;
  string: string | null;
  /** Multiline string — same value as {@link FieldValueMap.string}, distinct kind for rendering. */
  text: string | null;
  number: number | null;
  /** Application-defined 0–100 completion — same stored value as
   *  {@link FieldValueMap.number}, distinct kind so surfaces can elevate it;
   *  always finite and within 0–100 inclusive (fractions allowed). */
  progress: number | null;
  boolean: boolean | null;
  /** Date-only (`YYYY-MM-DD`), no time component. */
  date: string | null;
  /** THE due date of a level — same value as {@link FieldValueMap.date}. */
  dueDate: string | null;
  /** ISO-8601 timestamp. */
  datetime: string | null;
  /** THE due datetime of a level — same value as {@link FieldValueMap.datetime}. */
  dueDatetime: string | null;
  url: string | null;
  actor: Actor | null;
  /** Assignment members with at most one user; role members do not consume that cardinality. */
  assignee: Assignee[];
  assignees: Assignee[];
  /** An object with named sub-fields; the value is keyed by sub-field name. */
  object: Record<string, unknown> | null;
  /** An array of objects, each shaped by the kind's declared `of` sub-fields. */
  array: Record<string, unknown>[];
}

export declare class FieldValueShapeError extends WorkflowError<"field-value-shape"> {
  readonly entryType: string;
  readonly entryName: string;
  readonly issues: string[];
  constructor(args: {
    entryType: string;
    entryName: string;
    issues: string[];
    mode: "value" | "item";
  });
}

/**
 * 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[];

/** Returns `undefined`, never throws, for an activity an instance's pinned snapshot names but the definition has since renamed or removed. */
export declare function findActivityNode(args: {
  activityName: string;
  definition: WorkflowDefinition | undefined;
  stageName: string;
}): Activity | undefined;

/**
 * The current stage's {@link ActivityEntry} named `activityName`, or
 * `undefined` when the open stage holds no such activity (including when
 * `activityName` is itself `undefined`). Composes {@link findOpenStageEntry}
 * with the by-name lookup that activity ops, editability, params, and the
 * operation pre-flights all need — callers keep their own `.status` / `.fields`
 * chain off the result.
 */
export declare function findCurrentActivityEntry(
  host: {
    stages: StageEntry[];
    currentStage: StageName;
  },
  activityName: ActivityName | undefined,
): ActivityEntry | undefined;

/**
 * The open (un-exited) {@link StageEntry} matching `currentStage`, or
 * `undefined`. On loop-backs (re-entering a stage) several entries share
 * a name — the prior ones have `exitedAt` set, the current one does not.
 * Reads the `stages` + `currentStage` shape shared by the persisted
 * `WorkflowInstance` and the engine's mutable copy.
 */
export declare function findOpenStageEntry(host: {
  stages: StageEntry[];
  currentStage: StageName;
}): StageEntry | undefined;

export declare interface FindPendingEffectsArgs extends InstanceRefArgs {
  /**
   * Filter on claim PRESENCE — not protection. An entry whose claim's lease
   * expired still reports `claimed: true` here, yet a drain may take it
   * over; mirror the drainable set with {@link isClaimExpired} over the
   * returned entries' claims.
   */
  claimed?: boolean;
  /** Restrict to specific effect names. */
  names?: string[];
}

/** Returns `undefined`, never throws, for a stage an instance's pinned snapshot names but the definition has since renamed or removed. */
export declare function findStageNode(args: {
  definition: WorkflowDefinition | undefined;
  stageName: string;
}): Stage | undefined;

export declare interface FireActionArgs extends DedupableOperationArgs {
  activity: string;
  action: string;
  /**
   * Caller-supplied params for the action. Validated against
   * `Action.params[]` before commit; missing/required mismatch throws
   * `ActionParamsInvalidError`. Resolved values feed `ValueExpr.param`
   * lookups in ops and effect bindings.
   */
  params?: Record<string, unknown>;
  /**
   * If true, no-op (instead of throwing) when the activity is missing from
   * the current stage's `activityStatus` — typically because the workflow
   * has already advanced past it. Distinct from `idempotencyKey`: this flag
   * tolerates a *state* the fire no longer applies to (however it got
   * there, including someone else's action), while the key dedupes a retry
   * of *this specific request*. A drive script tolerating advanced
   * workflows wants the flag; a queue consumer redelivering a message
   * wants the key.
   */
  idempotent?: boolean;
}

/**
 * The flow consequence of one caller fire, computed by replaying it in
 * memory through the same machinery a real commit runs — never by a
 * parallel model of it. State-dependent: it answers "now", not "always".
 */
export declare interface FiringConsequence {
  /** The replayed commit's cascade exits the current stage in its first
   *  hop. `false` is a definite answer for the current state — including
   *  a selection halted by an unevaluable trigger, which holds the stage. */
  exitsStage: boolean;
  /** The transition the selection picked, present iff `exitsStage`. */
  transition?: string;
}

export { formatRead };

/**
 * Creates a {@link GdrUri} for a document in the supplied resource. Dataset
 * document IDs must be stable; `drafts.` and `versions.<release>.` prefixes
 * throw. Select draft or release content through {@link WorkflowInstance.perspective}.
 */
export declare function gdrFromResource(
  res: WorkflowResource,
  documentId: string,
): GdrUri;

/**
 * Creates a typed document reference in the supplied resource. Dataset
 * references require a stable document ID, as described by {@link gdrFromResource}.
 */
export declare function gdrRef<TType extends string = string>({
  res,
  documentId,
  type,
}: {
  res: WorkflowResource;
  documentId: string;
  type: TType;
}): GlobalDocumentReference<TType>;

/**
 * Global Document References (GDR).
 *
 * Every cross-document reference in the engine API uses this shape so
 * workflow state can live in one Sanity resource while subjects /
 * ancestors / effect-binding refs point at docs in *different* resources.
 *
 * Resource schemes mirror `@sanity/client`'s `ClientConfigResource`
 * discriminator. A GDR id is a typed URI:
 *
 *   dataset:<projectId>:<dataset>:<documentId>
 *   canvas:<resourceId>:<documentId>
 *   media-library:<resourceId>:<documentId>
 *   dashboard:<resourceId>:<documentId>
 *
 * The `type` field carries the doc's schema `_type` so consumers don't
 * need a separate lookup to know what they're pointing at.
 */
export declare type GdrScheme =
  | "dataset"
  | "canvas"
  | "media-library"
  | "dashboard";

/**
 * Resource-qualified document URI with a {@link GdrScheme} prefix. Construct
 * it with {@link gdrUri}, {@link gdrFromResource}, or {@link refDataset}.
 * Use {@link parseGdr} to validate a string's complete addressing format.
 *
 * Dataset URIs require the stable document ID, such as `article-1`, without
 * a `drafts.` or `versions.<release>.` prefix. Select draft and release
 * content through {@link WorkflowInstance.perspective}.
 */
export declare type GdrUri = `${GdrScheme}:${string}`;

/**
 * Creates a {@link GdrUri} from addressing parts. For datasets, `documentId`
 * must be the stable ID; `drafts.` and `versions.<release>.` prefixes throw.
 * Select draft or release content through {@link WorkflowInstance.perspective}.
 */
export declare function gdrUri(
  parts:
    | {
        scheme: "dataset";
        projectId: string;
        dataset: string;
        documentId: string;
      }
    | {
        scheme: "canvas" | "media-library" | "dashboard";
        resourceId: string;
        documentId: string;
      },
): GdrUri;

/**
 * The engine's reference value — deliberately NOT a lake reference, and
 * spelled differently on purpose (`id`/`type`, never `_ref`/`_id`):
 *
 * - **`id` is a URI, not a bare doc id**, because workflow references cross
 *   resources (another dataset, a media library) and a bare `_id` is only
 *   meaningful inside one dataset. Everything resource-aware — client
 *   routing, spawn discovery, guard target resolution — reads the resource
 *   out of this URI. It is stripped to a bare lake id at exactly one
 *   boundary: `paramsForLake` (core/params.ts), when a query actually runs
 *   against a lake.
 * - **`type` carries the target's schema type so consumers don't need a
 *   fetch — as stamped by the ref's constructor, never verified against the
 *   target.** Engine-built refs stamp it from real data (a projection row's
 *   `_type`, the `releaseRef` constructor); a caller-supplied ref's `type`
 *   is a trusted claim. Three advisory surfaces read it: the declared-subject-type
 *   contract (an entry's `types: [...]` accepts/rejects incoming refs —
 *   `refTypeIssues` at start `initialFields` and spawn `with`), start
 *   applicability ("which definitions accept a doc of this `_type`" —
 *   `acceptsDocumentType`), and guard `match.types` inference from resolved
 *   targets (`resolveMatchTypes`). All must work when the target lives in a
 *   resource the reader can't (or shouldn't) fetch from.
 *
 * In rendered GROQ this shape is what a reference-held value exposes
 * (`$fields.<entry>.id` / `.type`) — whereas `_id`/`_type` belong to
 * documents you hold (lake rows, `$row`, a dereferenced singular `doc.ref`).
 * The spelling is not a namespace guarantee: a content document can carry
 * its own `id`/`type` fields — what you're reading follows what the entry's
 * declared kind puts in your hand, never the key's spelling.
 *
 * `TType` preserves the `type` literal the constructors ({@link refDataset},
 * {@link gdrRef}, …) were called with, so a constructed ref satisfies
 * literal-typed targets (e.g. a `release.ref` value's `"system.release"`).
 */
export declare interface GlobalDocumentReference<
  TType extends string = string,
> {
  /** URI: `<scheme>:<...id-parts>` */
  id: GdrUri;
  /** Document `_type` (schema name) */
  type: TType;
}

/**
 * Filters are GROQ strings evaluated through groq-js with the document as
 * the dataset and the caller's principal id as `identity()`. Grants compose
 * most-permissive-wins.
 */
export declare interface Grant {
  filter: string;
  permissions: DocumentValuePermission[];
}

/**
 * Does the supplied `grants` set grant `permission` on `document` for
 * the given user? Walks each grant; a grant counts iff its filter
 * matches AND it lists the permission. Most-permissive wins.
 */
declare function grantsPermissionOn(args: {
  document?: {
    _id?: string;
    _type?: string;
    [key: string]: unknown;
  };
  grants: Grant[];
  permission: DocumentValuePermission;
  userId?: string;
}): Promise<boolean>;

/**
 * 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.
 */
export 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.
 */
export declare type Group = {
  name: string;
  title?: string | undefined;
  description?: string | undefined;
  kind?: GroupKind | undefined;
};

/**
 * Group-kind labels — the informational role of a declared group. Standalone
 * for the same reason as {@link ACTIVITY_KIND_DISPLAY}. A consumer reading a
 * definition as data and meeting an unknown kind (deployed by a newer engine)
 * must treat it as unset — a plain group; the strict engine parse itself
 * rejects unknown kinds, like every stored enum.
 */
export declare const GROUP_KIND_DISPLAY: {
  core: {
    title: string;
    description: string;
  };
  details: {
    title: string;
    description: string;
  };
};

/**
 * 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.
 */
export declare const GROUP_KINDS: readonly ["core", "details"];

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

/** A group member's address — enough to locate the node without the definition. */
export declare type GroupMember =
  | {
      kind: "field";
      scope: FieldScope;
      stage?: string;
      activity?: string;
      name: string;
    }
  | {
      kind: "activity";
      stage: string;
      name: string;
    }
  | {
      kind: "action";
      stage: string;
      activity: string;
      name: string;
    };

/**
 * 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.
 */
export declare type GroupMembership = string | string[];

/** The names in a `group` membership, normalised to a fresh list ([] when absent). */
export declare function groupMembershipNames(
  group: GroupMembership | undefined,
): string[];

/**
 * Every group a definition declares, in stable order: workflow groups, then
 * per stage — the stage's groups, then per activity — the activity's groups.
 * A membership that resolves to no declaration (rejected at deploy) is
 * omitted — no site is invented for it.
 */
export declare function groupSitesOf(
  definition: WorkflowDefinition,
): DefinitionGroupSite[];

/**
 * 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
 */
export declare type Guard = v.InferOutput<typeof GuardSchema>;

/**
 * The enforcement story hangs off this type: the lake does not evaluate
 * this doc type — it is the engine's placeholder for the lake's
 * forthcoming guard primitive (the lake reserves `system.*`). Until that
 * primitive ships, deployed guards deny OPTIMISTICALLY engine-side only, on
 * every project plan, and the lake ACL is the only hard gate. At cutover the
 * `temp.` prefix drops here, in exactly one place, and deployed guards become
 * lake-enforced (a breaking type change for already-persisted guard docs).
 */
export declare const GUARD_DOC_TYPE = "temp.system.guard";

export declare const GUARD_OWNER = "robot:workflow-engine";

/**
 * 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;
}[];

export declare type GuardAction = MutationGuardAction;

export declare type GuardDereference = (ref: {
  _ref: string;
}) => PromiseLike<Record<string, unknown> | null>;

/**
 * A stored guard's match criteria. See {@link AuthoringGuard} for matching
 * rules; stored `idRefs` contains strings instead of typed {@link GuardRead}s.
 */
export declare type GuardMatch = Guard["match"];

/**
 * Does this guard's `match` apply to a mutation on the given document?
 * `types` and id facets are ANDed; an unspecified facet does not constrain.
 */
export declare function guardMatches({
  guard,
  doc,
  action,
}: {
  guard: MutationGuardDoc;
  doc: {
    id: string;
    type?: string;
  };
  action: MutationGuardAction;
}): boolean;

/**
 * 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.
 */
export 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
>;

/**
 * All guards a workflow's definition deployed, unioned across the datasources
 * its guards statically name — no live instance required. Guard docs are
 * stamped with the version-less definition, so this spans the datasources
 * declared across ALL deployed versions
 * (`definitions`), not just the latest.
 *
 * A datasource is statically reachable when a guard idRef resolves to a
 * hardcoded GDR literal — directly, or via a `fieldRead` of a field entry whose
 * `initialValue` is a literal GDR — or to the workflow resource (`self`, or a
 * `query`-sourced field entry, which restamps into it). Guards whose resource is
 * only known once an instance exists — reading a `subject` / `input` / otherwise
 * runtime-sourced field entry — are NOT reachable here; that is the per-instance boundary, use
 * {@link guardsForInstance}. Dedups resources by key, results by `_id`.
 */
export declare function guardsForDefinition(
  args: DefinitionGuardsQueryArgs,
): Promise<MutationGuardDoc[]>;

export declare interface GuardsForDefinitionArgs {
  /** The definition's `name`. */
  definition: string;
}

/**
 * All guards this instance registered, unioned across every resource it
 * touches. Dedups resources by resource key and results by `_id`.
 * Housekeeping only — never a verdict input ({@link verdictGuardsForInstance}
 * owns that), since this union reads datasources outside the engine's trust
 * boundary.
 */
export declare function guardsForInstance(
  args: InstanceGuardsQueryArgs,
): Promise<MutationGuardDoc[]>;

/** Every guard in one resource, regardless of which workflow registered it. */
export declare function guardsForResource(
  client: WorkflowClient,
): Promise<MutationGuardDoc[]>;

export { guillemets };

/**
 * Computes a deterministic, non-cryptographic fingerprint of authored
 * definition content. The result is 16 lowercase hexadecimal characters.
 * Object-key order does not affect it; array order and field values do.
 * Pass authored content without stored-document envelope fields: this
 * function strips none of them. The authoring-only `runtime` block is the one
 * key it ignores, so two definitions that differ only in a hosting kind
 * fingerprint identically.
 */
export declare function hashDefinitionContent(def: WorkflowDefinition): string;

/** Whether the definition declares a `singleSubject` start requirement. */
export declare function hasSingleSubjectRequirement(
  definition: Pick<ApplicabilitySource, "start">,
): boolean;

/**
 * History-entry `_type` discriminators. Order roughly matches the
 * order a typical run produces them in a single fire-action commit.
 */
export declare const HISTORY_DISPLAY: {
  stageEntered: {
    title: string;
    description: string;
  };
  stageExited: {
    title: string;
    description: string;
  };
  activityStatusChanged: {
    title: string;
    description: string;
  };
  actionFired: {
    title: string;
    description: string;
  };
  transitionFired: {
    title: string;
    description: string;
  };
  effectQueued: {
    title: string;
    description: string;
  };
  effectCompleted: {
    title: string;
    description: string;
  };
  effectClaimReleased: {
    title: string;
    description: string;
  };
  spawned: {
    title: string;
    description: string;
  };
  subworkflowAdopted: {
    title: string;
    description: string;
  };
  subworkflowResolved: {
    title: string;
    description: string;
  };
  subworkflowOrphaned: {
    title: string;
    description: string;
  };
  aborted: {
    title: string;
    description: string;
  };
  opApplied: {
    title: string;
    description: string;
  };
  fieldQueryDiscarded: {
    title: string;
    description: string;
  };
};

/**
 * One appended audit row. Every `actor` stamp on one is token-resolved
 * advisory provenance, never authenticated identity — the lake's own document
 * history is the authenticated ground truth.
 *
 * On the three stage-movement arms, `via` discriminates a condition-driven
 * transition (`'transition'`, the default when absent) from an admin override
 * (`'setStage'`), and the `reason` beside it is that override's free text.
 */
export declare type HistoryEntry = HistoryEvent & {
  /**
   * The execution environment that committed this entry — inferred
   * runtime plus the host's declared `{kind, id}` (see
   * {@link ExecutionContext}). Stamped centrally at persist time on every
   * entry the engine appends; absent only on entries stored before the
   * stamp existed.
   */
  executionContext?: ExecutionContext;
};

/** @inline */
declare type HistoryEvent =
  | {
      _key: string;
      _type: "stageEntered";
      at: string;
      stage: StageName;
      fromStage?: StageName;
      transition?: string;
      via?: "transition" | "setStage";
      reason?: string;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "stageExited";
      at: string;
      stage: StageName;
      toStage: StageName;
      transition?: string;
      via?: "transition" | "setStage";
      reason?: string;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "activityStatusChanged";
      at: string;
      stage: StageName;
      activity: ActivityName;
      from: ActivityStatus;
      to: ActivityStatus;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "actionFired";
      at: string;
      stage: StageName;
      activity: ActivityName;
      action: ActionName;
      actor?: Actor;
      driverKind?: DriverKind;
      /** The engine fired this action in a cascade: `actor` is the cascading token that
       *  executed it, not a caller who invoked `fireAction`. */
      triggered?: true;
    }
  | {
      _key: string;
      _type: "transitionFired";
      at: string;
      fromStage: StageName;
      toStage: StageName;
      transition?: string;
      via?: "transition" | "setStage";
      reason?: string;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "effectQueued";
      at: string;
      effectKey: string;
      effect: EffectName;
      origin: EffectOrigin;
    }
  | {
      _key: string;
      _type: "effectCompleted";
      at: string;
      effectKey: string;
      effect: EffectName;
      status: EffectRunStatus;
      outputs?: Record<string, unknown>;
      detail?: string;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "effectClaimReleased";
      at: string;
      effectKey: string;
      effect: EffectName;
      claim: PendingEffectClaim;
      /** `drain-takeover` = a drain redispatched it; `sweep` = `sweepStaleClaims` released it. */
      via: "drain-takeover" | "sweep";
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "spawned";
      at: string;
      activity: ActivityName;
      instanceRef: GlobalDocumentReference;
      /** Identity of the `forEach` row that produced this child. */
      rowKey?: string;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "subworkflowAdopted";
      at: string;
      stage: StageName;
      activity: ActivityName;
      instanceRef: GlobalDocumentReference;
      rowKey: string;
    }
  | {
      _key: string;
      _type: "subworkflowResolved";
      at: string;
      activity: ActivityName;
      instanceRef: GlobalDocumentReference;
      status: "done" | "aborted";
    }
  | {
      _key: string;
      _type: "subworkflowOrphaned";
      at: string;
      /** A child naming this instance in its `ancestors` reached terminal, but no registry
       *  row matches it — its completion cannot drive any gate. A loud dead-end record. */
      instanceRef: GlobalDocumentReference;
      detail: string;
    }
  | {
      _key: string;
      _type: "aborted";
      at: string;
      stage: StageName;
      reason?: string;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "opApplied";
      at: string;
      stage: StageName;
      /** The op's boundary: an action fire sets `activity` + `action`; an edit sets `edit`
       *  (plus `activity` for an activity-scope field); completion ops set `effect`. */
      activity?: ActivityName;
      action?: ActionName;
      edit?: true;
      effect?: EffectName;
      opType: string;
      target?: {
        scope: FieldScope;
        field: string;
      };
      resolved?: Record<string, unknown>;
      actor?: Actor;
    }
  | {
      _key: string;
      _type: "fieldQueryDiscarded";
      at: string;
      scope: FieldScope;
      field: string;
      detail: string;
    };

export { humanize };

/** The in-memory groq-js dataset the engine's filters evaluate against. */
export declare interface HydratedSnapshot {
  /** Hydrated docs, keyed by GDR URI as `_id`. */
  docs: SanityDocument[];
  /** The GDR URIs of every document in `docs`, used to diagnose missing references. */
  knownIds: Set<string>;
}

/** Assignment ownership for list/read surfaces. Role aliases deliberately do
 *  not apply: aliases widen authorization, not whose inbox a literal pool
 *  member routes work into. */
export declare function identityMatchesAssignment(
  members: readonly Assignee[],
  identity: AssignmentIdentity,
): boolean;

/**
 * The in-flight arm — the one spelling of "not completed/aborted" every
 * list surface's `includeCompleted` filter negates (the engine stamps
 * `completedAt` on entry into any terminal stage, aborts included). A
 * sibling of {@link tagScopeFilter} for list builders that compose their
 * own conditions.
 */
export declare function inFlightFilter(): string;

/** Why one caller-supplied initial-field row cannot be consumed. */
export declare type InitialFieldIssue = {
  index: number;
  name: string;
  type: FieldKind;
} & (
  | {
      reason: "duplicate";
      duplicateIndexes: number[];
    }
  | {
      reason: "undeclared";
    }
  | {
      reason: "wrong-kind";
      expectedTypes: FieldKind[];
    }
  | {
      reason: "not-input";
      source:
        | "working-memory"
        | Exclude<NonNullable<FieldEntry["initialValue"]>["type"], "input">;
    }
  | ({
      reason: "invalid-scope";
      stage: string;
      declaredType: FieldKind;
    } & (
      | {
          scope: "stage";
        }
      | {
          scope: "activity";
          activity: string;
        }
    ))
);

/**
 * Explain every structural reason caller-supplied initial-field rows cannot
 * be consumed. Value-shape validation remains in the resolver because it
 * needs the matched declaration's complete schema.
 */
export declare function initialFieldIssues(
  args: ScopedInitialFieldDeclarations & {
    initialFields: readonly InitialFieldValue[];
  },
): InitialFieldIssue[];

/**
 * Thrown before start writes when one or more caller-supplied `initialFields`
 * rows cannot be consumed by workflow-scope, input-sourced declarations.
 * `issues` is stable machine-readable remediation context; the message renders
 * the same complete set for logs and command-line callers.
 */
export declare class InitialFieldsInvalidError extends WorkflowError<"initial-fields-invalid"> {
  readonly definition?: string;
  readonly issues: InitialFieldIssue[];
  constructor(args: { definition?: string; issues: InitialFieldIssue[] });
}

/**
 * Initial value for an `input`-sourced entry — what a caller supplies at
 * `startInstance` (or `setStage`). Same discriminator shape as
 * ResolvedFieldEntry minus `_key` and with null values disallowed
 * (omission signals "no initial value").
 */
export declare type InitialFieldValue = {
  [K in FieldKind]: {
    type: K;
    name: string;
    value: NonNullable<FieldValueMap[K]>;
  };
}[FieldKind];

export { InsightPhrase };

/** Where a condition lives in the current stage — the address a consumer
 *  joins back onto the matching evaluation node. */
export declare type InsightSite =
  | {
      kind: "transition";
      transition: string;
    }
  | {
      kind: "activity-filter";
      activity: string;
    }
  | {
      kind: "requirement";
      activity: string;
      requirement: string;
    }
  | {
      kind: "action";
      activity: string;
      action: string;
    }
  | {
      kind: "action-when";
      activity: string;
      action: string;
    }
  | {
      kind: "editable-field";
      scope: FieldScope;
      name: string;
      activity?: string;
    };

/** Viewer-scoped assignment counts across active activities in the open stage. */
export declare function instanceAssignmentStateCounts(
  instance: AssignmentInstance,
  identity: AssignmentIdentity,
): AssignmentStateCounts;

/**
 * The tag's instance partition as a listen filter — the one shared change
 * feed a preview store keeps itself fresh from (an event names the touched
 * instance; the store refetches that preview alone). Deliberately unfiltered
 * beyond the tag: one upstream listener serves every view, whatever each is
 * filtered to.
 */
export declare function instanceChangesQuery(args: {
  tag: string;
}): CompiledQuery;

/**
 * Mint the Sanity document `_id` for a workflow instance — a fresh
 * random suffix, so every instance (root or spawned child) gets a
 * unique doc id under its tag. Lives in the shell, not `core/`, because it
 * draws randomness; the deterministic `definitionDocId` is the pure-core
 * counterpart. Bare form — Sanity rejects `:` in document IDs, so this is
 * never a GDR URI.
 */
export declare function instanceDocId(tag: string): string;

/**
 * The per-instance guard filter — "this instance's guards in one datasource".
 * The engine's verdict load ({@link verdictGuardsForInstance}) fetches it once
 * against the engine datasource, and {@link guardsForInstance} unions it
 * across datasources for housekeeping; the reactive adapters subscribe the
 * set-shaped {@link instancesGuardQuery} this delegates to (one shared
 * live query per resource, sliced per `sourceInstanceId`), so every path
 * reads through one filter definition. Ordinary stage retraction deletes
 * guards, so results represent active persisted guard documents.
 */
export declare function instanceGuardQuery(instanceId: string): CompiledQuery;

export declare interface InstanceGuardsQueryArgs {
  client: WorkflowClient;
  clientForGdr: ClientForGdr;
  instance: WorkflowInstance;
}

/**
 * The instance id does not resolve to a workflow instance this engine can
 * see — the document is missing, or it belongs to another engine's tag
 * partition. Both arms share this class and kind (an invisible instance is
 * not-found to this caller); the message says which arm it was.
 */
export declare class InstanceNotFoundError extends WorkflowError<"instance-not-found"> {
  readonly instanceId: string;
  constructor(args: { instanceId: string; detail?: string });
}

/**
 * The preview projection over the same instances {@link instancesQuery}
 * matches — a `WorkflowInstancePreview` each, kilobytes lighter than the full
 * document (no snapshot, no audit trails), for surfaces that render many runs
 * at once. Parse results through `readInstancePreviewDoc`.
 */
export declare function instancePreviewsQuery(args: {
  tag: string;
  filter?: InstancesQueryFilter;
}): CompiledQuery;

/** Args for the verbs that address an instance without further input. */
export declare interface InstanceRefArgs {
  instanceId: string;
}

/**
 * The two join keys every instance-scoped event carries — one home for the
 * fields, their docs, and the policy, so a new event can't forget half the
 * pair or drift its wording.
 */
declare interface InstanceScopedEventData {
  /** Absent only when the definition predates content fingerprinting. */
  definitionContentHash?: string;
  /** The instance document `_id` — the per-instance join key (engine-minted
   *  `<tag>.wf-instance.<random>`; caller-supplied ids ride verbatim). */
  instanceId: string;
}

export declare interface InstanceSession {
  /** The watch-set to feed via {@link InstanceSession.update}, derived from the
   *  held instance. Recompute after the instance changes (a new stage changes it). */
  readonly subscriptionDocuments: WatchSet;
  /** Replace the held content with the current values the consumer observed
   *  (last-write-wins, scoped). A self-doc updates the held instance only when
   *  its `_updatedAt` is strictly newer — an older or timestamp-equal echo is
   *  ignored. Buffered if a commit is in flight; a BUFFERED push that fails
   *  validation surfaces on the NEXT `update` call (after that call's own
   *  docs are processed), never from the commit itself — the commit's
   *  outcome is never masked by a store echo's failure. */
  update(docs: LoadedDoc[]): void;
  /** Replace one held document without rebuilding the rest of the overlay.
   *  Consumers with per-document streams use this after the initial
   *  {@link InstanceSession.update} snapshot. Self-doc recency, commit-time
   *  buffering, and deferred buffered-validation errors follow the same
   *  contract as {@link InstanceSession.update}. */
  updateDocument(doc: LoadedDoc): void;
  /** Replace the held live guards (the consumer's guard stream,
   *  last-write-wins). Guards are a separate stream from the watch-set:
   *  {@link InstanceSession.evaluate} pre-flights the instance write against
   *  them so action verdicts surface `mutation-guard-denied` while a matching
   *  guard denies. Unlike {@link InstanceSession.update}, this is NOT buffered
   *  behind an in-flight commit — guards aren't part of the held-snapshot
   *  consistency story, and tick's pre-flight reads them at commit start. */
  updateGuards(guards: readonly MutationGuardDoc[]): void;
  /** Best-effort projection against the held content + held guards. The first
   *  call resolves the caller's identity/grants from the client's token over
   *  the network (cached per client) — plus each foreign subject resource's
   *  grants through its own client, for the subject-write forecast. The held
   *  snapshot is not refetched. Missing references receive completed availability
   *  metadata checks; a guard predicate using `->` reads its target
   *  through the bound engine client. */
  evaluate(): Promise<WorkflowEvaluation>;
  /** Advance the instance against the held content: cascade auto-transitions,
   *  deploy guards, queue effects, commit with `ifRevisionId`. */
  tick(): Promise<OperationResult>;
  /** Fire an action against an activity, gated on the held content, then cascade. */
  fireAction(args: {
    activity: string;
    action: string;
    params?: Record<string, unknown>;
  }): Promise<OperationResult>;
  /** Edit a declared-editable field against the held content (the generic edit
   *  seam), gated on the held projection, then cascade. Stages its own
   *  optimistic preview on entry and drops the target's previews when the
   *  commit settles — success lands the reloaded value, failure reverts the
   *  projection to the held committed state. */
  editField(args: {
    target: EditFieldTarget;
    mode?: EditMode;
    value?: unknown;
  }): Promise<OperationResult>;
  /** Stage an optimistic preview of a field edit: {@link InstanceSession.evaluate}
   *  projects against the held instance with staged previews applied, so field
   *  values and the advisory verdicts derived from them move instantly, while
   *  everything the engine writes (stage, activity statuses, history) stays
   *  committed by construction — previews apply `field.*` ops only. Set/unset
   *  replace the target's staged rows (last write wins); appends accumulate.
   *  Tolerant where commits are loud: a target that doesn't resolve in the
   *  current stage (it moved under a mounted editor), a closed edit window
   *  (a skipped activity's field), a value that doesn't fit the field's
   *  shape yet (a half-typed date), or a ref outside the declared resource
   *  surface stages an INERT preview — no echo, no throw; the commit at the
   *  semantic boundary is the loud surface. Never persisted — commit via
   *  {@link InstanceSession.editField}. */
  previewField(args: {
    target: EditFieldTarget;
    mode?: EditMode;
    value?: unknown;
  }): void;
  /** Drop staged previews for one target — or all, when omitted — reverting
   *  the projection to the held committed state on the next evaluate. */
  discardFieldPreview(target?: EditFieldTarget): void;
}

export declare interface InstancesForDocumentArgs {
  /** A resource-qualified GDR URI; a bare id is rejected. */
  document: GdrUri;
}

/**
 * The guard filter for a SET of instances in one datasource — the single
 * definition every per-instance read delegates to ({@link instanceGuardQuery}).
 * Reactive adapters subscribe it as ONE shared live query per resource for
 * every co-mounted session, fanning results back out per `sourceInstanceId`,
 * so a document's guard subscription count doesn't grow with its instance
 * count. Deterministically ordered, matching {@link guardsForResource}.
 */
export declare function instancesGuardQuery(
  instanceIds: readonly string[],
): CompiledQuery;

/**
 * The instance-list GROQ for a {@link InstancesQueryFilter}, ordered by
 * `startedAt` ascending (descending + sliced under
 * {@link InstancesQueryFilter.limit}). Adapters subscribe to it;
 * {@link workflow.query}-style one-shot reads fetch it — both see the same
 * rows.
 */
export declare function instancesQuery(args: {
  tag: string;
  filter?: InstancesQueryFilter;
}): CompiledQuery;

/**
 * Narrows an instance-list read. All conditions AND together; an empty
 * filter means "every in-flight instance in the engine's resource".
 */
export declare interface InstancesQueryFilter {
  /**
   * Only instances that may reference this document (resource-qualified GDR
   * URI). The lake-side predicate matches the reactive watch-set's
   * workflow, open-stage, activity, ancestor, live-child, and own-id references.
   */
  document?: GdrUri;
  /**
   * The multi-document form of {@link InstancesQueryFilter.document}: one
   * predicate matching instances that reference any of the given docs,
   * for consumers discovering instances across many open documents at once.
   * Merged with `document` when both are set. Callers may defensively recheck
   * with {@link instanceWatchesDocument}. A defined but empty
   * array matches nothing (the GROQ-natural reading of membership in an
   * empty set) — omit the field for the unconstrained every-in-flight read.
   */
  documents?: readonly GdrUri[];
  /**
   * Specific instances by bare doc id — OR'd with the document prefilter, so
   * a consumer tracking freshly-started instances (not yet referencing any
   * registered doc) sees them in the same live read. Bare ids only: an
   * instance's `_id` is never a GDR URI, so a URI here is a caller bug and
   * is rejected. A defined but empty array matches nothing, exactly like
   * {@link InstancesQueryFilter.documents}.
   */
  ids?: readonly string[];
  /** Version-less definition `name` the instances were started from. */
  definition?: string;
  /** Current stage name. */
  stage?: string;
  /** Current viewer assignment filter. `unrouted` needs no identity match;
   *  `routed` matches literal role members only while no user holds the
   *  activity; `held` matches the direct user and shadows every role. */
  assignment?: {
    userId: string;
    roles?: readonly string[] | undefined;
    states?: readonly AssignmentState[] | undefined;
  };
  /** Include completed/aborted instances (default: in-flight only). */
  includeCompleted?: boolean;
  /**
   * Cap the read to the newest `limit` instances — the query flips to
   * `startedAt desc` and slices, so a bounded consumer (a dashboard over an
   * unbounded dataset) reads the most recent rows instead of the oldest.
   * Unlimited reads keep the ascending order adapters index by. Must be a
   * positive integer.
   */
  limit?: number;
  /**
   * Keyset cursor into the newest-first order: only instances strictly older
   * than this position. Pass the last row of the previous page, and the next
   * `limit` rows continue where it ended. A cursor rather than an offset, so
   * rows starting or concluding between pages can't shift what a page holds.
   * Requires `limit`: pages only exist in the newest-first sliced read.
   */
  before?: {
    /** The `_id` tiebreak for rows sharing `startedAt`. */
    id: string;
    startedAt: string;
  };
}

/**
 * Whether {@link document} is in {@link instance}'s reactive watch-set — the
 * reverse of {@link subscriptionDocumentsForInstance}. Both derive from
 * the shared watch-ref collector, the single source of truth, so "which docs does
 * this instance watch" and "which instances watch this doc" stay in lockstep
 * — the same way `hydrateSnapshot`'s load-set does. Matching is on the
 * resource-qualified GDR URI, so a cross-dataset subject (`dataset:A:ds:doc`)
 * never matches a same-id doc in another resource (`dataset:B:ds:doc`).
 *
 * A non-reactive, content-change-driven runtime uses this to decide whether a
 * changed document should re-`tick` an instance it does not hold in memory.
 */
export declare function instanceWatchesDocument(
  instance: WorkflowInstance,
  document: GdrUri,
): boolean;

/**
 * @internal Whether a dot-joined attribute path can be spliced into GROQ with
 * no base, as `a.b` rather than `$var.a.b`, and read the same attributes. Every
 * segment must match the attribute grammar, and the leading one must not be a
 * name GROQ reads as its own literal in that position. Exported for workspace
 * packages that splice such paths into GROQ they compose; not a supported
 * consumer API.
 */
export declare function _isBareAttributePath(path: string): boolean;

/** The canonical cascade-fired test: structural on `when`, so both authored
 *  and stored shapes qualify. */
export declare function isCascadeFired(action: {
  when?: string | undefined;
}): boolean;

/**
 * A claim whose lease has lapsed no longer protects the entry. A claim
 * without `leaseExpiresAt` (persisted before leases existed) counts as
 * expired — those are exactly the stuck-forever entries leases recover.
 */
export declare function isClaimExpired(
  claim: PendingEffectClaim,
  now: string,
): boolean;

export declare function isClientProjectUser(
  value: unknown,
): value is ClientProjectUser;

export { isComparisonOp };

/**
 * The full applicability derivation for one definition against one loaded
 * document: startable ∧ {@link acceptsDocumentType} ∧ `start.filter`.
 * "Deployed" is the caller's premise — feed it deployed definitions (the
 * engine verb `definitionsForDocument` does). Throws when `document` carries
 * no `_type` — that's a ref or a projection, not a loaded document. A
 * `start.filter` that doesn't PARSE also throws, naming the definition —
 * that's a malformed definition (only writable by bypassing deploy
 * validation), and silently excluding it would make it vanish from every
 * picker with nothing screaming; only an evaluation result of GROQ null
 * ("can't decide") fails closed.
 */
export declare function isDefinitionApplicable(args: {
  definition: ApplicabilitySource;
  document: CandidateDocument;
  /** Caller-side filter bindings — omit for the bare candidate-doc context. */
  scope?: StartScope;
}): Promise<boolean>;

/**
 * Whether no live claim protects the entry, so a drain may claim it: it carries
 * no claim at all, or one {@link isClaimExpired} calls lapsed.
 */
export declare function isEntryUnheld(
  entry: Pick<PendingEffect, "claim">,
  now: string,
): boolean;

/**
 * Whether an entry was scoped OUT at stage entry — the `filter` existence
 * gate skipped it before it ever started. Distinct from an action-resolved
 * `skipped` (real, started work whose entry carries `startedAt`): under
 * filter-existence semantics render surfaces hide the former and keep the
 * latter. The ONE spelling of that split.
 */
export declare function isFilterScopedOut(entry: {
  status: ActivityStatus;
  startedAt?: string | undefined;
}): boolean;

/** Type filter for GDR shape. */
export declare function isGdr(value: unknown): value is GlobalDocumentReference;

/**
 * Whether an entry is caller-filled at start/spawn — the only source that
 * reads `initialFields`. Every other source (query/literal/fieldRead, or
 * working memory) resolves itself at materialisation, so a `$fields.<name>`
 * read of it can never bind on any read surface that evaluates a
 * `start.filter`. The deploy read-check keys on this.
 */
export declare function isInputSourced(
  entry: Pick<FieldEntry, "initialValue">,
): boolean;

/**
 * A notes-shaped `array` entry: the sugar's fixed `of` declares
 * `{body, actor, at}` rows ({@link NoteItem}), which tells the audit log
 * apart from other array kinds (e.g. the `todoList` sugar's
 * `{label, status}`). Accepts both vocabularies — a deployed definition
 * entry (`type`) and a resolved instance entry (`_type`) — so start-time
 * and runtime surfaces share one verdict. Resolved-entry overload last, as
 * on {@link isTodoListEntry}.
 */
export declare function isNotesEntry(entry: FieldEntry): entry is FieldEntry & {
  type: "array";
};

export declare function isNotesEntry(
  entry: ResolvedFieldEntry,
): entry is Extract<
  ResolvedFieldEntry,
  {
    _type: "array";
  }
>;

/** Whether a project-user API failure explicitly means the user is absent. */
export declare function isProjectUserNotFoundError(error: unknown): boolean;

/**
 * True when a write looks like a lost optimistic lock — every `statusCode: 409`
 * from the real client, or the bench's `ifRevisionId check failed` message.
 * A bare 409 is not exclusively a lost fence: a `create` against an existing id
 * (`documentAlreadyExistsError`) carries the same status. Narrow the error to
 * one rev-guarded write before asking — anything wider (a whole cascade, or a
 * commit together with its guard deploy) reads a create collision as a lost
 * race.
 */
export declare function isRevisionConflict(error: unknown): boolean;

/** Entry-level {@link isSingleDocRefKind}: narrows a resolved entry to the
 *  single-GDR arms (`doc.ref` / `subject`) — the value is one GDR (or null)
 *  and the entry may carry the accepted-target `types`. */
export declare function isSingleDocRefEntry(
  entry: ResolvedFieldEntry,
): entry is Extract<
  ResolvedFieldEntry,
  {
    _type: "doc.ref" | "subject";
  }
>;

/**
 * Kinds whose value is a single content-document GDR — `doc.ref` and its
 * elevated alias `subject`. The one predicate behind every "this entry is one
 * document reference" branch (deref reads, query/spawn ref coercion, input
 * shape checks, watch-set collection), so the alias can't drift out of a
 * site.
 */
export declare function isSingleDocRefKind(
  kind: string,
): kind is "doc.ref" | "subject";

/**
 * Whether a human may start this definition standalone (the default). A
 * `lifecycle: 'child'` definition is spawn-only — instantiated by a parent via
 * an action's `spawn`, so consumers exclude it from top-level start pickers.
 * Advisory: the engine does not enforce it (see the `required`-field backstop
 * for load-bearing input fields). Accepts any definition-shaped value (authored,
 * stored, deployed, or a projected list row).
 */
export declare function isStartableDefinition(definition: {
  lifecycle?: WorkflowLifecycle | undefined;
}): boolean;

/**
 * The SUBJECT-ENTRY RULE: the `subject`-kind entry is what makes a definition
 * "about" a subject document — the kind is the discriminator, never a
 * heuristic over required refs. One predicate shared by applicability's type
 * matching (`acceptsDocumentType`), the autonomous-start deploy invariant,
 * and the root-read deploy check (a root-reading `start.filter` needs a
 * subject entry to bind a candidate root) — so "counts as a subject" can't
 * drift between them.
 */
export declare function isSubjectEntry(
  entry: Pick<FieldEntry, "type">,
): boolean;

/**
 * Whether `documentType` is a system document: one in Sanity's reserved
 * `sanity.` or `system.` namespaces, or one the engine owns and writes for
 * itself. A subject entry that declares no `types` never matches one. Naming
 * a reserved type such as `sanity.imageAsset` or `system.release` in `types`
 * explicitly still matches; an engine-owned type does not, even when named,
 * at every applicability read.
 */
export declare function isSystemDocumentType(documentType: string): boolean;

/**
 * The environment denial process shells (CLI, MCP server) feed
 * {@link createTelemetryIntake}: CI and `DO_NOT_TRACK` are trueish
 * opt-outs — the standard Sanity CLI consent recipe.
 */
export declare function isTelemetryEnvDenied(
  env: Record<string, string | undefined>,
): boolean;

export declare function isTerminalActivityStatus(
  status: ActivityStatus,
): status is TerminalActivityStatus;

/**
 * A stage with no transitions out IS terminal — structural, not declared.
 * Reaching one completes the instance.
 */
export declare function isTerminalStage(stage: Stage): boolean;

/**
 * A todoList-shaped `array` entry: the sugar's fixed `of` declares `label` +
 * `status` rows, which tells a todo list apart from other array kinds (e.g.
 * the `notes` sugar's `{body, actor, at}`). Accepts both vocabularies —
 * a deployed definition entry (`type`) and a resolved instance entry
 * (`_type`) — so start-time and runtime surfaces share one verdict. The
 * resolved-entry overload comes last: contextual typing reads an overloaded
 * argument's FINAL signature, which `.filter(isTodoListEntry)` needs.
 */
export declare function isTodoListEntry(
  entry: FieldEntry,
): entry is FieldEntry & {
  type: "array";
};

export declare function isTodoListEntry(
  entry: ResolvedFieldEntry,
): entry is Extract<
  ResolvedFieldEntry,
  {
    _type: "array";
  }
>;

/** Per-row narrowing for {@link TodoListItem}: `_key` + `label` must be
 *  strings; `status`, when present, must be a string — a non-string status is
 *  rejected, while null counts as unset (GROQ materializes absent attributes
 *  as null). The remaining columns stay loose (field validation owns them). */
export declare function isTodoListItem(row: unknown): row is TodoListItem;

/**
 * True when the instance document exists but its start never finished: the
 * `create` committed, yet priming (stage entry, activities, guard deploy)
 * did not. The shape is legal and resumable — `startInstance` with the same
 * `instanceId` completes the outstanding commits. Readers should present it
 * as an incomplete start, never as a normal run sitting at its initial
 * stage. Terminal instances are excluded: an aborted never-primed instance
 * reads as aborted, not as still-resumable.
 */
export declare function isUnprimed(
  instance: Pick<WorkflowInstance, "stages" | "completedAt" | "abortedAt">,
): boolean;

/** Deterministic id (from the guard's authored `name`) so deploy/retract are query-free and idempotent; a positional index would silently shift if guards are reordered. */
export declare function lakeGuardId(args: {
  instanceDocId: string;
  guardName: string;
}): string;

/** The write operations Content Lake exposes to mutation guards. */
export declare type LakeMutationGuardAction = "create" | "update" | "delete";

/**
 * The one rule every lake-facing identity check (guard previews/pre-flights, `$can` grant filters)
 * must resolve through to agree with the lake's own `identity()`; binding `actor.id` directly at a
 * lake edge reintroduces the divergent-identity mismatch.
 */
export declare function lakePrincipalId(args: {
  actor: {
    id: string;
  };
  localPrincipalId?: string | undefined;
}): string;

/**
 * GROQ listing only the latest deployed version of each definition name.
 * The correlated inner query keeps the reduction in the lake, so discovery
 * reads do not transfer every historical definition body.
 *
 * Params: `$tag`.
 */
export declare function latestDefinitionsGroq(): string;

/**
 * The latest deployed version of each definition name from any supplied row
 * set. Useful at boundaries that may already hold multiple versions; callers
 * starting from the lake can use {@link latestDefinitionsGroq}. The highest
 * version wins regardless of input order, while names keep first-appearance
 * order.
 */
export declare function latestDeployedDefinitions<
  T extends {
    name: string;
    version: number;
  },
>(rows: readonly T[]): T[];

/**
 * Advisory producer/consumer check for a deployed definition: every
 * `$effects['<name>'].<key>` read whose `<name>` is not a declared effect,
 * or is one whose declared `outputs` do not list `<key>`. Returns
 * human-readable warning strings (empty when clean) — deploy surfaces them,
 * it never rejects. (Runtime completion is where declared `outputs` are
 * ENFORCED; this only warns the author at deploy about a consumer read no
 * producer declares.)
 *
 * `$effects` derives solely from completed effects' outputs — the start
 * seed and spawn handoff live in `$context` — so every producer IS a
 * declared effect and an unknown name is warnable, not tolerated. An
 * effect that declares no `outputs` produces nothing (an empty allowlist),
 * so a keyed read of it is flagged like any undeclared key.
 *
 * Reads are collected from the primary consumer sites: condition GROQ
 * ({@link conditionSitesOf}), effect binding GROQ, and guard reads (the
 * `$effects['<name>'].<path>` mini-language on `match.idRefs` / `metadata`).
 */
export declare function lintEffectOutputs(
  definition: WorkflowDefinition,
): string[];

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

export declare interface LoadedDoc {
  doc: SanityDocument;
  resource: WorkflowResource;
}

export declare type LoggerFactory = (name: string) => EngineLogger;

/** A by-name reference to another workflow definition (an
 *  `action.spawn.definition`). No `version` (or `'latest'`) means "the
 *  highest deployed version at spawn time"; a numeric version pins one
 *  deployed version permanently. */
export declare interface LogicalRef {
  name: string;
  version?: number | "latest";
}

/**
 * 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.
 */
export declare type ManualTarget =
  | {
      type: "url";
      url: string;
    }
  | {
      type: "field";
      field: StoredFieldRef;
    };

/** Returns true iff `document` survives `filter`'s GROQ predicate under the supplied identity. */
declare function matchesFilter(args: {
  document: {
    _id?: string;
    _type?: string;
    [key: string]: unknown;
  };
  filter: string;
  userId?: string;
}): Promise<boolean>;

export { MAX_COUNTERFACTUAL_INDEX };

/**
 * The engine always writes both stamps together, so a bare `modelVersion` with no
 * `minReaderModel` is malformed foreign data; that case reads the version itself as the
 * floor (conservative fallback).
 */
export declare function minReaderModelOf(doc: object): number;

/**
 * A selected document absent from the evaluated snapshot. Absence alone does
 * not prove deletion. When present, `availability` carries the completed check.
 * This evidence is derived for the evaluation and is never persisted.
 */
export declare interface MissingDocument {
  target: EditFieldTarget;
  reference: GlobalDocumentReference;
  /** The declared field title, when available. */
  title?: string;
  /** Completed availability evidence. Failed or unsupported checks yield `unreadable`.
   * Omitted when the caller supplied only a content snapshot. */
  availability?: DocumentAvailability;
}

/**
 * Shared formatter for Workflows integrations; not a supported consumer API.
 * @internal
 */
export declare function _missingDocumentsSummary(
  documents: readonly MissingDocument[],
): string;

export declare interface MissingHandlerDeployInfo {
  phase: "deploy";
  name: string;
  locations: string[];
  definitionId: string;
}

export declare interface MissingHandlerDrainInfo {
  phase: "drain";
  name: string;
  effectKey: string;
  instanceId: string;
}

/**
 * The `effects.missingHandler: 'fail'` policy tripped: an effect names a handler the
 * runtime never registered. `info` carries the phase-specific location
 * (deploy verification vs a drain attempt) so the runtime that opted into
 * failing can report exactly which handler is missing where.
 */
export declare class MissingHandlerError extends WorkflowError<"missing-effect-handler"> {
  readonly info: MissingHandlerInfo;
  constructor(args: { info: MissingHandlerInfo });
}

export declare type MissingHandlerInfo =
  | MissingHandlerDeployInfo
  | MissingHandlerDrainInfo;

export declare type MissingHandlerPolicy =
  | "fail"
  | "skip"
  | ((info: MissingHandlerInfo) => void | Promise<void>);

/**
 * The `required` input entries `initialFields` fails to provide — the pure
 * predicate behind {@link RequiredFieldNotProvidedError}: an entry counts as
 * required when it is `required` AND `input`-sourced (the only combination
 * deploy admits), and as provided when a supplied value matches its name AND
 * kind with a real (non-null) value. Keys on the same name+type as the input
 * read during input resolution, but is stricter: a present-but-null/
 * undefined value counts as absent here (a required field needs a real
 * value), whereas input resolution passes a null fill straight
 * through. Exported so pre-flight validators (e.g. mapping validation) share
 * the engine's own rule instead of mirroring it.
 */
export declare function missingRequiredInputs(args: {
  entryDefs: readonly FieldEntry[];
  initialFields: readonly InitialFieldValue[];
}): {
  name: string;
  type: FieldEntry["type"];
}[];

/**
 * Thrown when a document's reader floor exceeds {@link DATA_MODEL_VERSION} — reading it
 * could silently misinterpret a newer model's reshape, so the read fails hard instead.
 * Fix: upgrade `@sanity/workflow-engine`.
 */
export declare class ModelVersionAheadError extends WorkflowError<"model-version-ahead"> {
  readonly documentId: string;
  readonly documentModelVersion: number;
  readonly requiredReaderModel: number;
  readonly engineModelVersion: number;
  constructor(args: {
    documentId: string;
    documentModelVersion: number;
    requiredReaderModel: number;
  });
}

/** A document with no stamp, or a non-number stamp (foreign data this engine never wrote), reads as model 0. */
export declare function modelVersionOf(doc: object): number;

/**
 * Inputs to predicate evaluation: the delta-mode natives `before()`/`after()`,
 * the `mutation`, the `guard`, and `identity()`. `before` is null on create,
 * `after` null on delete.
 */
export declare interface MutationContext {
  before:
    | ({
        _id: string;
        _type: string;
      } & Record<string, unknown>)
    | null;
  after:
    | ({
        _id: string;
        _type: string;
      } & Record<string, unknown>)
    | null;
  action: LakeMutationGuardAction;
  /**
   * The caller's principal id in the guarded resource's own namespace
   * (what that lake's `identity()` returns), resolved as `identity()` in
   * the predicate. Advisory — the engine takes the caller's word for who
   * is acting; only the lake's own token identity is authenticated.
   */
  identity?: string;
}

/** Lake operations plus the authored lifecycle actions the compiler translates. */
export declare type MutationGuardAction =
  | LakeMutationGuardAction
  | "publish"
  | "unpublish";

/**
 * The persisted body of a mutation guard — every field except the lake system
 * fields. Shared by {@link MutationGuardDoc} (the stored doc) and the engine's
 * compile inputs, so the field set lives in one place.
 */
export declare interface MutationGuardBody {
  /** The single datasource this guard belongs to — the engine spans
   *  datasources and must record which one, since the lake is per-datasource and infers the resource from storage. */
  resourceType: string;
  resourceId: string;
  /**
   * Provenance stamp — who registered the guard (the engine writes its own
   * marker here). Unenforced: nothing reads `owner`, and there is no
   * owner/admin modification rule — guard deploy/refresh/retract ride the
   * caller's token like every other engine write. A lake-enforced guard can
   * therefore lock the engine's own housekeeping out (self-lockout) until a
   * dedicated engine execution identity exists.
   */
  owner: string;
  /**
   * Provenance — the workflow that registered this guard. The lake's own guard
   * model carries none of these; they exist so the engine can find its guards
   * for coherency refresh and housekeeping without parsing them out of `_id`.
   */
  sourceInstanceId: string;
  sourceDefinition: string;
  sourceStage: string;
  name?: string;
  description?: string;
  /** Bare document ids (resource-local; both published and `drafts.` forms). */
  match: MutationGuardMatch;
  /**
   * Lake delta-mode GROQ. The root exposes `document.before`,
   * `document.after`, `mutation`, and `guard`; `identity()` and resource-local
   * reference dereferencing are available. Empty string is unconditional deny.
   */
  predicate: string;
  /** Caller-owned projected state the predicate reads as `guard.metadata.*`. */
  metadata: Record<string, unknown>;
}

/** The `mutation-guard-denied` verdict arm, shared verbatim by
 *  {@link DisabledReason} and {@link EditDisabledReason}. */
export declare type MutationGuardDenial = Extract<
  DisabledReason,
  {
    kind: "mutation-guard-denied";
  }
>;

/**
 * Thrown when one or more guards deny a mutation — raised by the engine's
 * optimistic pre-flight and the bench's write seam; carries every denial.
 * Fail-closed: a predicate that errors or is non-true denies.
 *
 * The ONE guard-denial error: every verb whose write a guard denies —
 * `fireAction`, `editField`, `tick`, a session tick, a bench write — throws
 * this class, never a verb-specific wrapper.
 */
export declare class MutationGuardDeniedError extends WorkflowError<"mutation-guard-denied"> {
  readonly denied: DeniedGuardRef[];
  readonly documentId: string;
  readonly action: MutationGuardAction;
  constructor(args: {
    documentId: string;
    action: MutationGuardAction;
    denied: DeniedGuardRef[];
  });
  /**
   * Build the error straight from the denying guard docs, shared by every
   * enforcement site (engine pre-flight, bench write seam).
   */
  static fromGuards(args: {
    documentId: string;
    action: LakeMutationGuardAction;
    guards: readonly MutationGuardDoc[];
  }): MutationGuardDeniedError;
}

export declare interface MutationGuardDoc extends MutationGuardBody {
  _id: string;
  _type: typeof GUARD_DOC_TYPE;
  /**
   * Deliberately NO engine data-model stamp (`modelVersion`/`minReaderModel`)
   * — this doc format is the lake's forthcoming contract, and the engine
   * must not grow fields on a shape it doesn't own. Assigned by the lake on
   * write — never sent on create (an empty-string value fails datetime
   * validation).
   */
  _rev?: string;
  _createdAt?: string;
  _updatedAt?: string;
}

export declare const MutationGuardDocSchema: v.GenericSchema<MutationGuardDoc>;

export declare interface MutationGuardMatch {
  types?: string[];
  /** Bare document ids (resource-local; both published and `drafts.` forms). */
  idRefs?: string[];
  idPatterns?: string[];
  actions: MutationGuardAction[];
}

/** Every wait narrated, de-duplicated by phrase: same-named actions on
 *  sibling activities are distinct waits that tell one story — consumers
 *  want one line per story, not one per site. */
export declare function narrateAutonomyWaits(
  waits: readonly AutonomyWait[],
  ctx: DescribeContext,
): string[];

export { NEUTRAL_MARK };

/** The default logger: emit nothing. The engine's twin of `@sanity/telemetry`'s `noopLogger`. */
export declare const noopTelemetry: WorkflowTelemetryLogger;

/**
 * One row of a `notes`-sugar `array` entry, as the desugared `of` persists
 * it: `_key` + the domain `body`, with the `actor`/`at` audit stamps. Like
 * {@link TodoListItem}, the sugar guarantees the COLUMNS in the schema, not
 * values per row — `actor`/`at` are per-row optional (an appender that
 * doesn't know the author writes a stamp-less row, and rows are lake data
 * any client can write).
 */
export declare interface NoteItem {
  _key: string;
  body: string;
  actor?: Actor | null;
  at?: string | null;
}

/** @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.
 */
export declare type Op =
  | FieldOp
  | {
      type: "status.set";
      activity: string;
      status: ActivityStatus;
    };

/**
 * Op `type` discriminators — the stored mutation primitives.
 */
export declare const OP_DISPLAY: {
  "field.set": {
    title: string;
    description: string;
  };
  "field.setIfMissing": {
    title: string;
    description: string;
  };
  "field.unset": {
    title: string;
    description: string;
  };
  "field.append": {
    title: string;
    description: string;
  };
  "field.inc": {
    title: string;
    description: string;
  };
  "field.dec": {
    title: string;
    description: string;
  };
  "field.updateWhere": {
    title: string;
    description: string;
  };
  "field.removeWhere": {
    title: string;
    description: string;
  };
  "status.set": {
    title: string;
    description: string;
  };
};

export declare interface OpAppliedSummary {
  opType: string;
  target?: {
    scope: FieldScope;
    field: string;
  };
  resolved?: Record<string, unknown>;
}

/** Assignment members for each active activity in the instance's open stage. */
export declare function openActivityAssignments(
  instance: AssignmentInstance,
): readonly (readonly Assignee[])[];

export declare interface OperationArgs {
  instanceId: string;
  /**
   * URL path for grant resolution — see `StartInstanceArgs.grantsFromPath`.
   */
  grantsFromPath?: string;
}

/**
 * What a state-changing verb reports back. Every mutating verb —
 * `startInstance`, `fireAction`, `editField`, `completeEffect`,
 * `commitEffectOps`, `tick`, `setStage`, `abortInstance`, `resetActivity` —
 * returns this one shape, on the namespace, the `Engine`, and the reactive
 * session alike.
 */
export declare interface OperationResult {
  /** The instance after the operation + all cascading auto-transitions. */
  instance: WorkflowInstance;
  /** Number of auto-transitions that fired during the cascade. */
  cascaded: number;
  /**
   * Whether this call changed the instance's workflow state. `false` means
   * the call succeeded but was a no-op: an idempotent re-fire of an already
   * resolved activity, a `tick` that wrote nothing, a `setStage` already at
   * the target, an abort of an already-terminal instance, or a retry whose
   * `idempotencyKey` was already processed. Failures throw —
   * `changed: false` never signals an error.
   */
  changed: boolean;
  /** Engine primitives (`workflow.op.field.*` / `status.set`) that ran
   *  during the action commit. Surfaced for caller-side assertions and
   *  audit. */
  ranOps?: OpAppliedSummary[];
  /**
   * The earliest future ISO 8601 instant the engine can derive for a time-based
   * change to the instance's evaluation. Schedule the next {@link Engine.tick | tick} for it.
   * Excludes gates reading `$now` beside a caller variable;
   * {@link WorkflowEvaluation.nextEvaluationAt} carries those boundaries.
   * Derived per call, never persisted.
   *
   * Absent on a terminal instance or when the engine cannot derive a boundary.
   * Conditions using date arithmetic may yield no boundary. Time can still
   * affect a nonterminal instance when this value is absent.
   */
  nextEvaluationAt?: string;
}

export { OUTCOME_MARKS };

/**
 * The instance's direct parent — the last entry of the root-first
 * {@link WorkflowInstance.ancestors} chain; `undefined` for a root instance.
 */
export declare function parentRef(
  instance: Pick<WorkflowInstance, "ancestors">,
): GlobalDocumentReference | undefined;

/**
 * Parse one incoming definition at the deploy/diff boundary (`caller` prefixes
 * the error). Accepts authored content or a fetched definition document — the
 * document envelope and the authoring-only `runtime` block are stripped (the
 * inverse of the deploy serialisation, so a fetched document round-trips to
 * `unchanged` instead of fingerprinting its envelope as content, and a hosting
 * kind never changes a definition's version), then the remainder strict-parses
 * against the stored schema: any unknown key anywhere in the tree fails loud.
 */
export declare function parseDefinitionInput(
  def: Record<string, unknown>,
  caller: string,
): WorkflowDefinition;

/** Parse the frozen definition from a complete persisted instance. */
export declare function parseDefinitionSnapshot(
  instance: WorkflowInstance,
): WorkflowDefinition;

/**
 * The canonical parser for an instance's frozen
 * {@link WorkflowInstance.definitionSnapshot}. Accepting the persisted pair
 * keeps compatibility scanners and full instance consumers on the same
 * contextual failure path.
 */
export declare function parseDefinitionSnapshotValue(
  instance: Pick<WorkflowInstance, "_id" | "definitionSnapshot">,
): WorkflowDefinition;

/**
 * Parse definitions at the deploy boundary and derive the reader model their
 * parsed shape requires, the one sequence `workflow.deployDefinitions` applies
 * before it checks an acknowledgement. `caller` prefixes any parse error, and a
 * definition the parser rejects throws instead of yielding a floor.
 *
 * Anything that checks an acknowledgement against definitions must derive the
 * floor through this. Unsupported outside the Workflows packages.
 * @internal
 */
export declare function _parseDefinitionsWithReaderModel(
  definitions: readonly Record<string, unknown>[],
  caller: string,
): {
  definitions: WorkflowDefinition[];
  requiredMinReaderModel: number;
};

export declare interface ParsedGdr {
  scheme: GdrScheme;
  /** For `dataset`: `<projectId>` */
  projectId?: string;
  /** For `dataset`: `<dataset>` */
  dataset?: string;
  /** For `canvas` / `media-library` / `dashboard`: `<resourceId>` */
  resourceId?: string;
  /** The trailing `<documentId>` part — what `_id` of the target doc is */
  documentId: string;
}

/**
 * Parses a GDR URI into its scheme and addressing parts. Throws for an
 * unknown scheme, malformed addressing, or a dataset document ID prefixed
 * with `drafts.` or `versions.<release>.`. Use the stable document ID and
 * select draft or release content through {@link WorkflowInstance.perspective}.
 */
export declare function parseGdr(uri: string): ParsedGdr;

/**
 * Throws {@link PersistedDocShapeError} on shape mismatch. Unlike other
 * persisted docs, this doc carries no model-version stamp to gate on.
 */
export declare function parseGuardDocument(doc: unknown): MutationGuardDoc;

/**
 * Parse a fetched `sanity.workflow.instance` document, failing hard with a
 * {@link PersistedDocShapeError} naming the document and every offending
 * field. The caller's model-version gate (`assertReadableModel`) must run
 * first: a doc from beyond the reader floor is a governed
 * `ModelVersionAheadError`, not a shape error.
 */
export declare function parseInstanceDocument(doc: unknown): WorkflowInstance;

/** {@link parseInstanceDocument}'s row-projection counterpart, with the same
 *  gate-first contract. */
export declare function parseInstancePreviewDocument(
  doc: unknown,
): WorkflowInstancePreview;

/**
 * Parse a resource-shaped GDR (`<type>:<id>`, no document part) into the
 * {@link WorkflowResource} it names. The one grammar for resource addresses —
 * hosts validate/parse through this instead of hand-rolling the split.
 * Throws on unknown type, extra `:` parts (that shape is a document GDR —
 * see {@link parseGdr}), or a malformed dataset id.
 */
export declare function parseResourceGdr(uri: string): WorkflowResource;

/**
 * A stage's multi-guard deploy failed *after* at least one guard already landed.
 * Those partial locks can't be cleanly undone (guard docs have no transactional
 * deploy). Inside the engine `deployOrRollback` rolls the state move back
 * and escalates this to a loud {@link WorkflowStateDivergedError}; a caller that
 * invokes {@link deployStageGuards} directly (without that rollback wrapper) can
 * also see it, so it's exported to be catchable by type.
 */
export declare class PartialGuardDeployError extends WorkflowError<"partial-guard-deploy"> {
  readonly stageName: string;
  readonly deployed: number;
  /** The cleanup failure, when newly created guards could not be retracted. */
  readonly rollbackError?: unknown;
  constructor(args: {
    stageName: string;
    deployed: number;
    cause: unknown;
    rollbackError?: unknown;
  });
}

export declare interface PendingEffect {
  _key: string;
  _type?: "pendingEffect";
  name: EffectName;
  title?: string;
  description?: string;
  /**
   * Authoring bindings preserved verbatim (GROQ strings over the rendered
   * scope). The resolved concrete values live on `params`. Useful for
   * audit / debugging — the runtime should always read from `params`.
   */
  bindings?: Record<string, string>;
  params: Record<string, unknown>;
  origin: EffectOrigin;
  /**
   * Actor that *queued* the effect (the one who fired the action /
   * activated the activity). Separate from `claim.claimedBy`, which is the
   * actor that later picks it up for dispatch.
   */
  actor?: Actor;
  queuedAt: string;
  /**
   * `_key` of the stage entry this effect was queued under — for a
   * transition's effects, the entry being entered. Carried onto the
   * completion's history row, where it is what ties a run to its stage
   * entry for the `$effectStatus` read. Absent only on entries persisted
   * before the engine stamped it.
   */
  stageEntryKey?: string;
  /**
   * Presence = a drainer is dispatching this entry. Absence = the entry
   * is unclaimed and eligible for drain. Settled entries (any
   * {@link EffectRunStatus}) don't live on `pendingEffects[]` at all; they
   * move to `effectHistory[]`.
   */
  claim?: PendingEffectClaim;
}

/**
 * A claim on a pending effect — presence means a drainer has taken
 * dispatch responsibility for the entry. Absence means the entry is
 * available. There is intentionally no `status` enum; presence of
 * `claim` is the sole marker.
 *
 * Wire format includes `_type` so future fields can land additively
 * without parsing strings.
 */
export declare interface PendingEffectClaim {
  _type: "pendingEffect.claim";
  claimedAt: string;
  claimedBy: Actor;
  /**
   * When this claim's lease lapses. Past this instant the claimer is
   * presumed dead: a drain may take the claim over and `sweepStaleClaims`
   * may force-release it. Absent only on claims persisted before leases
   * existed — treated as already expired, so the exact entries leases
   * exist to recover (claimed-then-abandoned) stay recoverable.
   *
   * There is deliberately no attempt counter here: the retry count is the
   * `effectClaimReleased` history rows for the entry's `_key` (plus the
   * live claim), and a field would drift from that trail across releases.
   */
  leaseExpiresAt?: string;
  /**
   * The exact-claim identity a mid-dispatch state report must present.
   * `effectKey` cannot serve: a lease takeover keeps the same key, so a
   * superseded handler holding only the key could still write. The token is
   * minted fresh on every claim and takeover; `commitEffectOps` rejects a
   * report whose token no longer matches before writing anything. Absent
   * only on claims persisted before tokens existed — those never match, so
   * their dispatches simply cannot report mid-flight.
   */
  claimToken?: string;
}

/**
 * A persisted engine-owned document failed its shape parse — the stored
 * field tree does not match what this engine's data model declares for the
 * doc type. Distinct from {@link ModelVersionAheadError} (a declared,
 * governed fence: upgrade the engine); this is UNGOVERNED corruption — a
 * document no conforming engine wrote — and the read fails hard instead of
 * letting the malformed value corrupt behavior downstream. The issues name
 * every offending field path.
 */
export declare class PersistedDocShapeError extends WorkflowError<"persisted-doc-shape"> {
  readonly documentId: string;
  readonly documentType: string;
  readonly issues: ValidationIssue[];
  constructor(args: {
    documentId: string;
    documentType: string;
    issues: ValidationIssue[];
  });
}

export declare type PersonActor = Omit<Actor, "kind"> & {
  readonly kind: "person";
};

/**
 * The namespace a bare principal-id string belongs to.
 *
 * - `global` — account-global (comparable across every org-level context)
 * - `project` — scoped to ONE project; which project is not in the string,
 *   it comes from context (for stored engine values: the anchor resource
 *   the document lives in)
 * - `robot` — a token principal with one universal id (never needs mapping)
 * - `sentinel` — `<anonymous>` / `<system>`, never a person
 * - `unknown` — unclassifiable; treat as unresolvable and surface it
 */
export declare type PrincipalNamespace =
  | "global"
  | "project"
  | "robot"
  | "sentinel"
  | "unknown";

/**
 * One row of the instance's idempotency ledger — a caller-supplied
 * `idempotencyKey` a state-changing verb already committed under. Recorded in
 * the same CAS commit as the operation it dedupes, so "the op applied" and
 * "the key is recorded" can never diverge. Rows expire at `expiresAt` and are
 * pruned lazily whenever a later keyed operation commits.
 */
export declare interface ProcessedRequest {
  _key: string;
  _type: "processedRequest";
  /** The caller-supplied idempotency key. */
  key: string;
  /** The verb the key was processed under. Reusing a live key on a
   *  different verb is a caller bug and throws. */
  op: string;
  processedAt: string;
  expiresAt: string;
}

/**
 * The execution-environment user properties a process shell (CLI, MCP
 * server) attaches to its store — the sanity CLI's precedent set, joined
 * to events by sessionId downstream. The `surface` marker is what lets
 * intake data slice per shell; user identity is deliberately absent
 * (the intake service resolves the sender from the authenticated session
 * on every event).
 */
export declare function processShellUserProperties<
  Surface extends "cli" | "mcp",
>(
  surface: Surface,
): {
  surface: Surface;
  machinePlatform: string;
  cpuArchitecture: string;
  runtime: string;
  runtimeVersion: string;
};

/** `setProgress`'s field addressing: a bare name targets the workflow scope;
 *  pass `{scope: 'stage', field}` for a stage-scope progress field. */
export declare type ProgressTarget =
  | string
  | {
      scope: "workflow" | "stage";
      field: string;
    };

/** Project a readable instance into the only row shape start predicates may scan. */
export declare function projectStartSliceRow(
  instance: WorkflowInstance,
): StartSliceRow;

/**
 * Project a store-resolved doc onto its watch ref's identity, the way the
 * lake's perspective reads do: the published-form id becomes `_id` (the form
 * the session keys its overlay and snapshot by), and a draft/version
 * representation's stored id rides along as `_originalId` — session-side
 * conditions (including the `_originalId in path("versions.**")` shape) then
 * read the same projected identity as the engine's perspective-aware hydration.
 * Strict by construction: only a canonical watch-reference representation is
 * accepted — an id that merely *ends* in
 * the watched id (another doc's dotted id under a version prefix), a release
 * the perspective doesn't read, or a draft the perspective makes invisible is
 * a store routing bug, and projecting it would make content the engine's read
 * can never see impersonate the watched doc silently, so it throws instead.
 */
export declare function projectToWatchRef(args: {
  doc: SanityDocument;
  ref: SubscriptionDocument;
  perspective: WorkflowPerspective | undefined;
}): SanityDocument;

/** Host integration for current project-user data. */
export declare interface ProjectUserDirectory<User> {
  /** Return `inaccessible` for lookup failures; directory methods must not reject. */
  readonly findById: (id: string) => Promise<ProjectUserLookup<User>>;
  readonly findByEmail?: (email: string) => Promise<ProjectUserLookup<User>>;
}

export declare type ProjectUserLookup<User> =
  | {
      readonly status: "resolved";
      readonly user: User;
    }
  | {
      readonly status: "missing";
    }
  | {
      readonly status: "inaccessible";
      readonly cause?: unknown;
    };

export declare interface QueryArgs {
  groq: string;
  params?: Record<string, unknown>;
}

export declare interface QueryInScopeArgs extends InstanceRefArgs, QueryArgs {}

export { quoted };

export declare const READER_MODEL_ROLLOUT_URL =
  "https://www.sanity.io/docs/workflows/prerelease";

/** A producer has not acknowledged the floor required by its submitted definitions. */
export declare class ReaderModelAcknowledgementError extends WorkflowError<"reader-model-acknowledgement"> {
  readonly code = "WORKFLOW_READER_MODEL_ACKNOWLEDGEMENT_MISMATCH";
  readonly expectedMinReaderModel: unknown;
  readonly requiredMinReaderModel: number;
  readonly engineMinReaderModel = 4;
  readonly engineMaxReaderModel = 10;
  readonly engineModelVersion = 10;
  readonly documentationUrl = "https://www.sanity.io/docs/workflows/prerelease";
  constructor(
    expectedMinReaderModel: unknown,
    options?: {
      requiredMinReaderModel?: number;
      context?: string;
    },
  );
}

/**
 * The single definition of the instance read discipline (model gate
 * {@link assertReadableModel} first, shape parse
 * {@link parseInstanceDocument} second), shared by the point-read funnel
 * above and the list-read sites that fetch instance rows in bulk.
 */
export declare function readInstanceDoc(doc: SanityDocument): WorkflowInstance;

/** {@link readInstanceDoc}'s preview-projection counterpart: the same
 *  gate-then-parse order over an `instancePreviewsQuery` result. */
export declare function readInstancePreviewDoc(
  doc: unknown,
): WorkflowInstancePreview;

/**
 * @internal Whether `condition` reads `$now`, the one clock the engine binds.
 * Shared with the Blueprints generator, which cannot narrow a trigger for a
 * condition the clock can change; not a supported consumer API. Throws
 * groq-js's syntax error on a condition that does not parse.
 */
export declare function _readsNow(condition: Condition_2): boolean;

/**
 * Whether a watched ref reads RAW — never perspective-scoped. The
 * instance, its ancestors, and its spawned children (all instance docs), and
 * `release.ref` system docs (`system.release`) are not versioned by a release
 * perspective; everything else is content and resolves to its
 * version/draft/published form. This is the single encoding of the rule
 * the {@link WatchSet} `perspective` contract describes to consumers, and
 * the rule `hydrateSnapshot` applies on the fetch side.
 */
export declare function readsRaw(ref: { type: string }): boolean;

/** Whether a GROQ expression reads its root document at all: a named path or a
 *  whole-document read. Reading another document is not a read of this one, so
 *  {@link RootDocumentReads.readsOtherDocuments} alone answers `false`, as does
 *  a malformed expression. */
export declare function readsRootDocument(groq: string): boolean;

/** Make a GDR pointer to a Canvas-resource doc. */
export declare function refCanvas<TType extends string = string>({
  resourceId,
  documentId,
  type,
}: ResourceRefArgs<TType>): GlobalDocumentReference<TType>;

/** Make a GDR pointer to a Dashboard-resource doc. */
export declare function refDashboard<TType extends string = string>({
  resourceId,
  documentId,
  type,
}: ResourceRefArgs<TType>): GlobalDocumentReference<TType>;

/**
 * Creates a typed reference to a dataset document. Pass the stable document
 * ID; `drafts.` and `versions.<release>.` prefixes throw. Select draft or
 * release content through {@link WorkflowInstance.perspective}.
 */
export declare function refDataset<TType extends string = string>({
  projectId,
  dataset,
  documentId,
  type,
}: {
  projectId: string;
  dataset: string;
  documentId: string;
  type: TType;
}): GlobalDocumentReference<TType>;

/**
 * Kinds whose entries carry the accepted-target `types` facet — the
 * content-document reference kinds. `release.ref` is excluded: it points at a
 * release system doc whose type is fixed.
 */
export declare function refKindAcceptsTypes(
  kind: string,
): kind is "doc.ref" | "doc.refs" | "subject";

/** Make a GDR pointer to a Media-Library-resource doc. */
export declare function refMediaLibrary<TType extends string = string>({
  resourceId,
  documentId,
  type,
}: ResourceRefArgs<TType>): GlobalDocumentReference<TType>;

/**
 * Thrown when a field write carries a ref to a resource outside the
 * declared surface. The write does not commit; the engine has not mutated
 * state.
 */
export declare class RefResourceUndeclaredError extends WorkflowError<"ref-resource-undeclared"> {
  readonly entryType: string;
  readonly entryName: string;
  readonly issues: string[];
  constructor(args: { entryName: string; entryType: string; issues: string[] });
}

/**
 * Every spawn reference a definition carries, as logical
 * {@link LogicalRef} entries — the definition's outgoing edges in the
 * spawn-dependency graph. The one walk deploy ordering, delete's
 * referrer check, and external dependency tooling all share, so what
 * counts as a reference can never drift between them.
 */
export declare function refsOf(def: WorkflowDefinition): LogicalRef[];

/**
 * GDR `type`s in a reference-kind ({@link refKindAcceptsTypes}) value that the
 * entry's declared `types` reject — empty when it conforms, no `types` are
 * declared, or the kind isn't a ref. Skips non-GDR-shaped values; the shape
 * schemas already reject those.
 */
export declare function rejectedRefTypes(args: {
  entryType: string;
  types: readonly string[] | undefined;
  value: unknown;
}): string[];

/**
 * The `_id` of a release's system document — the one owner of the
 * `_.releases.<name>` spelling, shared by {@link releaseRef} and the
 * validation cross-check so the id scheme can't drift between them.
 */
export declare function releaseDocId(releaseName: string): string;

/**
 * A reference to a Content Release. Extends the GDR shape (so existing
 * doc-ref machinery treats it as a reference to the `_.releases.<name>`
 * system document) with the bare `releaseName` the engine reads to
 * build the read perspective stack.
 *
 * `id` points at the release system doc (`_.releases.<name>` in the
 * workflow resource); `type` is always `"system.release"`;
 * `releaseName` is the final segment of the release id.
 */
export declare interface ReleaseRef extends GlobalDocumentReference<"system.release"> {
  releaseName: string;
}

/**
 * Build a {@link ReleaseRef} — the one constructor for the id ↔
 * `releaseName` pairing, so the envelope can't be assembled out of step
 * (validation cross-checks the pairing, but only at instance-write time).
 */
export declare function releaseRef({
  res,
  releaseName,
}: {
  res: WorkflowResource;
  releaseName: string;
}): ReleaseRef;

/**
 * The remediations that would unstick a diagnosis — the *what to do about it*
 * half. Empty unless the instance is `stuck`: a `waiting` instance advances on
 * its own next action (see `availableActions`), and terminal or `progressing`
 * ones need nothing. Each verb is flagged
 * {@link SuggestedRemediation.available} from the runnable-verb vocabulary.
 */
export declare function remediationsFor(
  diagnosis: Diagnosis,
): SuggestedRemediation[];

/**
 * A verb that would unstick a {@link StuckCause} — the *what to do about it*
 * half of a diagnosis. Surface-neutral identifiers; a consumer maps each to
 * its own command or button. `retry-effect` is not yet a callable engine
 * operation — see {@link SuggestedRemediation.available}.
 */
export declare type RemediationVerb =
  | "retry-effect"
  | "drain-effects"
  | "reset-activity"
  | "set-stage"
  | "abort";

/**
 * Where an engine event came from. Narrower than the vocabulary a host can
 * declare, because {@link EXECUTION_KINDS} values naming a role rather than
 * a host are projected onto one: `drainer` reports `server`, and
 * `interactive`, `script`, and `test` report `other`, as does any value
 * outside the vocabulary. Every other shipped value reports itself.
 */
export declare type ReportedExecutionKind =
  | "cli"
  | "mcp"
  | "other"
  | "sdk"
  | "server"
  | "studio";

/** @internal Validated project-member reads shared by workspace adapters; not a supported consumer API. */
export declare function _requestProjectMembers(
  request: (options: { url: string }) => Promise<unknown>,
  projectId: string,
): Promise<_ClientProjectMember[]>;

/** The reader model a deployment must acknowledge for its submitted definitions. */
export declare function requiredDefinitionReaderModel(
  definitions: readonly unknown[],
): number;

/**
 * Thrown when a workflow is started (or a child spawned) without a value for
 * a field entry marked `required`. Mirrors {@link ActionParamsInvalidError}:
 * the engine has NOT created the instance — a missing load-bearing field
 * (e.g. the subject of a review) screams here rather than silently defaulting
 * to `null`/`[]` and birthing a half-formed instance mid-process.
 */
export declare class RequiredFieldNotProvidedError extends WorkflowError<"required-field-not-provided"> {
  readonly definition?: string;
  readonly missing: {
    name: string;
    type: string;
  }[];
  constructor(args: {
    definition?: string;
    missing: {
      name: string;
      type: string;
    }[];
  });
}

/** The known persisted-model requirements applicable to one canonical stored tree. */
export declare function requiredModelFeatures(
  documentType: DataModelDocumentType,
  document: unknown,
): readonly DataModelChange[];

/** The oldest engine model that can safely interpret one canonical stored tree. */
export declare function requiredReaderModel(
  documentType: DataModelDocumentType,
  document: unknown,
): number;

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

/**
 * Identity and display copy for an unmet requirement. Authored requirements use
 * their declared names; required-reference readability checks use `field:<name>`.
 */
export declare interface RequirementDescriptor {
  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[];

export declare interface ResetActivityArgs extends DedupableOperationArgs {
  /** Name of the activity to reset, within the instance's current stage. */
  activity: string;
  /**
   * The target status. `active` (the default) reopens the activity for
   * caller-fired actions. `skipped` counts the activity as resolved for
   * `$allActivitiesDone`. Returning to `active` does not repeat a `when`
   * action that already fired during this stage visit.
   */
  to?: ResetActivityTarget;
}

export declare type ResetActivityResult =
  | {
      fired: false;
    }
  | {
      fired: true;
      stage: StageName;
      activity: ActivityName;
      from: ActivityStatus;
      to: ResetActivityTarget;
    };

/**
 * What to reset a stuck activity INTO — the two non-`failed` outcomes that
 * unstick a stage gated on it. `active` re-runs it (back in progress, so a
 * caller drives it to completion again); `skipped` bypasses it (terminal but
 * resolved, so `$allActivitiesDone` can satisfy and a gated exit transition
 * fire). `done` is deliberately absent: a reset is recovery, not a silent
 * declaration that the work succeeded.
 */
export declare type ResetActivityTarget = "active" | "skipped";

/**
 * Resolve the engine's `WorkflowAccess` for a client — actor and grants
 * (when a path is supplied) fetched from its token in parallel and cached.
 * Throws if the client can't yield an actor — the engine refuses to operate
 * without an identity. A grants-fetch failure degrades open instead: the
 * rendered `$can` stays undefined and the real Sanity write boundary still
 * enforces. Does not fetch User Attributes; see {@link resolveUserAttributes}.
 */
export declare function resolveAccess(
  taggedClient: WorkflowClient,
  args?: ResolveAccessArgs,
): Promise<WorkflowAccess>;

export declare interface ResolveAccessArgs {
  /**
   * Where the engine should fetch grants from the supplied client,
   * e.g. a Canvas resource at `/canvases/<resourceId>/acl` or a
   * dataset at `/projects/<id>/datasets/<ds>/acl`. Omit to skip the
   * grants fetch (the rendered `$can` stays undefined).
   */
  grantsFromPath?: string;
}

/** Resolves person provenance without treating agent or system ids as user ids. */
export declare function resolveActor<User>(
  directory: ProjectUserDirectory<User>,
  actor: Actor,
): Promise<ActorResolution<User>>;

/** Resolve an actor through a plain engine client, without a UI adapter. */
export declare function resolveClientActor(
  client: WorkflowClient,
  args: ResolveClientActorArgs,
): Promise<ActorResolution<ClientProjectUser>>;

export declare interface ResolveClientActorArgs {
  readonly actor: Actor;
  readonly projectId: string;
}

/** {@link EngineEffectsArgs} after the engine applied its defaults. */
export declare interface ResolvedEngineEffects {
  readonly handlers: Readonly<Record<string, EffectHandler>>;
  readonly missingHandler: MissingHandlerPolicy;
}

/**
 * A resolved field entry as the engine persists it on an instance.
 * Discriminated by `_type` (bare — unique within this union); the `value`
 * type follows FieldValueMap. A `query`-sourced entry (its definition's
 * `initialValue` is `{type:'query'}`, of any kind) additionally carries
 * `resolvedAt` — the lake-read time — so `resolvedAt` is provenance-driven,
 * not kind-specific. `object` / `array` entries carry their declared
 * sub-field shape (`fields` / `of`) — and the reference kinds
 * ({@link refKindAcceptsTypes}) their declared accepted `types`, and
 * assignment kinds their eligible `roles` — so the instance is
 * self-describing for op-time validation and rendering.
 */
export declare type ResolvedFieldEntry = {
  [K in FieldKind]: {
    _key: string;
    _type: K;
    name: string;
    title?: string;
    description?: string;
    value: FieldValueMap[K];
    /** Lake-read time, present only on `query`-sourced entries. */
    resolvedAt?: string;
    options?: ChoiceOptions;
    validation?: ScalarValidation;
  } & (K extends "object"
    ? {
        fields: FieldShape[];
      }
    : Record<never, never>) &
    (K extends "array"
      ? {
          of: FieldShape[];
        }
      : Record<never, never>) &
    (K extends "assignee" | "assignees"
      ? {
          roles?: string[];
        }
      : Record<never, never>) &
    (K extends "doc.ref" | "doc.refs" | "subject"
      ? {
          types?: string[];
        }
      : Record<never, never>);
}[FieldKind];

/** Resolves against the OPEN stage for stage/activity scopes; `undefined`
 *  when the field hasn't resolved yet (e.g. an activity field before activation). */
export declare function resolveFieldEntry(
  instance: WorkflowInstance,
  site: {
    scope: FieldScope;
    activity?: ActivityName;
    name: string;
  },
): ResolvedFieldEntry | undefined;

/**
 * Resolves telemetry build or execution mode from `NODE_ENV`.
 * `production` stays `production`; `development` and `test` map to `development`.
 * Other values use the required fallback: CLI and MCP pass `production`, SDK
 * passes `development`. This does not identify the target deployment or dataset.
 * Unsupported outside the Workflows packages.
 * @internal
 */
export declare function _resolveTelemetryEnvironment(
  nodeEnv: string | undefined,
  fallback: "development" | "production",
): "development" | "production";

/**
 * Resolve the caller's advisory `$attributes`. Results are cached per client
 * and organization. Expected absences (401–404) leave attributes undefined;
 * unexpected failures throw.
 * Call only from soft-gate paths (evaluate / fireAction filter re-check /
 * editField), never from ticks or drainers.
 */
export declare function resolveUserAttributes(
  taggedClient: WorkflowClient,
): Promise<UserAttributes | undefined>;

/**
 * A map binding each resource-alias name to the physical {@link WorkflowResource}
 * it resolves to at deploy. Parallels the role-alias map: where role aliases map
 * a role to its fulfillers, resource aliases map a logical content reference
 * (`@<alias>:<id>`) to a physical resource. Swapping the map is how the same
 * source definitions deploy to different environments.
 */
export declare type ResourceAliases = Record<string, WorkflowResource>;

/**
 * Collapse a deployment's `resourceAliases` bindings into the
 * {@link ResourceAliases} map (handle name → physical resource) that
 * `deployDefinitions` expands `@<handle>:` references against. Deploy-time
 * only — the map never reaches any other verb. A duplicate binding name
 * silently overwrites here (last wins), which is why `DeploymentSchema`
 * rejects one at parse time, before this ever runs.
 */
export declare function resourceAliasesToMap(
  resourceAliases: WorkflowDeployment["resourceAliases"],
): ResourceAliases;

/**
 * Cross-resource read routing override — return a client for the parsed
 * GDR's resource, or `undefined` to let the engine route it. Serving a
 * resource also declares it on the written-ref surface, so narrowing this
 * resolver rejects refs to resources it stops serving; engine verb scopes
 * also rebind any returned client onto their own API version.
 */
export declare type ResourceClientResolver = (
  parsed: ParsedGdr,
) => WorkflowClient | undefined;

/**
 * The {@link WorkflowResource} an already-parsed GDR addresses. Total: a caller
 * holding a {@link ParsedGdr} has already proven the URI parsed, so there's no
 * not-a-GDR case to handle. The `?? ''` only satisfies the cross-scheme-optional
 * `resourceId` type — {@link parseGdr} guarantees it is present per non-dataset
 * scheme, so the fallback never fires.
 */
export declare function resourceFromParsed(parsed: ParsedGdr): WorkflowResource;

/**
 * Format a {@link WorkflowResource} as a resource-shaped GDR — `<type>:<id>`
 * with no document part (`dataset:abc123.production`, `media-library:mlXyz`).
 * The string form for naming a *resource* (not a document in it) across an
 * API boundary — e.g. the per-call workflow-environment address an MCP tool
 * takes. Inverse of {@link parseResourceGdr}.
 */
export declare function resourceGdr(res: WorkflowResource): string;

/** Args for the single-resource ref constructors ({@link refCanvas}, {@link refMediaLibrary}, {@link refDashboard}). */
export declare interface ResourceRefArgs<TType extends string> {
  resourceId: string;
  documentId: string;
  type: TType;
}

export declare interface ResourceSurface {
  /** True when the parsed GDR targets a declared resource. */
  allows: (parsed: ParsedGdr) => boolean;
  /** Prose rendering of the declared surface, for rejection messages. */
  description: string;
}

/**
 * Retract every guard for a stage being exited by deleting it, but
 * only once the instance has genuinely moved off that stage — or was aborted
 * on it: an aborted instance keeps its `currentStage` (no stage move), so the
 * `abortedAt` stamp is what licenses retracting the stage it still occupies. The
 * gate is `abortedAt`, not `completedAt` — normal completion parks the
 * instance on a structurally terminal stage whose guards must stay live.
 * Skip if it is still live on the stage (a concurrent loop-back re-entered
 * the stage and must keep its lock) or gone (leave the lock as the orphan
 * seam rather than silently unlocking a vanished instance — the same
 * over-lock direction as deploy).
 *
 * Guard revisions are observed before the live-stage gate, then only those
 * revisions are deleted: a deploy landing in between changes the revision,
 * so the delete's revision fence fails instead of deleting the active guard.
 */
export declare function retractStageGuards(args: StageGuardArgs): Promise<void>;

/**
 * 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.
 */
export declare type RoleAliases = Record<string, string[]>;

/** What a GROQ expression reads off its root document: the candidate a
 *  `start.filter` binds, not an item inside a rebound scope (filters, `map`). */
export declare interface RootDocumentReads {
  /**
   * The attribute paths read, dot-joined, deduped and ascending. Element and
   * array access end a path, so `tags[0]` reads `tags` and `authors[].year`
   * reads `authors`, and a dereference ends it at the reference, so
   * `author->name` reads `author`.
   *
   * Every segment of a path is a bare GROQ attribute name, so the path can be
   * written back as GROQ and read the same attributes. A read through an
   * attribute name that needs quoting has no path: `@["a.b"]` reads the whole
   * document rather than `a` then `b`, and `tags["a.b"]` reads `tags`.
   */
  paths: string[];
  /**
   * `true` when the expression reads the root document in a way no
   * {@link RootDocumentReads.paths} entry describes. Any write to the document
   * may then change what it evaluates to. The cases are:
   *
   * - the whole document, through `@` or a `^` that escapes past the outermost
   *   scope;
   * - an attribute of the document itself named by an expression, or whose
   *   name needs quoting: `@["a.b"]`. Below a bare prefix it is a path
   *   instead, so `tags["a.b"]` reads `tags`;
   * - a function handed the scope implicitly: `references()`,
   *   `sanity::versionOf()`, `sanity::partOfRelease()`.
   */
  readsWholeDocument: boolean;
  /**
   * Whether the expression resolves against a document other than the one in
   * scope: a dataset scan (`*[…]`) or a dereference (`->`), at any depth. Its
   * value can then change with no write to the root document at all.
   */
  readsOtherDocuments: boolean;
}

/** What `groq` reads: its own document, and whether it reaches past it. A
 *  malformed expression reads nothing, so every member comes back empty or
 *  `false`. */
export declare function rootDocumentReads(groq: string): RootDocumentReads;

/**
 * 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.
 */
export 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.
 */
export declare type RuntimeKind = "function" | "durableFunction" | "selfHosted";

/** Whether two workflow resources address the same place. */
export declare function sameResource(
  a: WorkflowResource,
  b: WorkflowResource,
): boolean;

/**
 * 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.
 */
export declare interface ScalarValidation {
  min?: number | undefined;
  max?: number | undefined;
}

export declare function scalarValidationIssues(args: {
  entryType: string;
  validation: ScalarValidation | undefined;
  value: unknown;
}): string[] | undefined;

/**
 * The DECLARED field tree of a runtime schema — every entry key (optional
 * keys marked `key?`), every enum vocabulary, every variant arm — walked out
 * of valibot's runtime shape. The declared twin of `fieldTreeShape` (which
 * walks a CONCRETE document): the model-surface gate pins persisted doc
 * types by what their schema declares, so an optional field no fixture
 * reaches is still ledger-visible. Recursive grammars (a field shape nesting
 * field shapes) close with a `'(circular)'` marker.
 */
export declare function schemaTreeShape(schema: v.GenericSchema): unknown;

export { ScopeAssignment };

export declare interface ScopedInitialFieldDeclarations {
  workflowFields: readonly FieldEntry[];
  stages?: readonly {
    name: string;
    fields?: readonly FieldEntry[] | undefined;
    activities?:
      | readonly {
          name: string;
          fields?: readonly FieldEntry[] | undefined;
        }[]
      | undefined;
  }[];
}

export declare type Semantic = SignalSemantic | CustomSemantic;

export { sentenceCase };

export declare interface SessionArgs {
  /** The instance document to bind — typically the consumer's live-store value. */
  instance: WorkflowInstance;
  /** URL path for grant resolution — see `StartInstanceArgs.grantsFromPath`. */
  grantsFromPath?: string | undefined;
}

export declare interface SetStageArgs extends DedupableOperationArgs {
  /** Stage id to force the instance into. */
  targetStage: string;
  /** Free-text reason — surfaces on history entries for audit. */
  reason?: string;
  /**
   * Initial values for field entries on the target stage, in the same shape as
   * `startInstance.initialFields`; reserved for the stage-field work.
   */
  initialFields?: InitialFieldValue[];
}

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

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

/**
 * No-op logger. Default for library callers that don't want any
 * output unless explicitly opted in.
 */
export declare const silentLogger: EngineLogger;

/**
 * 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.
 */
export declare type SingleSubjectRequirement = RequirementBase & {
  type: "singleSubject";
};

/**
 * Evaluate a declared `singleSubject` requirement — resolves `true` when it
 * REFUSES the start: an in-flight instance (no `completedAt`) of THIS
 * definition already holds the prospective subject. The subject resolves from
 * the `$fields` map's subject entry (a GDR envelope, `.id` the identity),
 * falling back to `scope.subject`. No subject in hand means nothing to compare — the requirement
 * passes; a pre-flight surface reports the unbound subject entry as
 * provisional through {@link unboundRequirementReads}. The rule is
 * count-shaped, so an absent `scope.fetchDataset` THROWS like a
 * dataset-reading GROQ requirement — an empty `*` would pass vacuously. One
 * evaluator serves every moment: the `startInstance` gate enforces it
 * (`StartNotAllowedError`), the `evaluateStart` verb pre-flights it, and start
 * surfaces evaluate it directly for their controls — every site gated by
 * {@link hasSingleSubjectRequirement}, so only a rule this engine knows arrives
 * here (an absent or unsupported rule is the caller's contract violation).
 * Advisory under races like every engine-side check.
 */
export declare function singleSubjectRequirementRefused(args: {
  definition: Pick<ApplicabilitySource, "name" | "fields" | "start">;
  /** A produced `$fields` map (`startFieldsParam`, or a surface's seed map). */
  fields?: Record<string, unknown> | undefined;
  scope?: StartScope | undefined;
}): Promise<boolean>;

/** One site whose verdict a proposed assignment flips. */
export declare interface SiteConsequence {
  site: InsightSite;
  before: ConditionOutcome;
  after: ConditionOutcome;
}

/**
 * Suspends for `ms` before resolving. The engine's only deliberate wait is a
 * `retry` policy's backoff between attempts inside one `drainEffects` call, so
 * a deterministic harness substitutes one that moves its {@link Clock} instead
 * of spending real time. Injected once beside the clock, never per call.
 *
 * A substitute must not resolve before `ms` has passed on whatever clock the
 * engine reads: a policy's pacing and its `expiryMs` window are both judged
 * against that clock.
 */
export declare type Sleeper = (ms: number) => Promise<void>;

/** Pure resource-local dereferencing for held snapshot evaluation. */
export declare function snapshotGuardDereference(args: {
  snapshot: HydratedSnapshot;
  resource: WorkflowResource;
}): GuardDereference;

/** One statically invalid parent-to-child spawn contract found at deploy. */
export declare type SpawnContractIssue =
  | {
      reason: "unresolved-definition";
      from: string;
      ref: string;
    }
  | {
      reason: "unconsumable-field";
      from: string;
      child: string;
      field: string;
      detail: string;
    };

/** Deploy refused one or more invalid static `spawn` contracts. */
export declare class SpawnContractsInvalidError extends WorkflowError<"spawn-contracts-invalid"> {
  readonly issues: SpawnContractIssue[];
  constructor(args: { issues: SpawnContractIssue[]; message: string });
}

/** One declared `spawn` block and the address it sits at. */
export declare interface SpawnSite {
  stage: string;
  activity: string;
  action: string;
  spawn: Subworkflows;
}

/**
 * Every child cohort a definition spawns, in definition order. An action's
 * `spawn` block is the only carrier, and one action declares at most one
 * cohort, so each address appears at most once.
 */
export declare function spawnSites(def: WorkflowDefinition): SpawnSite[];

/**
 * 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
 */
export declare type Stage = StageFields<
  FieldEntry,
  Activity,
  Transition,
  Guard,
  Editable
>;

/** A stage's rollup: progress through any exit transition, plus each
 *  activity's own completion answer. */
export declare interface StageAutonomy extends AutonomyAnswer {
  stage: string;
  activities: Record<string, AutonomyAnswer>;
}

/** The stage slice of a rollup. Total by construction — the rollup derives
 *  from the same `definition.stages` consumers iterate, so a miss is an
 *  engine bug worth failing loud on. */
export declare function stageAutonomyOf(
  autonomy: WorkflowAutonomy,
  stageName: string,
): StageAutonomy;

export declare interface StageEntry {
  _key: string;
  name: StageName;
  enteredAt: string;
  /** Set on transition out; absent for the current stage. */
  exitedAt?: string;
  /** Stage-scoped resolved field entries. */
  fields: ResolvedFieldEntry[];
  activities: ActivityEntry[];
}

export declare interface StageEvaluation {
  stage: Stage;
  /** The stage's advisory workflow meaning, unchanged from its definition. */
  semantics?: Semantic[] | undefined;
  activities: ActivityEvaluation[];
  transitions: TransitionEvaluation[];
  /** The stage's causal-autonomy rollup — will it progress without a caller,
   *  and what does it wait on. Definition-derived, identical for every actor. */
  autonomy: StageAutonomy;
}

/** @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;
};

export declare interface StageGuardArgs {
  client: WorkflowClient;
  clientForGdr: ClientForGdr;
  instance: WorkflowInstance;
  definition: WorkflowDefinition;
  stageName: string;
  /** Shell-supplied clock reading (ISO) backing guard `$now` reads. */
  now: string;
  /** The commit's hydrated snapshot, so a `metadata` read dereferences a
   *  `doc.ref` into content. `undefined` → identity-only resolution (content
   *  reads resolve `null`). Required (not optional) so a new call site can't
   *  silently drop it — pass `undefined` deliberately. */
  snapshot: HydratedSnapshot | undefined;
}

export declare type StageName = string;

/** Why a mid-dispatch report's claim no longer authorises it — see
 *  {@link StaleEffectClaimError}. */
export declare type StaleClaimReason =
  | "unclaimed"
  | "claim-superseded"
  | "lease-expired";

/**
 * Thrown when a mid-dispatch state report (`commitEffectOps`) presents a
 * claim token that no longer authorises writing: the entry's claim was
 * released, taken over by another dispatch (`claim-superseded`), or its
 * lease lapsed. Nothing was written — the gate runs before any mutation.
 * The handler should stop reporting; its completion still follows the
 * normal first-writer-wins completion semantics.
 */
export declare class StaleEffectClaimError extends WorkflowError<"stale-effect-claim"> {
  readonly instanceId: string;
  readonly effectKey: string;
  readonly reason: StaleClaimReason;
  constructor(args: {
    instanceId: string;
    effectKey: string;
    reason: StaleClaimReason;
  });
}

/**
 * The vars a definition's `start.filter` reads — the start-filter dialect,
 * not the rendered condition scope (no {@link ConditionVarBinding}: these
 * bind only while the filter is evaluated on the READ side — the
 * `definitionsForDocument` derivation and the Studio start control).
 * `startInstance` never evaluates the filter. BROWSE-TIME-PURE: `$fields` and
 * every caller-bound var (`$actor` / `$assigned` / `$can` / `$attributes` /
 * `$params`) are deliberately absent — a read is deploy-rejected (`$fields`
 * with a pointer to start GROQ requirements; caller vars as silent
 * never-match). Bound in one place: `startContextParams` in the applicability
 * evaluator.
 */
export declare const START_FILTER_VARS: readonly {
  name: string;
  label: string;
  description: string;
}[];

/**
 * The vars a definition's start GROQ requirements read — the start-time readiness
 * dialect: everything the filter context binds ({@link START_FILTER_VARS})
 * plus `$fields`, which start time always has. No candidate root ever binds
 * here (the subject rides `$fields.<entry>.id`; a root read is
 * deploy-rejected). Pre-flights can omit not-yet-collected input bindings and
 * report those reads as provisional. Bound in one place: `startContextParams`
 * in the applicability evaluator.
 */
export declare const START_REQUIREMENT_VARS: readonly {
  name: string;
  label: string;
  description: string;
}[];

/**
 * 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.
 */
export declare type StartBlock = StartFields & {
  kind: StartKind;
};

/**
 * The start-time seed a caller supplies at `startInstance`, stored as
 * {@link WorkflowInstance.context} entries and read back as
 * `$context.<name>`. Written only at start — a completed effect's
 * `outputs` live on the run row and read as `$effects`, a separate bag.
 *
 * Each value may be any JSON — a scalar, a {@link GlobalDocumentReference}, or
 * an arbitrary object/array. Scalars and GDRs store as their typed
 * `context` entries; anything else stores as one `context.json` entry.
 */
export declare type StartContext = Record<string, unknown>;

/**
 * What `evaluateStart` projects — the same gates `startInstance` enforces,
 * as renderable state. `allowed` and `missingRequired` are deliberately
 * orthogonal: a missing required input is a caller mistake (the verb throws
 * `RequiredFieldNotProvidedError` for it), never a readiness verdict.
 */
export declare interface StartEvaluation {
  /** Overall preflight startability: every supplied initial-field row is
   *  valid and every declared start requirement is satisfied. `outcome` describes only the
   *  predicates; structurally invalid rows can therefore produce
   *  `allowed: false` with `outcome: 'satisfied'`. */
  allowed: boolean;
  /**
   * Three-valued, BINDABILITY-AWARE verdict over the start predicates:
   * `'unsatisfied'` is a definitive no for these inputs (disable and
   * explain), `'unevaluable'` means the verdict can't be decided yet —
   * either a null operand reached an ordered comparison, or a predicate
   * reads an entry `initialFields` doesn't supply
   * ({@link StartEvaluation.unboundReads} non-empty). One exception outranks
   * the provisional rule: any definitive requirement refusal keeps the
   * aggregate `'unsatisfied'` even while other reads are unbound. Keep the
   * affordance enabled on `'unevaluable'`; `startInstance` still enforces
   * the final verdict, where absence is final rather than provisional.
   */
  outcome: ConditionOutcome;
  /** One result per declared readiness node, in author order. */
  requirements: StartRequirementEvaluation[];
  /** The `$fields` entries the predicates read that `initialFields` doesn't
   *  supply — "fill these to decide", including a `singleSubject` node's
   *  implicit subject read. Non-empty makes undecided requirements
   *  `'unevaluable'`; a separate definitive refusal still keeps the aggregate
   *  outcome `'unsatisfied'`. Empty when the definition declares no requirements. */
  unboundReads: string[];
  /** Required input entries `initialFields` doesn't fill yet — the rows a
   *  `startInstance` now would throw `RequiredFieldNotProvidedError` about. */
  missingRequired: {
    name: string;
    type: FieldEntry["type"];
  }[];
  /** Supplied rows `startInstance` would reject before writing. Empty means
   *  every row targets a workflow-scope, input-sourced declaration exactly
   *  once. Render these as corrections, not an authorization verdict. */
  invalidInitialFields: InitialFieldIssue[];
}

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

/**
 * Project caller-supplied `initialFields` into the `$fields` map the
 * start-requirement context binds: one key per declared `input`-sourced entry,
 * resolved through the supplied-field lookup — the predicate can only ever see
 * a value the input resolution would persist, and an undeclared supplied name
 * never leaks in. Unsupplied (or null-supplied) entries stay unbound, so a
 * read of one is GROQ null. Document references bind as their GDR envelopes
 * (`$fields.<entry>.id` is the GDR URI).
 */
export declare function startFieldsParam(args: {
  entryDefs: readonly FieldEntry[];
  initialFields: readonly InitialFieldValue[];
}): Record<string, unknown>;

export declare interface StartInstanceArgs {
  /** The definition's `name` — which deployed workflow to instantiate. */
  definition: string;
  /** Optional explicit version. Defaults to the highest deployed version. */
  version?: number;
  /**
   * Initial values for `input`-sourced field entries declared on the
   * workflow definition. Each value is a
   * typed `InitialFieldValue` whose `type` + `name` must match an entry
   * on `definition.fields[]`. Entries not present here resolve to their
   * default (null for scalars, [] for arrays, or the entry's own
   * `initialValue` resolution for query/working-memory entries).
   *
   * To start an instance "about" a specific document, declare a
   * `{ type: "subject", name: "subject", initialValue: { type: "input" } }`
   * entry on the workflow and pass
   * `{ type: "subject", name: "subject", value: { id, type } }` here.
   * Conditions then read it as `$fields.subject`, and document pickers key
   * on the `subject` kind.
   */
  initialFields?: InitialFieldValue[];
  ancestors?: GlobalDocumentReference[];
  /**
   * Stable named values supplied when starting this instance. They cannot
   * be changed after start.
   * Effect bindings and conditions read them as `$context.<name>`; the
   * `$effects` bag is separate (completed effects' outputs only).
   *
   * Values supplied directly to start may be any JSON: a scalar,
   * a {@link GlobalDocumentReference},
   * or an arbitrary object/array. Scalars and GDRs store as their typed
   * `context` entries; anything else stores as one `context.json`
   * entry, so all forms read back the same under `$context.<name>`.
   * A parent's `spawn.context` has a narrower contract: only strings, numbers,
   * booleans, and full GDRs are accepted; nullish results are omitted, and
   * other objects or arrays reject the spawn.
   */
  context?: StartContext;
  /**
   * Caller-supplied id; auto-generated otherwise (mint one with
   * `instanceDocId`). This is start's idempotency key: a retry carrying the
   * same id resumes the earlier attempt's outstanding commits instead of
   * creating a duplicate — the per-instance request ledger can't cover the
   * create (it lives on the instance document), so id identity is the rail.
   * Inputs bind on the create only; a resume never re-reads them.
   */
  instanceId?: string;
  /**
   * URL path on the supplied client where the engine fetches the
   * caller's ACL grants. Identity is always token-resolved — `actor` is
   * resolved from the supplied client's token, never passed in — and grants
   * feed the advisory `$can.*` params action conditions can read;
   * omitting this leaves the rendered `$can` undefined (conditions
   * referencing it fail closed, nothing else is gated engine-side —
   * the real Sanity write boundary still enforces).
   *
   * Canvas-style: `/canvases/<resourceId>/acl`.
   * Project/dataset: `/projects/<id>/datasets/<ds>/acl`.
   */
  grantsFromPath?: string;
  /**
   * Perspective for content reads, including field queries and subworkflow
   * discovery. An explicit value applies to workflow-field initialization
   * and subsequent reads.
   *
   * When omitted, workflow-field queries at start use `drafts`. After those
   * fields resolve, the instance uses `[releaseName]` from its first populated
   * workflow `release.ref` field, or `drafts` when none is populated.
   * Under `drafts`, drafts take precedence over published content.
   *
   * A child's workflow fields initialize under its parent's perspective.
   * Afterward, the child's first populated workflow `release.ref` field
   * selects its release perspective; otherwise it inherits the parent's.
   *
   * Pass `[releaseName]` to read under a Content Release, or
   * `[releaseName, 'drafts']` to include drafts. Engine-owned instance and
   * definition documents, and `system.release` documents, always read under `raw`.
   */
  perspective?: WorkflowPerspective;
}

/**
 * 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.
 */
export declare type StartKind = "interactive" | "autonomous";

/**
 * The declared {@link StartKind} of a definition, defaulting the absent
 * `start` block to `'interactive'` — the one reading rule for every consumer,
 * so definitions deployed before the block existed classify unchanged.
 * Classification only: the engine never gates on it.
 */
export declare function startKindOf(definition: {
  start?:
    | {
        kind?: StartKind | undefined;
      }
    | undefined;
}): StartKind;

/**
 * Thrown by `startInstance` when one or more declared start requirements are
 * not satisfied for the supplied `initialFields`. Carries every unmet node's
 * authored descriptor in declaration order; `evaluateStart` provides the
 * corresponding per-node outcomes and GROQ insights.
 * There is no override arg — like `fireAction`, you don't bypass a verdict,
 * you change what produces it. Advisory under races like every engine-side
 * check.
 */
export declare class StartNotAllowedError extends WorkflowError<"start-not-allowed"> {
  readonly definition: string;
  readonly unmetRequirements: RequirementDescriptor[];
  constructor(args: {
    definition: string;
    unmetRequirements: RequirementDescriptor[];
  });
}

/**
 * Thrown when a start fails AFTER its create committed but BEFORE priming:
 * the instance document exists, unprimed (see {@link isUnprimed}) — a
 * genuinely failed start, but a RESUMABLE one. The error names the id so
 * every surface's failure message can point at the retry rail: retrying
 * `startInstance` with this `instanceId` finishes the start instead of
 * creating a duplicate; aborting the instance discards it.
 */
export declare class StartNotPrimedError extends WorkflowError<"start-not-primed"> {
  readonly instanceId: string;
  constructor(args: { instanceId: string; cause: unknown });
}

/**
 * Thrown when a start's first cascade fails AFTER the instance was created
 * and primed: the run exists — stage entered, activities active, guards
 * deployed — it just hasn't auto-advanced to a stable stage yet. Callers
 * must not present this as a failed start: the workflow IS running, and a
 * `tick` (or retrying `startInstance` with the same `instanceId`) resumes
 * the settling.
 */
export declare class StartNotSettledError extends WorkflowError<"start-not-settled"> {
  readonly instanceId: string;
  /** The primed instance re-read after the cascade failure — absent when
   *  that best-effort read also failed. */
  readonly instance?: WorkflowInstance;
  constructor(args: {
    instanceId: string;
    instance?: WorkflowInstance;
    cause: unknown;
  });
}

/** Advisory only, per {@link isStartableDefinition} — a start surface has no parent context to give a spawn-only child, so it rejects fast with this message instead. */
export declare function startRefusal(definition: {
  lifecycle?: WorkflowLifecycle | undefined;
}): string | undefined;

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

export declare interface StartRequirementEvaluation extends RequirementDescriptor {
  /** Whether this requirement is satisfied, unsatisfied, or not yet decidable. */
  outcome: ConditionOutcome;
  /** GROQ explanation; absent for non-GROQ requirement kinds. */
  insight?: ConditionInsight | undefined;
}

/**
 * The caller-side half of the start contexts — everything the evaluating
 * surface knows that the definition doesn't. Every member is optional
 * because the surfaces genuinely differ (a pure consumer may hold no clock):
 * An absent binding evaluates each read of it to GROQ null, and where that
 * null lands decides the verdict — a predicate that can't decide without
 * the binding fails closed, while a count-of-matches clause over values
 * every row stores passes vacuously (in GROQ null equals only null, so the
 * unbound read matches no stored value). The vars themselves are
 * inventoried in `START_FILTER_VARS` / `START_REQUIREMENT_VARS`; the caller's
 * `$fields` map is NOT scope — `start.filter` never binds it, and
 * `explainStartRequirement` takes it as its own argument.
 */
export declare interface StartScope {
  /** The engine's tag partition — binds `$tag`. */
  tag?: string | undefined;
  /** ISO clock reading — binds `$now`. */
  now?: string | undefined;
  /** Resource-qualified identity of the prospective subject. Unlike a loaded
   *  document's bare `_id`, this stays collision-free across resources. */
  subject?: GdrUri | undefined;
  /**
   * The engine-owned start slice, for predicates that read `*[...]` or for a
   * `singleSubject` requirement — invoked lazily only when evaluation needs it.
   * Each row exposes exactly `{definition, subject, completedAt}`; completed
   * rows are included, so authors qualify in-flight
   * themselves (`!defined(completedAt)`). Absent ⇒ a dataset-reading filter
   * fails closed (this surface cannot see the dataset, so it cannot decide),
   * while a dataset-reading requirement THROWS — see
   * {@link explainStartRequirement}.
   */
  fetchDataset?: (() => Promise<unknown[]>) | undefined;
}

export declare interface StartSliceRow {
  definition: string;
  subject: GdrUri | null;
  completedAt: string | null;
}

/**
 * A field reference with `scope` already resolved — the form every op target carries.
 *
 * @interface
 */
export 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
>;

export declare function stripSystemFields(
  doc: Record<string, unknown>,
): Record<string, unknown>;

/**
 * A fault or missing dependency in an in-flight instance. Missing documents
 * follow effect/activity faults and precede transition faults. The diagnosis
 * is advisory: it does not prohibit actions that can still run.
 * An active activity awaiting a human action is the healthy
 * {@link Diagnosis} `waiting` state.
 *
 * `transition-unevaluable` is the recoverable arm: every activity resolved,
 * but an exit transition's `when` came back GROQ `null` (a referenced operand
 * is missing or unreadable), so selection halts and the cascade re-fires once
 * the operand resolves — where `no-transition-fires` means every `when` is a
 * definite `false`. It carries the undecidable transitions.
 */
export declare type StuckCause =
  | {
      kind: "document-missing";
      documents: MissingDocument[];
    }
  | {
      kind: "failed-effect";
      effect: EffectHistoryEntry;
    }
  | {
      kind: "hung-effect";
      effect: PendingEffect;
    }
  | {
      kind: "failed-activity";
      activity: string;
    }
  | {
      kind: "no-transition-fires";
    }
  | {
      kind: "transition-unevaluable";
      transitions: string[];
    };

/**
 * Display label per {@link SubjectPermissionDenial} —
 * `<permission> on <subject> (<resource>)`. The one display convention for
 * rendering the subject-write shortfall to a person (the subject-forecast
 * twin of {@link deniedGuardLabels}); consumers phrase their own sentence
 * around the labels instead of re-deriving them from the payload.
 */
export declare function subjectDenialLabels(
  denied: SubjectPermissionDenial[],
): string[];

/**
 * One prospective subject write the actor's grants don't allow — the payload
 * of the `subject-permission-denied` {@link DisabledReason} arm.
 */
export declare interface SubjectPermissionDenial {
  /** GDR URI of the subject document the write would target. */
  subject: GdrUri;
  /** Resource-shaped GDR (`<type>:<id>`) of the resource whose ACL denied. */
  resource: string;
  /** The forecast write permission the resource's grants don't confer. */
  permission: DocumentValuePermission;
}

export declare interface SubjectResourceAccess {
  grants: Grant[];
  /** The actor's principal id in this resource's own namespace: per-project user id for a dataset resource, account-global id for an org-level one. */
  actorId: string;
}

/**
 * A document the reactive layer should subscribe to, with its GDR
 * exploded so consumers never re-parse: the resource-addressing parts
 * (from {@link ParsedGdr}), the round-trip `globalDocumentId` URI, and
 * the target doc's schema `_type`. The resource parts let an adapter
 * detect refs pointing at a project/dataset/resource it isn't
 * configured for; `type` feeds per-doc handles (`useDocument` /
 * `editState`).
 */
export declare interface SubscriptionDocument extends ParsedGdr {
  /** Full GDR URI — resource-qualified identity, for round-trip / snapshot keying. */
  globalDocumentId: GdrUri;
  /** Target doc's schema `_type`. */
  type: string;
}

/**
 * Build one {@link SubscriptionDocument} from a {@link GlobalDocumentReference}:
 * the parsed addressing parts plus the round-trip URI and schema `_type`.
 * Exported so adapter tests build fixtures exactly the way production does.
 */
export declare function subscriptionDocument(
  ref: GlobalDocumentReference,
): SubscriptionDocument;

export declare function subscriptionDocumentsForInstance(
  instance: WorkflowInstance,
): WatchSet;

/**
 * One spawned child in the instance's workflow-scope registry
 * (`instance.subworkflows`). A child instance is a real lake document whose
 * lifetime is not bound to any stage, so its record lives at workflow scope —
 * rows are never deleted, and a child's status is always derived from its
 * document (or from {@link SubworkflowEntry.resolved} once it terminated).
 */
export declare interface SubworkflowEntry {
  _key: string;
  /** The spawning activity's name. */
  activity: ActivityName;
  /**
   * The spawning ACTION's name — rows key per (activity entry, spawning
   * action), so two spawn actions on one activity can never cross-adopt
   * each other's children.
   */
  action: string;
  /** The child definition's `name` — adoption never crosses definitions. */
  definition: string;
  /**
   * `_key` of the {@link StageEntry} whose cohort this row currently belongs
   * to. Re-adoption on a stage re-entry re-binds the row to the new entry;
   * a row bound to an exited entry is a *detached* child — still tracked,
   * still propagating, just outside any activity's implicit gate.
   */
  stageEntry: string;
  /**
   * The cohort's stage NAME (denormalized from {@link SubworkflowEntry.stageEntry}
   * for lake queries/inspectors). Deliberately not called `stage`: the child's
   * own stage lives on `resolved.stage` and the `$subworkflows` var row.
   */
  cohortStage: StageName;
  /**
   * Identity of the `forEach` row that produced this child — what adopt
   * matching keys on: `_key` ?? `_id` ?? GDR `id` (a `{id, type}` row with
   * a GDR-URI `id`) for object rows, the value itself for scalar rows.
   */
  rowKey: string;
  /** GDR of the child instance document. */
  ref: GlobalDocumentReference;
  spawnedAt: string;
  /**
   * An abort the engine owes this child but could not perform inside the
   * condemning commit (children are separate documents — aborting one is its
   * own commit). Lives ON the row — a condemned child's whole story is one
   * record — and survives a crash because the row persists; the cascade
   * drains condemned rows (abort child → stamp {@link SubworkflowEntry.resolved})
   * idempotently, and the field stays afterwards as the audit of WHY. Set by
   * a parent abort or an `onExit: "abort"` stage exit; a condemned row is
   * never adopted into a fresh cohort.
   */
  abortPending?: {
    /** The condemning commit's clock reading. */
    at: string;
    /** Why — recorded on the child's own abort history when the drain runs. */
    reason: string;
  };
  /**
   * Terminal cache, stamped when the engine observes the child terminal.
   * Terminal state is immutable, so once stamped the child leaves the
   * watch-set and status derives from here instead of its document.
   */
  resolved?: {
    /** The child's `completedAt` — or the drain's clock reading when the
     *  child document was already gone and only the disposition is known. */
    at: string;
    /** The child's final stage. Absent when the child document vanished
     *  before the engine could observe it. */
    stage?: StageName;
    /** Set when the child was aborted rather than completing normally. */
    aborted?: true;
  };
}

/**
 * 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
 */
export 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
>;

export declare interface SuggestedRemediation {
  verb: RemediationVerb;
  /** True iff a consumer can run this as an engine operation today. `false`
   *  marks a remediation we can name but not yet execute — a planned verb, or
   *  an operational step (re-running the effect drainer). */
  available: boolean;
  /** Surface-neutral one-line rationale — no color or terminal symbols; a
   *  consumer decorates it for its own surface. */
  rationale: string;
}

/**
 * Force-release every pending-effect claim whose lease has expired, so the
 * entries become drainable again after their claimer died between claim and
 * complete. One CAS write per pass (all expired claims at once) with an
 * `effectClaimReleased` audit row per release; the `ifRevisionId` guard is
 * the sweeper election — concurrent sweepers or drainers race safely, the
 * loser re-reads (bounded, then fails loud). Release only: dispatching the
 * recovered entries is the next `drainEffects` call's job. To kill a stuck
 * entry WITHOUT redispatching, report it via
 * `completeEffect({status: 'failed'})` instead.
 *
 * A standalone export, NOT an `Engine` verb: like the guard-lifecycle
 * helpers, this is housekeeping for admin/ops tooling, not part of the
 * editor/runtime verb surface — a drain already self-recovers via takeover.
 */
export declare function sweepStaleClaims(args: {
  client: WorkflowClient;
  tag: string;
  instanceId: string;
  clock?: Clock;
  /** Declared execution context stamped on the release audit rows —
   *  a sweeper runtime declares itself here (identity is its token). */
  executionContext?: DeclaredExecutionContext;
}): Promise<SweepStaleClaimsResult>;

export declare interface SweepStaleClaimsResult {
  /** The entries whose expired claims were force-released, as they stood
   *  before the release (each still carries the expired `claim`). */
  released: PendingEffect[];
}

/** Lake `identity()` sentinel for system-initiated actions. */
export declare const SYSTEM_IDENTITY = "<system>";

/**
 * @internal Sanity's reserved document-type namespaces. Shared with the
 * Studio plugin, which excludes them from an unscoped subject's document
 * search; not a supported consumer API.
 */
export declare const _SYSTEM_TYPE_PREFIXES: readonly string[];

/** Single source of the tag-scope GROQ predicate; the engine's lookups, `workflow.query`, and CLI/MCP reads all call this instead of hand-rolling the filter. */
export declare function tagScopeFilter(): string;

/**
 * Optional telemetry-injection field on the raw `workflow.*` verbs — the
 * telemetry twin of the `Clocked` seam in `clock.ts`. It is exported
 * because those verbs expose this composition helper in their public
 * signatures, but production normally injects a logger once via
 * `createEngine({ telemetry })`, not as an everyday per-call option. A
 * raw-namespace caller that omits it emits nothing (the verbs default to
 * {@link noopTelemetry}).
 */
export declare type Telemetered<T> = T & {
  telemetry?: WorkflowTelemetryLogger;
};

/** Mirror of `@sanity/telemetry`'s `ConsentStatus`. */
export declare type TelemetryConsentStatus =
  | "undetermined"
  | "unset"
  | "granted"
  | "denied";

/**
 * Structural mirror of the `resolveConsent`/`sendEvents` pair in
 * `@sanity/telemetry`'s `CreateBatchedStoreOptions` — assignable to it
 * verbatim.
 */
export declare interface TelemetryIntake {
  resolveConsent: () => Promise<{
    status: TelemetryConsentStatus;
  }>;
  sendEvents: (batch: unknown[]) => Promise<unknown>;
}

/** The slice of a `SanityClient` the intake recipe needs — narrow so
 *  shells can hand in any authenticated client and tests fake exactly
 *  what the recipe reads. `timeout` is the per-request cap in ms — the
 *  real client honors it by aborting the request, which is what actually
 *  closes the socket (a `Promise.race` alone cannot). */
export declare interface TelemetryIntakeClient {
  request: <T>(opts: {
    url: string;
    method?: string;
    body?: unknown;
    tag?: string;
    timeout?: number;
  }) => Promise<T>;
}

/**
 * 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`.
 */
export declare type TerminalActivityStatus = "done" | "skipped" | "failed";

/** See {@link terminalState}. */
export declare type TerminalState = "aborted" | "completed" | "in-flight";

/**
 * Classify an instance by its terminal stamps. The single definition of the
 * precedence rule: aborted instances have `completedAt` too (stamped at the
 * abort, so in-flight queries treat both terminals uniformly), so `abortedAt`
 * must be checked first — `'completed'` means completed *without* an abort.
 */
export declare function terminalState(
  instance: Pick<WorkflowInstance, "completedAt" | "abortedAt">,
): TerminalState;

/**
 * A GDR URI stripped back to its bare document `_id`; a non-GDR string passes
 * through unchanged. The one canonical "URI → bare id" transform — use it
 * wherever a stored ref (which may be a full GDR URI, or already bare) must
 * become a lake-queryable `_id`.
 */
export declare function toBareId(id: string): string;

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

/**
 * One row of a `todoList`-sugar `array` entry, as the desugared `of`
 * persists it. The sugar guarantees the COLUMNS in the schema, not values
 * per row — field validation wraps every declared column in optional, so a
 * `status`-less row is valid lake data. `_key` + `label` identify a row;
 * `status` / `assignee` / `dueDate` are per-row optional. Rows are lake
 * data any client can write — read them through {@link isTodoListItem},
 * never a cast.
 */
export declare interface TodoListItem {
  _key: string;
  label: string;
  status?: string | null;
  /** Singular assignment slot: any number of routing roles and at most one user. */
  assignee?: Assignee[];
  dueDate?: string | null;
}

/**
 * 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.
 */
export declare type Transition = TransitionFields & {
  when: string;
};

export declare interface TransitionEvaluation {
  transition: Transition;
  /**
   * Whether the transition's `when` trigger is definitively satisfied at read
   * time. Projected caller-free, exactly as the engine's cascade evaluates
   * it — the evaluation's actor and grants never participate.
   */
  whenSatisfied: boolean;
  /**
   * The trigger evaluated to GROQ `null` — a referenced operand was missing or
   * incomparable, so it couldn't be decided. `whenSatisfied` is `false`, but
   * this is a *recoverable hold*, not a deliberate `false`: the engine halts
   * selection (it won't fall through to a later transition) and the cascade
   * re-fires once the operand resolves. Lets a diagnosis tell an undecidable
   * hold apart from a genuine routing dead-end.
   */
  unevaluable: boolean;
  /** Derived state of the transition's `when` trigger — the atoms standing between
   *  here and the next stage. `whenSatisfied`/`unevaluable` are projections
   *  of `insight.outcome`; one evaluation feeds all three. */
  insight: ConditionInsight;
}

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

/**
 * Parse a GDR URI, returning `undefined` instead of throwing when the string
 * is not a GDR (or is malformed). The "is this a GDR, and if so its parts"
 * primitive — every "parse a ref, treat unparseable as not-a-GDR" call site
 * routes through this rather than re-spelling the try/catch.
 */
export declare function tryParseGdr(uri: string): ParsedGdr | undefined;

/**
 * The `$fields` entries a start GROQ requirement reads that `fields` does
 * not bind — the BINDABILITY rule every pre-flight surface applies before
 * trusting a verdict over possibly-incomplete inputs. GROQ equality against
 * a missing operand collapses to a definitive-looking answer (`null == x` is
 * false, not null), so a verdict that read an unbound entry is PROVISIONAL in
 * both directions: supplying the entry could overturn a refusal AND an
 * approval. Non-empty ⇒ report "can't decide yet" instead of the collapsed
 * verdict (the `evaluateStart` verb does; the Studio start control does).
 *
 * The GATE never consults this: at `startInstance` the supplied inputs are
 * final, so evaluating over genuine absence — including rules that WANT it,
 * like `!defined($fields.rush)` — is the correct semantics there.
 *
 * `fields` is a produced `$fields` map (`startFieldsParam`, or a surface's
 * seed map) — producers bind only own keys with real values, so key presence
 * IS the supplied-ness rule.
 */
export declare function unboundRequirementReads(
  query: string,
  fields: Record<string, unknown>,
): string[];

/**
 * @internal {@link isEntryUnheld} as GROQ, evaluated with the entry in scope
 * and `$claimLapsedBy` bound to the comparison time. It compares instants, so a
 * stamp in any offset form orders the way the predicate orders it, and it is
 * parenthesised, so it composes into a conjunction unchanged. Shared with the
 * Blueprints runtime; not a supported consumer API.
 */
export declare function _unheldEntryFilter(): string;

/**
 * The diagnose idiom shared by every consumer: each unsatisfied exit
 * transition with its insight summary. Consumers shape the result (the CLI
 * maps by name, the MCP prefixes the site phrase) — the selection lives here
 * so it can't drift between them.
 */
export declare function unsatisfiedTransitionSummaries(
  evaluation: WorkflowEvaluation,
): {
  transition: string;
  summary: string;
}[];

/** Flat key → active-value record bound as advisory `$attributes` when present. */
export declare type UserAttributes = Record<string, unknown>;

/** The identity provider under whichever spelling the answering endpoint used
 *  — the ONE place that disagreement is resolved. */
export declare function userLoginProvider(
  user: ClientProjectUser | undefined,
): string | undefined;

/**
 * Validate a (stored, desugared) definition before deploy: parse-check every
 * GROQ string (malformed predicates, conditions, bindings, triggers) and
 * re-run the cross-field invariants. `defineWorkflow` already
 * ran the invariants at authoring time, but deploy must reject what authoring
 * rejects — a stored-shape definition handed straight to the verb (raw JSON,
 * a foreign tool) would otherwise bypass every invariant.
 *
 * Plain condition sites come from {@link conditionSitesOf} — the same walker
 * the insight surface renders from — so a condition the runtime will parse
 * cannot escape the deploy check. Editability is checked at its AUTHORED
 * sites: an entry's `editable` string alongside its other attributes (with
 * `initialValue.query`), a stage tighten-override at its walker site. The
 * walker's `editable-field` sites carry the derived per-stage EFFECTIVE
 * predicate instead — a composition of those authored parts, parseable
 * whenever they are — so they are the one site kind this check skips. GROQ
 * strings that are not condition sites (effect bindings, op `where`s,
 * subworkflow reads, guard reads) keep their own checks below.
 *
 * Throws an `Error` with all problems aggregated. Reserved params don't need
 * to be declared here — groq-js's parser doesn't know about runtime params,
 * just syntax.
 */
export declare function validateDefinition(
  definition: WorkflowDefinition,
): void;

export declare function validateTag(tag: string): void;

export declare interface ValidationIssue {
  path: ReadonlyArray<PropertyKey>;
  message: 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.
 */
export 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>;
    };

/**
 * The guards allowed to influence this instance's verdicts, read from the
 * engine's own datasource only. A guard applies solely within the datasource
 * it physically lives in, and `resourceType`/`resourceId` are plain document
 * fields any writer in that datasource can set — so a verdict load must be
 * physically scoped: a guard doc in a watched content dataset that
 * self-declares the engine's resource id must never reach a verdict. This
 * keeps the advisory layer consistent (verdicts are UX, not enforcement);
 * it is not itself a security boundary. Reads through the same filter
 * definition the reactive adapters subscribe with
 * ({@link instanceGuardQuery}, the one-id form of the set-shaped
 * {@link instancesGuardQuery}), so the stateless and reactive paths agree.
 */
export declare function verdictGuardsForInstance(
  client: WorkflowClient,
  instanceId: string,
): Promise<MutationGuardDoc[]>;

export declare interface VerifyDeployedDefinitionsResult {
  /** Definitions seen, ordered by `name` asc, `version` asc. */
  definitions: {
    name: string;
    version: number;
    _id: string;
  }[];
  /** Effect names referenced by any deployed definition without a
   *  registered handler — one entry per (name, definitionId) tuple. */
  missing: {
    name: string;
    definitionId: string;
    locations: string[];
  }[];
}

/** The default clock: real wall-clock time as an ISO-8601 string. */
export declare const wallClock: Clock;

/**
 * The reactive subscription target for an instance: the exploded,
 * deduped watch-set plus the instance's read {@link WorkflowPerspective}.
 */
export declare interface WatchSet {
  /**
   * Docs to subscribe to — instance + ancestors + the docs named by
   * `doc.ref`/`subject`/`doc.refs`/`release.ref` field entries — deduped by
   * `globalDocumentId`. Refs that aren't resource-qualified GDR URIs are
   * skipped (without a resource there's nothing to subscribe against).
   */
  documents: SubscriptionDocument[];
  /**
   * The instance's effective read perspective (a release stack like
   * `[releaseName]` or `[releaseName, "drafts"]`), already resolved at
   * `startInstance`. `undefined` means content reads use the
   * drafts-preferring {@link DEFAULT_CONTENT_PERSPECTIVE}.
   *
   * The engine does not form `versions.<release>.<id>` ids — it has no
   * such concept (it reads content through `client.fetch({perspective})`
   * for queries). A reactive consumer applies this perspective when it
   * subscribes: a **content** doc resolves under the release
   * {@link contentReleaseName} names (e.g. Studio `editState`'s version
   * param, or the SDK's `getVersionId`), falling back to the draft only
   * when {@link contentDraftFallback} allows it, then published — while
   * instance / ancestor / `system.release` docs are always raw. The `type`
   * on each {@link SubscriptionDocument} tells the consumer which is which.
   */
  perspective?: WorkflowPerspective;
}

export { whatIfCondition };

export { WhatIfOutcome };

export { withAssignment };

export declare const workflow: {
  /**
   * Deploys immutable definition versions. The engine assigns each version:
   * content matching the latest deployed fingerprint returns `unchanged`;
   * otherwise deployment creates the next version and returns `created`.
   * Redeploying older content creates a new version; existing versions and
   * their pinned instances are unchanged.
   *
   * Children deploy before parents. References may resolve within the batch
   * or to deployed definitions; unresolved references and cycles reject the
   * batch before any write.
   *
   * Accepts authored content or a fetched definition document. The document
   * envelope (`_*` system fields, `tag`, `version`, `contentHash`) is excluded
   * from the fingerprint. Fetched content follows the same latest-version
   * comparison; any other unknown input key is rejected.
   */
  deployDefinitions: <T extends WorkflowDefinitionInput<T>>(
    rawArgs: Telemetered<DeployDefinitionsArgs<T> & EngineScopeArgs>,
  ) => Promise<DeployDefinitionsResult>;
  /**
   * Remove a deployed definition (all versions, or one via `version`). Refuses
   * while non-terminal instances exist unless `cascade` aborts them first —
   * instances are never deleted, only aborted in place. The operation also
   * checks spawn referrers and cleans up guard documents.
   */
  deleteDefinition: (
    rawArgs: Clocked<Telemetered<DeleteDefinitionArgs & EngineScopeArgs>>,
  ) => Promise<DeleteDefinitionResult>;
  /**
   * Spawn a new instance from a deployed definition: pins the snapshot, seeds
   * the `context` bag, enters the initial stage with every in-scope activity
   * born active, then cascades until stable. The gates run before anything is
   * written — supplied rows must be structurally consumable, required inputs
   * must be present, then every declared start requirement is evaluated in
   * author order and all unmet nodes are reported by one
   * {@link StartNotAllowedError} (no override arg; pre-flight with
   * `evaluateStart`). `start.filter` is NOT evaluated here — that is a
   * read-side visibility rule, see `definitionsForDocument`.
   *
   * Start is three commits — create, prime, first cascade — and a supplied
   * `instanceId` is the idempotency key across them: reusing it for the SAME
   * start RESUMES (input gates and field resolution are skipped, those values
   * were pinned at create), while reusing it for a DIFFERENT start, or for an
   * unfinished start that was aborted, throws
   * {@link ContractViolationError}. `changed` is `true` on a fresh start and
   * rev-derived on a resume; `cascaded` reports how far the instance
   * auto-advanced.
   */
  startInstance: (
    rawArgs: Clocked<Telemetered<StartInstanceArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Fire an action against an active activity, then cascade and propagate to
   * ancestors once it commits. The universal "something happened" call —
   * editors fire it, and runtimes fire it in response to webhooks, effect
   * completions, and timer firings; external signals never bypass it. A
   * cascade-fired (`when`) action is rejected: the cascade is its only firing
   * path.
   */
  fireAction: (
    rawArgs: Clocked<Telemetered<FireActionArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Edit a declared-editable field directly — reassign, reschedule,
   * claim-by-hand, append to a running log — through the generic edit seam
   * instead of a bespoke action per field. Soft-gates on the field's declared
   * editability (the same projection a UI renders), applies the edit as a
   * `field.*` op so provenance and history are stamped by the op path,
   * refreshes the stage's guards, then cascades — an edit to a value a
   * transition reads can and should move the instance. Advisory like every
   * engine gate.
   *
   * Each call is a discrete COMMIT (a history entry, a guard refresh, a
   * cascade, an `ifRevisionId` write), not a draft patch — so an inline-field
   * UI must bind it to a deliberate boundary (blur, Enter, Save, debounce),
   * never an `onChange` per keystroke.
   */
  editField: (
    rawArgs: Clocked<Telemetered<EditFieldArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Report a queued effect's outcome. Drains it from `pendingEffects` and
   * appends an `effectHistory` entry whose `outputs` are what downstream
   * bindings and conditions read as `$effects['<name>'].<output>` — the
   * start-only `context` bag is never touched. Any `ops` the handler returned
   * (`field.*`) are validated and applied in the same commit, through the op
   * applier an action's field ops use. Cascades after. A completion that
   * applies always changes state, so `changed` is `true`; a bad
   * `effectKey`/status throws instead, and a keyed retry of an
   * already-applied completion replays as `changed: false`.
   *
   * Completion is first-writer-wins — see {@link CompleteEffectArgs}. A
   * completer reporting over a retrying transport (webhook redelivery, queue,
   * cron) should pass `idempotencyKey`.
   */
  completeEffect: (
    rawArgs: Clocked<Telemetered<CompleteEffectArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Commit mid-dispatch field state from a running effect handler — the engine
   * verb behind `ctx.commitOps`. Gates on the dispatch's exact claim (token
   * match plus unexpired lease; a stale report throws `StaleEffectClaimError`
   * and writes nothing), validates and applies the `field.*` ops through the
   * shared op applier, records history and the mandatory idempotency key,
   * renews the claim's lease in the same compare-and-swap commit, refreshes
   * the stage's guards, then cascades — a report that satisfies a transition
   * moves the instance, by design.
   *
   * `completeEffect` remains the authoritative final result and stays
   * claim-blind; this verb only protects the mid-dispatch write channel from
   * superseded handlers.
   */
  commitEffectOps: (
    rawArgs: Clocked<Telemetered<CommitEffectOpsArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Run the cascade until stable — triggered actions fire, transitions move.
   * For a runtime reacting to any event that might affect the workflow but
   * isn't itself an action fire: a subject doc was patched, a sibling workflow
   * completed, the clock crossed a deadline a `when` reads. The caller doesn't
   * need to know what changed — it nudges the affected instance and the engine
   * re-evaluates. `changed` reports whether the nudge wrote anything, derived
   * from the instance's `_rev` rather than `cascaded` alone, since a hop can
   * fire triggered actions without unlocking a transition.
   */
  tick: (
    rawArgs: Clocked<Telemetered<OperationArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Admin override — force the instance into `targetStage` regardless of
   * filters or declared transitions. ACL gating is enforced upstream by the
   * caller; this verb performs no permission pre-flight, only the mechanical
   * move. `changed: false` means the move was a no-op (already at the target,
   * or terminal).
   */
  setStage: (
    rawArgs: Clocked<Telemetered<SetStageArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Admin override — hard-stop an in-flight instance where it stands. No stage
   * move, no transition effects, pending effects cancelled. The abort
   * propagates through affected ancestor instances.
   * Propagated, not cascaded — the instance is terminal, so `cascaded` is
   * always `0` and ancestor movement is reported on the ancestors, not here.
   * `changed: false` means the instance was already terminal.
   */
  abortInstance: (
    rawArgs: Clocked<Telemetered<AbortInstanceArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /**
   * Admin override — reset a failed (or otherwise terminal) activity in the
   * instance's current stage. `to: 'active'` (the default) re-runs it;
   * `to: 'skipped'` is the bypass that resolves it so a `$allActivitiesDone`-gated
   * exit can fire. Cascades after the reset, so an unblocked transition fires
   * in the same call. ACL gating is enforced upstream by the caller; this verb
   * performs no permission pre-flight. `changed: false` means the reset was a
   * no-op (instance terminal, or the activity already at the target status).
   */
  resetActivity: (
    rawArgs: Clocked<Telemetered<ResetActivityArgs & EngineScopeArgs>>,
  ) => Promise<OperationResult>;
  /** Fetch a workflow instance by id, scoped to the engine's tag. Throws when
   *  the instance doesn't exist or isn't visible to this engine. */
  getInstance: (
    rawArgs: InstanceRefArgs & EngineScopeArgs,
  ) => Promise<WorkflowInstance>;
  guardsForInstance: (
    rawArgs: InstanceRefArgs & EngineScopeArgs,
  ) => Promise<MutationGuardDoc[]>;
  guardsForDefinition: (
    rawArgs: GuardsForDefinitionArgs & EngineScopeArgs,
  ) => Promise<MutationGuardDoc[]>;
  /**
   * Run a caller-supplied GROQ query with the engine's tag bound as `$tag`.
   * This does NOT rewrite the query — arbitrary GROQ can't be safely
   * tag-scoped after the fact — so the CALLER MUST filter on `$tag` (e.g.
   * `tag == $tag`). To guard against accidental cross-partition reads, a query
   * that never references `$tag` is rejected before it reaches the lake. The
   * caller is responsible for type-narrowing the result.
   */
  query: <T = unknown>(rawArgs: QueryArgs & EngineScopeArgs) => Promise<T>;
  /**
   * Snapshot-aware GROQ — runs against the same in-memory view that filters
   * see for a given instance. Hydrates the instance's snapshot (instance +
   * ancestors + every doc declared by a `doc.ref` / `subject` / `doc.refs`
   * entry in scope), then evaluates the supplied GROQ in groq-js against that
   * dataset. The caller-free rendered scope cascade gates evaluate in is
   * auto-bound — the instance-derived vars with the open stage's overlay
   * merged into `$fields`, `$assigned` at its caller-free `false`, plus the
   * author's pre-evaluated `$<predicate>` booleans — with ids in GDR URI form
   * to match the snapshot's keying. Pure read; never writes.
   */
  queryInScope: <T = unknown>(
    rawArgs: Clocked<QueryInScopeArgs & EngineScopeArgs>,
  ) => Promise<T>;
  /** Every pending effect on the instance — the same entries the runtime would
   *  see, claimed and unclaimed alike. */
  listPendingEffects: (
    rawArgs: InstanceRefArgs & EngineScopeArgs,
  ) => Promise<PendingEffect[]>;
  /** Filter the instance's pending effects: `claimed` on claim presence,
   *  `names` on specific effect names. Both filters compose (AND). */
  findPendingEffects: (
    rawArgs: FindPendingEffectsArgs & EngineScopeArgs,
  ) => Promise<PendingEffect[]>;
  /**
   * Project the instance from a given actor's perspective — a
   * {@link WorkflowEvaluation} with per-action verdicts (`allowed` plus a
   * structured `disabledReason`). Used by UIs to render
   * disabled-with-reason buttons and by `fireAction` to gate writes through
   * the same logic. Pure read; never writes.
   */
  evaluate: (
    rawArgs: Clocked<EvaluateArgs & EngineScopeArgs>,
  ) => Promise<WorkflowEvaluation>;
  /**
   * Diagnose why an instance is or isn't progressing. Projects the instance
   * (the same read as `evaluate`) and classifies it — terminal,
   * `progressing`, `waiting` (an action is available, so healthy), or `stuck`
   * with a structured cause — returning that verdict as a
   * {@link DiagnoseResult} alongside the evaluation it came from, so a
   * consumer can render the supporting evidence without a second projection.
   * Pure read.
   */
  diagnose: (
    rawArgs: Clocked<EvaluateArgs & EngineScopeArgs>,
  ) => Promise<DiagnoseResult>;
  /** The actions an actor could fire on the instance's current stage, each
   *  flagged `allowed` with a structured `disabledReason` when not, returned
   *  with the evaluation they were projected from. Pure read. */
  availableActions: (
    rawArgs: Clocked<EvaluateArgs & EngineScopeArgs>,
  ) => Promise<AvailableActionsResult>;
  /**
   * Materialised spawned children of a parent instance. Walks `history` for
   * `spawned` events — the durable record, and still the one place adoption
   * and orphan events sit alongside spawns — strips each `instanceRef`'s GDR
   * URI to a bare `_id`, fetches the instances, drops any not visible to this
   * engine's tag, and returns them sorted by `startedAt` ascending. Pass
   * `activity` to restrict to a single spawning activity on the parent.
   */
  children: (
    rawArgs: ChildrenArgs & EngineScopeArgs,
  ) => Promise<WorkflowInstance[]>;
  /**
   * Every in-flight instance whose reactive watch-set includes `document` —
   * the reverse of an instance's subscription document set. For a
   * content-change-driven runtime holding no instances in memory: a document
   * changed, which instances should it `tick`? The watch-set covers the
   * instance itself, its ancestors, live spawned children, and the docs named
   * by `doc.ref` / `subject` / `doc.refs` / `release.ref` entries on the
   * workflow scope AND the current stage, so a hand-rolled GROQ over `fields[]`
   * gets it subtly wrong. The GROQ filter narrows candidates server-side and
   * {@link instanceWatchesDocument} rechecks each result, keeping the reverse
   * in lockstep with the forward set.
   *
   * `document` must be a resource-qualified GDR URI; a bare id is rejected,
   * since it can't be resource-routed and would silently mismatch — an
   * instance watching `dataset:A:ds:doc` is never matched by a change to
   * `dataset:B:ds:doc`. Sorted by `startedAt` ascending.
   */
  instancesForDocument: (
    rawArgs: InstancesForDocumentArgs & EngineScopeArgs,
  ) => Promise<WorkflowInstance[]>;
  /**
   * The startable half of {@link workflow.instancesForDocument}: every
   * deployed definition that APPLIES to `document` — what a start picker for
   * it should offer. Loads the latest deployed version of each definition
   * visible to the engine's tag and filters it through
   * {@link applicableDefinitions}: startable ∧ the `subject`-kind entry
   * accepts the doc's `_type` ∧ `start.filter` passes, evaluated in the
   * browse-time-pure start-filter context. Start requirements never
   * participate — readiness is a start-time question; pre-flight it with
   * {@link workflow.evaluateStart}.
   *
   * Takes the LOADED candidate document, not a ref — applicability evaluates
   * its content under whatever perspective the caller read it with. Surfaces
   * ALL matches (name ascending) with no engine ranking: presenting a picker
   * or auto-picking is consumer policy. Advisory like every engine-side check.
   */
  definitionsForDocument: (
    rawArgs: Clocked<DefinitionsForDocumentArgs & EngineScopeArgs>,
  ) => Promise<DeployedDefinition[]>;
  /**
   * Pre-flight the start gates for a definition plus candidate
   * `initialFields` — the read `startInstance` enforces, as a
   * {@link StartEvaluation} a surface can render: `missingRequired` mirrors
   * the input contract, while `requirements` preserves every declared node's
   * authored descriptor, outcome, and GROQ insight where applicable;
   * `allowed` / `outcome` aggregate those ordered results.
   *
   * BINDABILITY-AWARE for partial mid-form inputs: when a predicate reads an
   * entry `initialFields` doesn't supply — including a `singleSubject` node's
   * implicit subject read — `outcome` is `'unevaluable'` and `unboundReads`
   * names the entries ("fill these to decide") instead of the collapsed answer
   * GROQ equality would give. That is the ONE deliberate divergence from the
   * gate, where absence is final rather than provisional. A definition
   * declaring no start requirements is vacuously allowed, exactly like the
   * verb. Pure read; advisory under races — the enforcement moment is
   * `startInstance` itself.
   */
  evaluateStart: (
    rawArgs: Clocked<EvaluateStartArgs & EngineScopeArgs>,
  ) => Promise<StartEvaluation>;
  /** Permission helpers — Sanity ACL grants evaluated against documents via
   *  GROQ, used by `workflow.evaluate` to soft-gate actions when the caller
   *  supplies grants. Deliberately namespace-only, not mirrored on `Engine`:
   *  pure helpers that need none of the engine's pinned scope. */
  permissions: {
    matchesFilter: typeof matchesFilter;
    grantsPermissionOn: typeof grantsPermissionOn;
    fetchGrants: typeof fetchGrants;
  };
};

/**
 * The lake document type for a deployed workflow definition. Engine-owned
 * standalone documents carry the platform namespace; in-array discriminators
 * stay bare. Mirrors {@link WORKFLOW_INSTANCE_TYPE}.
 */
export declare const WORKFLOW_DEFINITION_TYPE = "sanity.workflow.definition";

/**
 * The lake document type for a workflow instance. Single source of truth — the
 * {@link WorkflowInstance} `_type`, every tag-scoped query, and the create
 * write all derive from here, mirroring {@link WORKFLOW_DEFINITION_TYPE}.
 * Engine-owned standalone documents use the platform namespace.
 */
export declare const WORKFLOW_INSTANCE_TYPE = "sanity.workflow.instance";

/**
 * The engine's view of "who am I, what can I do?". `actor` is who
 * the engine stamps onto history / `completedBy` / `ValueExpr.actor` —
 * token-resolved advisory provenance (see {@link Actor}). `grants`
 * (when present) feed the advisory `$can.*` params action conditions
 * can read; there is no engine-side permission verdict. When grants are
 * absent the rendered `$can` is undefined — conditions referencing it
 * fail closed, everything else is ungated engine-side — and the real
 * Sanity write boundary takes over. See {@link WorkflowAccess.attributes}
 * for the parallel `$attributes` bag.
 */
export declare interface WorkflowAccess {
  actor: Actor;
  /**
   * The actor's principal id in the workflow resource's OWN identity
   * namespace — what that resource's lake `identity()` returns for the same
   * token (the per-project user id for dataset resources; equal to
   * {@link Actor.id} for org-level resources and robots). In-memory only,
   * never persisted: it exists for the lake-facing edge — binding
   * `identity()` in guard previews and grant-filter evaluation so the
   * advisory verdicts agree with what the lake itself would decide.
   */
  localPrincipalId?: string;
  grants?: Grant[];
  /**
   * Optional bag for callers that compose a {@link WorkflowAccess} by hand
   * (the test bench). {@link resolveAccess} never populates this — soft-gate
   * paths load attributes via {@link resolveUserAttributes}.
   */
  attributes?: UserAttributes;
}

export declare const WorkflowActionFired: WorkflowTelemetryEvent<WorkflowActionFiredData>;

export declare interface WorkflowActionFiredData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** Effective kind of the activity the action fired on. */
  activityKind?: ActivityKind;
  hasParams: boolean;
  /** Auto-transitions fired during the post-action cascade. */
  cascaded: number;
}

export declare const WorkflowActivityReset: WorkflowTelemetryEvent<WorkflowAdminOverrideData>;

/** Outcome flag for the admin-override events — the attempt emits either way. */
export declare interface WorkflowAdminOverrideData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** `false` = the override was a no-op (already at the target / already terminal). */
  changed: boolean;
}

/** The whole-definition rollup: every stage must progress, so the workflow
 *  verdict conjoins the stage verdicts. */
export declare interface WorkflowAutonomy extends AutonomyAnswer {
  stages: StageAutonomy[];
}

export declare interface WorkflowClient {
  /** Build a resource-bound data URL, as on SanityClient. Used to confirm document availability. */
  getDataUrl?: (operation: string, path?: string) => string;
  /**
   * Read the effective client configuration. The engine uses `apiHost` for
   * account-global identity routing and `projectId` for project directory and
   * organization lookups. Without `projectId`, organization attributes cannot
   * be loaded and project-scoped principals cannot use the directory bridge.
   *
   * For clients without {@link WorkflowClient.withConfig}, an omitted
   * `apiVersion` means the implementation must already serve
   * {@link ENGINE_API_VERSION}. A declared `apiVersion` other than that version
   * skips organization attributes with a warning.
   */
  config?: () => WorkflowClientConfigState;
  fetch: <T = unknown>(
    query: string,
    params?: Record<string, unknown>,
    options?: WorkflowFetchOptions,
  ) => Promise<T>;
  getDocument: <T = SanityDocument>(
    id: string,
    options?: {
      tag?: string;
    },
  ) => Promise<T | null | undefined>;
  patch: (documentId: string) => WorkflowPatch;
  /**
   * Create a brand-new document. Errors loud (HTTP 409 / mutation
   * error) if a document with the same `_id` already exists. The engine
   * uses this whenever it mints a new doc — instances on
   * `startInstance`, child instances on spawn, new definitions on first
   * deploy.
   *
   * The interface deliberately omits `createOrReplace`: for existing
   * docs the engine uses `patch().set(...).ifRevisionId(rev).commit()`,
   * which fails fast if the doc was deleted or concurrently modified
   * (createOrReplace's behaviour on a missing target is ambiguous and
   * its rev-less form silently clobbers). If a consumer truly needs
   * createOrReplace they can extend their own client type.
   */
  create: <
    T extends {
      _id: string;
      _type: string;
    },
  >(
    doc: T,
    options?: WorkflowCommitOptions,
  ) => Promise<T>;
  /**
   * Build a multi-document transaction. All operations succeed or fail
   * together. Used whenever the engine writes multiple documents that
   * are provably in the same workflow resource (spawn fan-out, deploy
   * batches, parent + child propagation that stays in one dataset).
   *
   * Shape matches `@sanity/client.transaction()` and the in-memory test
   * client. `patch()` accepts a `WorkflowPatch` handle built via
   * `client.patch(id).set(...).ifRevisionId(rev)` — pass the handle in
   * without calling `.commit()` on it.
   */
  transaction: () => WorkflowTransaction;
  /**
   * Optional — present on the real `@sanity/client` and on the test
   * fake (from `@sanity-labs/client-fake-for-test@0.2.0`+). Effect
   * handlers use it to dispatch Content Releases and version actions
   * (`sanity.action.release.publish`, `sanity.action.document.version.create`,
   * etc.) without depending on the broader client surface.
   *
   * Typed loosely so both the strict real-client `Action` union and
   * the test fake's discriminated shape satisfy the field entry. Callers
   * (effect handlers) pass the concrete action object literal.
   */
  action?: (
    action: any,
    options?: {
      tag?: string;
    },
  ) => Promise<any>;
  /**
   * Optional — present on the real `@sanity/client` and the in-memory test
   * fake. Returns a sibling client with the given config overrides,
   * inheriting everything else from the source (token, apiHost). The engine
   * derives three things from it:
   *
   * - **Cross-resource routing** (`resource` + the dataset pair): a sibling
   *   for a foreign GDR when `resourceClients` doesn't map it. A client
   *   without `withConfig` makes foreign GDRs a loud routing error rather
   *   than a silent read of the wrong resource.
   * - **API-version normalization** (`apiVersion`): every engine entry
   *   derives its working client with
   *   `withConfig({apiVersion: ENGINE_API_VERSION})`, so the caller's
   *   configured version never reaches engine traffic (the caller's own
   *   instance is untouched). A client without `withConfig` cannot be
   *   rebound and is used as-is — it must be built to serve
   *   {@link ENGINE_API_VERSION} already; older dated versions fail
   *   silently incomplete, not loud.
   * - **Effect request attribution** (`requestTagPrefix`): handlers receive a
   *   derived client whose untagged traffic carries the effect tag while the
   *   caller's own client remains untouched. A client without `withConfig`
   *   uses the structural request wrapper instead.
   *
   * Dataset resources carry the `{projectId, dataset}` pair alongside
   * `resource`: the real client routes by `resource` (it takes precedence in
   * URL building), while the test fake keys its dataset registry by the pair.
   * Known gap: the fake ignores `resource`, so it derives DATASET siblings
   * only — a canvas/media-library derivation on the fake aliases the current
   * store until the fake learns `resource` upstream.
   */
  withConfig?: (config: WorkflowClientConfig) => this;
  /**
   * Optional — present on the real `@sanity/client`. Without it, ACL grant
   * discovery uses its dry-run fallback, while a definition containing
   * role-constrained assignment fields fails loudly because the engine cannot
   * read the project membership directory required to validate assignees.
   *
   * Raw request transport. The engine passes the request target through
   * `url`; relative paths must resolve against the client's configured API
   * host, matching supported `SanityClient.request` implementations.
   */
  request?: <T>(opts: WorkflowRequestOptions) => Promise<T>;
}

/**
 * The config bag {@link WorkflowClient.withConfig} accepts — all optional: a
 * resource rebind (`resource`, plus the dataset pair for dataset targets), an
 * `apiVersion` rebind, a request-tag prefix, or any combination. Everything
 * omitted is inherited from the source client.
 */
export declare interface WorkflowClientConfig {
  resource?: WorkflowResource;
  projectId?: string;
  dataset?: string;
  /** Explicit API origin, mirroring `@sanity/client`'s `apiHost`. */
  apiHost?: string;
  apiVersion?: string;
  requestTagPrefix?: string;
  /**
   * Host selection, mirroring `@sanity/client`: `false` derives a sibling
   * addressing the global API host instead of the project host. The engine
   * uses this for exactly one read — resolving the acting token's
   * account-global identity from the global `/users/me`.
   */
  useProjectHostname?: boolean;
}

/** The engine reads only project and API metadata from this value. */
export declare interface WorkflowClientConfigState extends Omit<
  WorkflowClientConfig,
  "resource"
> {
  resource?: {
    type: string;
    id: string;
  };
}

export declare interface WorkflowCommitOptions {
  /**
   * When the mutation becomes visible to subsequent queries. The engine
   * reads its own writes back through GROQ (`fetch`) — a freshly-spawned
   * child listed by id, a just-deployed definition — so single-document
   * writes (`create`, `patch().commit()`) commit `'sync'`: the change is
   * query-visible before the call resolves and the next read can't miss it.
   * `@sanity/client` already defaults to `'sync'`, but the engine states it
   * rather than depend on a transport default a consumer's client config
   * could change underneath it. (Transactions ride that same default — see
   * {@link WorkflowTransaction.commit}.)
   */
  visibility?: WorkflowVisibility;
  /**
   * Request tag for request-log attribution — see
   * {@link WorkflowFetchOptions.tag}; not the workflow-domain deployment
   * tag. The engine stamps every write with an operation-scoped
   * `workflow.*` tag.
   */
  tag?: string;
}

/**
 * `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
 */
export 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}.
 */
export 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
 */
export declare type WorkflowDefinition = v.InferOutput<
  typeof WorkflowDefinitionSchema
>;

export declare const WorkflowDefinitionDeleted: WorkflowTelemetryEvent<WorkflowDefinitionDeletedData>;

export declare interface WorkflowDefinitionDeletedData extends ExecutionScopedEventData {
  /** Deployed versions removed by this delete. */
  deletedVersionCount: number;
  /** Non-terminal instances cascade-aborted before the delete. */
  cascadeAbortedCount: number;
  /** Orphaned guard docs removed (populated only when the last version goes). */
  deletedGuardCount: number;
}

export declare const WorkflowDefinitionDeployed: WorkflowTelemetryEvent<WorkflowDefinitionDeployedData>;

export declare interface WorkflowDefinitionDeployedData extends ExecutionScopedEventData {
  /** Content fingerprint of the deployed content. */
  contentHash: string;
  /** Whether this deploy minted a new version or matched the latest one.
   *  Unchanged redeploys emit too — the attempt is the adoption signal. */
  status: "created" | "unchanged";
  /** Groups every definition event minted by one `deployDefinitions` call —
   *  a random run id, never derived from names or resource coordinates, so
   *  deployment-level rollups are a group-by without carrying customer
   *  strings. Distinct from the workflow-domain deployment tag. */
  deployId: string;
  stageCount: number;
  activityCount: number;
  actionCount: number;
  transitionCount: number;
  /** Declared field entries across workflow, stage, and activity scopes. */
  fieldCount: number;
  /** Distinct effective activity kinds used, sorted. */
  activityKinds: ActivityKind[];
  /** Distinct declared field kinds across workflow, stage, and activity
   *  scopes, sorted. */
  fieldKinds: FieldKind[];
  guardCount: number;
  /** Effects declared across the definition's actions. */
  effectCount: number;
  /** Actions carrying a `spawn` block. */
  subworkflowCount: number;
  lifecycle: WorkflowLifecycle;
}

/**
 * What deploy/diff accept, conditioned on how the value is typed. The
 * `string extends keyof T` test matches ONLY index-signature types (`keyof`
 * of a literal is a finite key union that `string` never extends) — i.e. how
 * fetch results are typed (`Record<string, unknown>`), which pass through to
 * the runtime boundary parse. Everything precisely typed gets the exact
 * {@link WorkflowDefinition} contract with two accepted exceptions: the
 * document envelope (the closed system-key union, so a typed
 * {@link DeployedDefinition} passes castless) and the authoring-only root
 * `runtime` block, so a {@link DefinedWorkflow} passes castless too. Every
 * other unknown key is `never`, making a typo'd literal a compile error rather
 * than a silent collapse to the record arm.
 */
export declare type WorkflowDefinitionInput<T> = string extends keyof T
  ? Record<string, unknown>
  : WorkflowDefinition & {
      [K in Exclude<
        keyof T,
        keyof WorkflowDefinition | DocumentEnvelopeKey | AuthoringRuntimeKey
      >]?: never;
    };

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}. */
export 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'`.
 */
export declare type WorkflowDeploymentInput = Omit<
  WorkflowDeployment,
  "expectedMinReaderModel"
> & {
  expectedMinReaderModel: number;
};

export declare const WorkflowEffectCompleted: WorkflowTelemetryEvent<WorkflowEffectCompletedData>;

export declare interface WorkflowEffectCompletedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** The effect's author-chosen name, unique per definition. */
  effect: EffectName;
  /** The recorded outcome of the effect — `cancelled` when an abort
   *  discarded it rather than a completer reporting. */
  status: EffectRunStatus;
  /** Which declaration boundary queued the effect. */
  origin: EffectOriginKind;
  /** Auto-transitions fired during the post-completion cascade — always 0
   *  for a cancellation (the instance is terminal). */
  cascaded: number;
}

export declare const WorkflowEffectsDrained: WorkflowTelemetryEvent<WorkflowEffectsDrainedData>;

export declare interface WorkflowEffectsDrainedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** Pending effects dispatched to a registered handler in this drain —
   *  0 for an empty poll (the pass itself is the signal). */
  drainedCount: number;
  /** The dispatched effects' author-chosen names, in drain order. */
  drainedEffects: EffectName[];
}

export declare const WorkflowEffectStateReported: WorkflowTelemetryEvent<WorkflowEffectStateReportedData>;

export declare interface WorkflowEffectStateReportedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** The reporting effect's author-chosen name. */
  effect: EffectName;
  /** Auto-transitions fired during the post-report cascade — a report that
   *  satisfies a transition moves the instance. */
  cascaded: number;
}

/**
 * Base class of the engine's structured errors. `kind` is the stable
 * discriminant — render on it; `name` mirrors the concrete class for logs.
 * Each subclass pins its literal via the `K` parameter, so passing a
 * mismatched kind to `super` is a compile error. Advisory like every engine
 * check: catching one of these explains a refusal, it does not enforce
 * anything.
 */
export declare abstract class WorkflowError<
  K extends WorkflowErrorKind = WorkflowErrorKind,
> extends Error {
  readonly kind: K;
  constructor(kind: K, message: string, options?: ErrorOptions);
}

export declare type WorkflowErrorKind =
  | "action-disabled"
  | "start-not-allowed"
  | "edit-field-denied"
  | "mutation-guard-denied"
  | "action-params-invalid"
  | "effect-ops-invalid"
  | "effect-outputs-invalid"
  | "required-field-not-provided"
  | "initial-fields-invalid"
  | "workflow-state-diverged"
  | "partial-guard-deploy"
  | "start-not-primed"
  | "start-not-settled"
  | "concurrent-cascade"
  | "concurrent-fire-action"
  | "concurrent-edit-field"
  | "concurrent-complete-effect"
  | "concurrent-commit-effect-ops"
  | "stale-effect-claim"
  | "effect-commit-queue-overflow"
  | "cascade-limit"
  | "field-value-shape"
  | "ref-resource-undeclared"
  | "model-version-ahead"
  | "reader-model-acknowledgement"
  | "persisted-doc-shape"
  | "instance-not-found"
  | "definition-not-found"
  | "definition-in-use"
  | "spawn-contracts-invalid"
  | "effect-not-found"
  | "missing-effect-handler"
  | "contract-violation";

export declare interface WorkflowEvaluation {
  instance: WorkflowInstance;
  definition: WorkflowDefinition;
  /** Missing targets of populated subject, doc.ref, and doc.refs fields in active
   * scopes. Clears on resolution; empty fields and exited-stage fields are excluded.
   * Required reference declarations and runtime conditions determine whether absence blocks progress. */
  missingDocuments?: MissingDocument[];
  /**
   * Missing required reference targets, or references read by unmet runtime requirements or transition conditions,
   * including named predicates in their evaluated scope. Empty when missing references
   * are optional for current progress. Omitted when no references are missing.
   */
  blockingMissingDocuments?: MissingDocument[];
  /** The workflow's advisory meaning, unchanged from its definition. */
  semantics?: Semantic[] | undefined;
  actor: Actor;
  currentStage: StageEvaluation;
  /** Active activities whose singular or plural assignment entry matches the actor. */
  pendingOnYou: ActivityEvaluation[];
  /** True if at least one action on any active activity is allowed. */
  canInteract: boolean;
  /**
   * Declared-editable fields in the current scope (workflow + current stage +
   * its activities), each with this actor's edit verdict and the current value's
   * provenance. The reactive edit-seam surface; empty when the workflow
   * declares no editable fields.
   */
  editableFields: EditableFieldEvaluation[];
  /**
   * Per-field derived state across every condition site in the current stage:
   * which gates read each field (involvement) and the counterfactually
   * verified consequences of the values that would unblock blocking atoms.
   * Empty when no condition reads a field.
   */
  fieldInsights: FieldInsight[];
  /**
   * The whole definition's causal-autonomy rollup: per activity, per stage,
   * and workflow-wide — will each level resolve without a caller, and what
   * does it wait on. Static (no instance state), stamped here so every
   * consumer reads one derivation. Spawn children are not resolved at
   * evaluation time, so their legs report `conditional`.
   */
  autonomy: WorkflowAutonomy;
  /**
   * The earliest future ISO 8601 instant the engine can derive for a time-based
   * change to this evaluation. Re-evaluate then. Includes a gate reading `$now`
   * beside `$actor`, `$assigned`, `$can`, or `$attributes`, evaluated in this
   * actor's scopes. Derived per call, never persisted.
   *
   * Absent on a terminal instance or when the engine cannot derive a boundary.
   * Conditions using date arithmetic may yield no boundary. Time can still
   * affect a nonterminal instance when this value is absent.
   */
  nextEvaluationAt?: string;
}

export declare interface WorkflowFetchOptions {
  /**
   * Override the client's configured perspective for this read. The
   * engine uses this to scope field-entry query and spawn forEach
   * reads to the instance's `perspective` field.
   */
  perspective?: WorkflowPerspective;
  /**
   * Request tag for request-log attribution (`?tag=` — combined with any
   * client-configured `requestTagPrefix` as `prefix.tag`). Unrelated to
   * the workflow-domain deployment tag ({@link validateTag}'s `$tag`
   * partition): same word, disjoint concepts. The engine stamps every
   * read with an operation-scoped `workflow.*` tag.
   */
  tag?: string;
}

export declare const WorkflowFieldEdited: WorkflowTelemetryEvent<WorkflowFieldEditedData>;

export declare interface WorkflowFieldEditedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** Declared kind of the edited field entry. */
  fieldKind?: FieldKind;
  mode: EditMode;
}

/** @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;
};

export declare interface WorkflowInstance extends SanityDocument {
  _type: typeof WORKFLOW_INSTANCE_TYPE;
  /**
   * Engine data-model stamp — the shape contract this document conforms to
   * (see {@link DATA_MODEL_VERSION}), orthogonal to the definition-content
   * pins (`pinnedVersion` / `pinnedContentHash`). Stamped at create and
   * re-asserted on every full persist; absent on documents last written
   * before the stamp existed (model 0).
   */
  modelVersion?: number;
  /**
   * Reader floor — the oldest engine data model that can safely interpret
   * this document. Derived from its persisted features and the retained
   * model-4 baseline, and written alongside
   * {@link WorkflowInstance.modelVersion}. Full persists never lower it.
   */
  minReaderModel?: number;
  /**
   * Engine-scope environment partition stamped on the instance at create
   * time. Reads are scoped to a single tag, so an engine only sees
   * instances whose `tag` equals its own.
   */
  tag: string;
  /**
   * The Sanity resource this instance lives in. Stored on the doc so
   * any internal operation can mint GDRs for ancestors / spawned
   * children / etc. without re-supplying it. Mirrors
   * `@sanity/client`'s `ClientConfigResource`.
   */
  workflowResource: WorkflowResource;
  /** Reference to the deployed definition, by its `name`. */
  definition: string;
  pinnedVersion: number;
  /**
   * Content fingerprint of the pinned definition version (see
   * {@link hashDefinitionContent}). Pinned alongside the version so a consumer
   * can detect a deployed definition that drifted from what this instance
   * started on. Advisory — the engine enforces nothing; this enables detection,
   * not prevention. Absent when the instance was started against a definition
   * deployed before content-addressing (it had no hash to pin).
   */
  pinnedContentHash?: string;
  /** Frozen JSON snapshot of the definition at the moment the instance started. */
  definitionSnapshot: string;
  /**
   * Resolved workflow fields, retained for the instance's lifetime. Their
   * initial values come from the definition's `fields` declarations and
   * {@link StartInstanceArgs.initialFields}.
   *
   * To declare the workflow's subject document, use
   * `{type: 'subject', name: 'subject', initialValue: {type: 'input'}}`.
   * Conditions read that entry as `$fields.subject`. The `subject` field
   * type identifies its role; naming a `doc.ref` field `subject` does not.
   */
  fields: ResolvedFieldEntry[];
  /**
   * The start seed: named values set once at `startInstance` (or by a
   * parent's `spawn.context`) and never mutated after. Conditions and
   * effect bindings read them as `$context.<name>`.
   */
  context: ContextEntry[];
  /**
   * Chain of ancestor workflow instances, root-first. Each entry is a
   * GDR pointing at a {@link WORKFLOW_INSTANCE_TYPE} document in the
   * engine's own workflow resource.
   */
  ancestors: GlobalDocumentReference[];
  /**
   * Perspective for content reads, including field queries and subworkflow
   * discovery. Defaults to {@link DEFAULT_CONTENT_PERSPECTIVE}, where drafts
   * take precedence over published content. Set it through
   * {@link StartInstanceArgs.perspective}; child instances inherit it.
   *
   * Engine-owned instance and definition documents, and `system.release`
   * documents, always read under `raw`.
   */
  perspective?: WorkflowPerspective;
  currentStage: StageName;
  /**
   * Per-stage instance entries — one StageEntry per stage the instance
   * has been in, in entry order. Past stages persist with `exitedAt`
   * set; the current stage is the entry whose `exitedAt` is undefined.
   * Each entry owns its activities.
   */
  stages: StageEntry[];
  /**
   * Workflow-scope registry of every child this instance ever spawned;
   * see {@link SubworkflowEntry}. Rows are never deleted; a row without
   * `resolved` is a live child (watched, hydrated, propagating), one with
   * it is terminal, and a live row with `abortPending` is condemned — the
   * cascade owes it an abort. Rendered as the `$subworkflows` condition
   * var. Absent only on instances persisted before the registry existed.
   */
  subworkflows?: SubworkflowEntry[];
  pendingEffects: PendingEffect[];
  effectHistory: EffectHistoryEntry[];
  history: HistoryEntry[];
  /**
   * Idempotency ledger — see {@link ProcessedRequest}. Optional because
   * instances persisted before the ledger existed lack it (any commit
   * materialises it, empty). Only keyed operations add rows — it never
   * grows on instances whose callers pass no `idempotencyKey`.
   */
  processedRequests?: ProcessedRequest[];
  startedAt: string;
  lastChangedAt: string;
  completedAt?: string;
  /**
   * Set (to the same instant as `completedAt`) when the instance was
   * hard-stopped via `abortInstance` rather than reaching a terminal
   * stage. `completedAt` is always stamped alongside it so every
   * "in-flight" query (`!defined(completedAt)`) treats aborted and
   * completed instances uniformly; this field is what distinguishes them.
   */
  abortedAt?: string;
}

export declare const WorkflowInstanceAborted: WorkflowTelemetryEvent<WorkflowAdminOverrideData>;

/**
 * The instance list projection — a reduced {@link WorkflowInstance} for
 * surfaces that render many runs at once, fetched by `instancePreviewsQuery`.
 *
 * The reduction keeps the full instance's field names and member shapes so
 * instance helpers (`terminalState`, `findOpenStageEntry`, `parentRef`, the
 * identity normalizer) read a preview unchanged; what shrinks is the content:
 * `stages` holds the open entry alone, every `fields` list keeps only the
 * identity, date, document-reference, and release-reference kinds, and the unbounded audit
 * trails are gone — `claimedEffects` and `failedEffects` hold the two facts
 * a stuck classifier reads in their place. There is deliberately no
 * `definitionSnapshot`: a consumer titles what it shows from the deployed
 * catalog, falling back to raw names.
 */
export declare interface WorkflowInstancePreview {
  _id: string;
  _type: typeof WORKFLOW_INSTANCE_TYPE;
  /** See {@link WorkflowInstance.modelVersion}. */
  modelVersion?: number;
  /** See {@link WorkflowInstance.minReaderModel}. */
  minReaderModel?: number;
  workflowResource: WorkflowResource;
  definition: string;
  pinnedVersion: number;
  /** Identity, date, document-reference, and release-reference entries only
   *  — the kinds list surfaces read. Composite (`object`/`array`) entries are
   *  dropped, so identities nested inside them are invisible to a preview. */
  fields: ResolvedFieldEntry[];
  ancestors: GlobalDocumentReference[];
  perspective?: WorkflowPerspective;
  currentStage: StageName;
  /** The open stage entry alone, its activities' fields reduced like
   *  {@link fields}. A completed run keeps its terminal entry open, so this
   *  is empty only for an aborted run (whose entries closed in place) or
   *  before the run primes. */
  stages: StageEntry[];
  /** Pending effects a drainer has claimed — the hung-automation fact. */
  claimedEffects: WorkflowInstancePreviewEffect[];
  /** Effect-history rows that reported failure — the failed-automation fact. */
  failedEffects: WorkflowInstancePreviewEffect[];
  startedAt: string;
  completedAt?: string;
  abortedAt?: string;
}

/** A stalled automation as a preview reports it — the effect's machine name
 *  and its display title. */
export declare interface WorkflowInstancePreviewEffect {
  name: string;
  title?: string;
}

/** The instance list projection (`instancePreviewsQuery` results). The reduced
 *  members reuse the persisted document's own schemas, so a preview can
 *  never admit a shape the full parse would refuse. */
export declare const WorkflowInstancePreviewSchema: v.GenericSchema<WorkflowInstancePreview>;

/**
 * The persisted instance document, root to leaf. Reused verbatim by every
 * engine read boundary through {@link parseInstanceDocument}; the
 * model-surface gate derives its shape ledger from this schema.
 */
export declare const WorkflowInstanceSchema: v.GenericSchema<WorkflowInstance>;

export declare const WorkflowInstanceStarted: WorkflowTelemetryEvent<WorkflowInstanceStartedData>;

export declare interface WorkflowInstanceStartedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** Caller-supplied initial-field entries — `initialFields` for a direct
   *  start, the parent's projected `with` bindings for a spawned child. */
  initialFieldCount: number;
  /** Started by a parent's subworkflow spawn rather than a direct
   *  `startInstance` — automation vs. hands-on at instance creation. */
  viaSpawn: boolean;
  lifecycle: WorkflowLifecycle;
}

export declare const WorkflowInstanceTicked: WorkflowTelemetryEvent<WorkflowInstanceTickedData>;

export declare interface WorkflowInstanceTickedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** Auto-transitions fired during the cascade. */
  cascaded: number;
}

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

/**
 * The subset of `@sanity/client` the engine actually needs. The
 * `@sanity-labs/client-fake-for-test` TestClient is
 * structurally assignable to this, as is the real `@sanity/client`
 * SanityClient.
 */
export declare interface WorkflowMutationOptions {
  /**
   * Optimistic concurrency: only proceed if the target document's
   * current `_rev` matches. On mismatch the underlying client throws.
   * Pass the `_rev` loaded alongside the doc you're about to write back.
   */
  ifRevisionId?: string;
}

export declare interface WorkflowPatch {
  set: (props: Record<string, unknown>) => WorkflowPatch;
  setIfMissing: (props: Record<string, unknown>) => WorkflowPatch;
  unset: (paths: string[]) => WorkflowPatch;
  ifRevisionId: (rev: string) => WorkflowPatch;
  commit: (options?: WorkflowCommitOptions) => Promise<SanityDocument>;
}

/**
 * Perspective layering — see Sanity Content Lake docs. The engine
 * threads this into reads that should reflect a release-stacked view
 * of the dataset (field-entry query resolution, spawn forEach discovery).
 * Engine-internal reads of `workflow.instance` / `workflow.definition`
 * stay raw regardless — those docs are unversioned metadata.
 *
 * Either both the real `@sanity/client` and the fake test client
 * support the same shape. `string[]` is an ordered release-name stack;
 * `"drafts"` may appear in the array. `"published"` is the implicit
 * tail.
 */
export declare type WorkflowPerspective =
  | "raw"
  | "published"
  | "drafts"
  | string[];

export declare interface WorkflowRequestOptions {
  /** API-relative path resolved against the configured API host, or an absolute URL. */
  url: string;
  signal?: AbortSignal;
  /** Optional `?tag=` query for observability — supported by `@sanity/client`. */
  tag?: string;
}

/**
 * The resource a Sanity client is configured against — mirrors
 * `@sanity/client`'s `ClientConfigResource` discriminator. For
 * `dataset`, `id` is `<projectId>.<dataset>`. For the others, `id` is
 * the resource id.
 */
export declare type WorkflowResource =
  | {
      type: "dataset";
      id: string;
    }
  | {
      type: "canvas";
      id: string;
    }
  | {
      type: "media-library";
      id: string;
    }
  | {
      type: "dashboard";
      id: string;
    };

export declare const WorkflowStageSet: WorkflowTelemetryEvent<WorkflowAdminOverrideData>;

export declare const WorkflowStageTransitioned: WorkflowTelemetryEvent<WorkflowStageTransitionedData>;

export declare interface WorkflowStageTransitionedData
  extends ExecutionScopedEventData, InstanceScopedEventData {
  /** Positional index of the exited stage in the definition's `stages[]`
   *  order — indexes, never names, so the payload stays content-free. */
  fromStageIndex: number;
  /** Positional index of the entered stage in the definition's `stages[]` order. */
  toStageIndex: number;
  /** The entered stage is terminal (no transitions out) — reaching it
   *  completes the instance. */
  toIsTerminal: boolean;
  /** The entered stage was already visited on this instance — a loop-back. */
  isRevisit: boolean;
  /** Time spent in the exited stage (its entry's `enteredAt` to this exit,
   *  on the engine clock). Omitted when the exited entry is unavailable. */
  dwellMs?: number;
  /** Condition-driven transition vs. the setStage admin override. */
  via: "transition" | "setStage";
}

/**
 * Thrown when a guard deploy fails *after* its state move committed and the
 * engine could not cleanly undo the result — any of: the rollback write itself
 * failed; the move created sibling docs (spawn) that a parent-only rollback
 * cannot undo; or a multi-guard deploy partially applied, so even a clean state
 * rollback leaves the earlier guards orphaned ({@link PartialGuardDeployError}).
 * The workflow's persisted state and its deployed guards are now divergent and
 * need manual reconciliation; the engine screams rather than leaving the
 * inconsistency silent.
 */
export declare class WorkflowStateDivergedError extends WorkflowError<"workflow-state-diverged"> {
  readonly instanceId: string;
  /** The guard-deploy failure that triggered the (attempted) rollback. */
  readonly guardError: unknown;
  /** The rollback failure, when rollback was attempted and itself failed. */
  readonly rollbackError?: unknown;
  constructor(args: {
    instanceId: string;
    guardError: unknown;
    rollbackError?: unknown;
    reason: string;
  });
}

/**
 * A telemetry event descriptor — a structural mirror of `@sanity/telemetry`'s
 * `DefinedTelemetryLog`, so shells hand these straight to their store logger.
 */
export 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.
 */
export declare interface WorkflowTelemetryLogger {
  log<Data>(event: WorkflowTelemetryEvent<Data>, data: Data): void;
  log(event: WorkflowTelemetryEvent<void>): void;
}

export declare interface WorkflowTransaction {
  /**
   * Queue a `create` mutation. Fails the transaction on `_id` collision,
   * same as `client.create`.
   */
  create: <
    T extends {
      _id: string;
      _type: string;
    },
  >(
    doc: T,
  ) => WorkflowTransaction;
  /**
   * Queue a patch. Expected argument is a `WorkflowPatch` handle built
   * via `client.patch(id).set(…).ifRevisionId(rev)` — pass it without
   * calling `.commit()`.
   *
   * Typed `any` so the test-client's `TransactionHandle.patch(string |
   * PatchHandle, …)` and `@sanity/client`'s `Transaction.patch(Patch |
   * string, …)` both satisfy the field entry under `strictFunctionTypes`. The
   * engine call site always passes a `WorkflowPatch`; both underlying
   * clients drain it structurally.
   */
  patch: (patch: any) => WorkflowTransaction;
  /**
   * Queue a document delete. Deliberately a transaction-only capability —
   * the top-level client surface stays delete-free so no engine code path
   * can casually remove documents. Engine-side consumers are guard retraction
   * and `deleteDefinition` housekeeping; outside the engine the CLI's `nuke`
   * reset deletes raw engine-owned docs through it. Both the real
   * `@sanity/client` Transaction and the test fake's TransactionHandle carry
   * this shape.
   */
  delete: (id: string) => WorkflowTransaction;
  /**
   * Commit the batch. The options bag carries only the request tag
   * ({@link WorkflowFetchOptions.tag} — attribution, not the deployment
   * tag). Deliberately no `visibility`: a transaction rides the client's
   * *default* `visibility` — `'sync'` in `@sanity/client` (so a post-spawn
   * `listInstances` GROQ sees freshly-created children), immediate in the
   * in-memory test fake. This is a standing engine assumption — a consumer
   * that configured an `async` default would make spawn read-backs racy.
   * Single-document writes state `'sync'` explicitly via
   * {@link WorkflowCommitOptions}.
   */
  commit: (options?: { tag?: string }) => Promise<unknown>;
}

export declare type WorkflowVisibility = "sync" | "async" | "deferred";

export {};
