@sanity/workflow-engine 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { rethrowWithContext, andConditions, deriveActivityKind, WorkflowError, CALLER_BOUND_VARS, START_REQUIREMENT_VARS, CONDITION_VARS, isSubjectEntry, isUnevaluable, ContractViolationError, isStartableDefinition, conditionFieldReadNames, isGdr, errorMessage, conditionParameterNames, START_FILTER_VARS, gdrFromResource, selfGdr, isSingleDocRefKind, actorFulfillsRole, toBareId, sameResource, resourceFromParsed, tryParseGdr, isTerminalActivityStatus, FieldValueShapeError, validateFieldValue, validateFieldAppendItem, isAlwaysArrayFieldKind, evaluateCondition, isSingleDocRefEntry, choiceValueIssues, scalarValidationIssues, StoredFieldOpSchema, formatIssues, conditionSyntaxIssues, checkWorkflowInvariants, formatIssuePath, isGuardReadExpr, conditionEffectReads, EFFECTS_READ, datasetResourceParts, evaluatePredicates, WORKFLOW_DEFINITION_TYPE, tagScopeFilter, isCascadeFired, parseGdr, isGdrUri, gdrRef, isInputSourced, parseFieldValue, VersionSpecificDatasetGdrError, toPhysicalGdr, isBareSeedId, tolerantEntries, NonEmptyString, FIELD_VALUE_KINDS, tolerantObject, ActorShape, IsoTimestamp, ACTIVITY_STATUSES, GdrShape, DRIVER_KINDS, FIELD_SCOPES, fieldValueSchemas, parsePersistedDoc, ACTOR_KINDS, classifyPrincipalId, directoryBridgeId, InstanceNotFoundError, evaluateConditionOutcome, runGroq, FIELD_READ, MUTATION_GUARD_ACTIONS, resourceGdr, resourceFromGdrUri, refTypeIssues, rejectedRefTypes, DOCUMENT_VALUE_PERMISSIONS, lakePrincipalId, firstCarriedGlobalId, driverKind, EffectNotFoundError, deriveExecutorClassification, validateTag, extractDocumentId, parseStoredDefinition, validateResourceAliasName, labelFor, DefinitionNotFoundError, definitionDocId, SpawnContractsInvalidError, gdrResourcePrefix, RESOURCE_ALIAS_NAME_SOURCE, DefinitionInUseError, isParseableInstant, groupMembershipNames } from "./_chunks-es/invariants.js";
1
+ import { rethrowWithContext, andConditions, deriveActivityKind, CALLER_BOUND_VARS, START_REQUIREMENT_VARS, CONDITION_VARS, isSubjectEntry, isUnevaluable, ContractViolationError, isStartableDefinition, conditionFieldReadNames, isGdr, errorMessage, conditionParameterNames, START_FILTER_VARS, gdrFromResource, selfGdr, isSingleDocRefKind, actorFulfillsRole, toBareId, WorkflowError, sameResource, resourceFromParsed, tryParseGdr, isTerminalActivityStatus, FieldValueShapeError, validateFieldValue, validateFieldAppendItem, isAlwaysArrayFieldKind, evaluateCondition, isRecord, isSingleDocRefEntry, isAssignmentFieldEntry, choiceValueIssues, scalarValidationIssues, StoredFieldOpSchema, formatIssues, conditionSyntaxIssues, checkWorkflowInvariants, formatIssuePath, isGuardReadExpr, conditionEffectReads, EFFECTS_READ, datasetResourceParts, assignmentKindAcceptsRoles, evaluatePredicates, WORKFLOW_DEFINITION_TYPE, tagScopeFilter, isCascadeFired, classifyPrincipalId, directoryBridgeId, parseGdr, isGdrUri, gdrRef, isInputSourced, parseFieldValue, VersionSpecificDatasetGdrError, toPhysicalGdr, isBareSeedId, NonEmptyString, tolerantEntries, FIELD_VALUE_KINDS, tolerantObject, ActorShape, IsoTimestamp, ACTIVITY_STATUSES, GdrShape, DRIVER_KINDS, FIELD_SCOPES, fieldValueSchemas, parsePersistedDoc, ACTOR_KINDS, InstanceNotFoundError, evaluateConditionOutcome, runGroq, FIELD_READ, MUTATION_GUARD_ACTIONS, resourceGdr, resourceFromGdrUri, refTypeIssues, rejectedRefTypes, DOCUMENT_VALUE_PERMISSIONS, lakePrincipalId, firstCarriedGlobalId, driverKind, EffectNotFoundError, deriveExecutorClassification, validateTag, extractDocumentId, parseStoredDefinition, validateResourceAliasName, labelFor, DefinitionNotFoundError, definitionDocId, SpawnContractsInvalidError, gdrResourcePrefix, RESOURCE_ALIAS_NAME_SOURCE, DefinitionInUseError, isParseableInstant, groupMembershipNames } from "./_chunks-es/invariants.js";
2
2
 
3
3
  import { ACTION_SEMANTICS, ACTIVITY_KINDS, ANONYMOUS_IDENTITY, DECISION_SEMANTICS, DEFAULT_TRANSITION_WHEN, EXECUTOR_CLASSIFICATIONS, FILTER_SCOPE_VARS, GROUP_KINDS, GUARD_PREDICATE_VARS, PersistedDocShapeError, RESERVED_CONDITION_VARS, SIGNAL_SEMANTICS, SYSTEM_IDENTITY, clientConfigFromResource, gdrUri, isNotesEntry, isTodoListEntry, isTodoListItem, parseResourceGdr, readsRootDocument, refCanvas, refDashboard, refDataset, refKindAcceptsTypes, refMediaLibrary, releaseDocId, releaseRef, resourceAliasesToMap, schemaTreeShape, startKindOf } from "./_chunks-es/invariants.js";
4
4
 
@@ -130,6 +130,9 @@ function resolveFieldSite(site, stage) {
130
130
  ...site.entry.validation !== void 0 ? {
131
131
  validation: site.entry.validation
132
132
  } : {},
133
+ ...site.entry.roles !== void 0 ? {
134
+ roles: site.entry.roles
135
+ } : {},
133
136
  ref: {
134
137
  scope: site.scope,
135
138
  field: site.entry.name
@@ -266,58 +269,58 @@ function resolveTelemetry(telemetry) {
266
269
  }
267
270
 
268
271
  const HIGH_FREQUENCY_SAMPLE_MS = 6e4, WorkflowDefinitionDeployed = defineWorkflowEvent({
269
- name: "Editorial Workflows Definition Deployed",
272
+ name: "Workflows Definition Deployed",
270
273
  version: 1,
271
274
  description: "A definition went through a deploy — status distinguishes a newly minted version from an unchanged redeploy"
272
275
  }), WorkflowInstanceStarted = defineWorkflowEvent({
273
- name: "Editorial Workflows Instance Started",
276
+ name: "Workflows Instance Started",
274
277
  version: 1,
275
278
  description: "A workflow instance was started from a deployed definition"
276
279
  }), WorkflowStageTransitioned = defineWorkflowEvent({
277
- name: "Editorial Workflows Stage Transitioned",
280
+ name: "Workflows Stage Transitioned",
278
281
  version: 1,
279
282
  description: "A committed stage move — one event per hop, cascades included, whichever verb drove it. Unsampled: funnel and dwell reads need complete counts, and volume is bounded by actual movement"
280
283
  }), WorkflowActionFired = defineWorkflowEvent({
281
- name: "Editorial Workflows Action Fired",
284
+ name: "Workflows Action Fired",
282
285
  version: 1,
283
286
  description: "An action was fired against an activity"
284
287
  }), WorkflowFieldEdited = defineWorkflowEvent({
285
- name: "Editorial Workflows Field Edited",
288
+ name: "Workflows Field Edited",
286
289
  version: 1,
287
290
  description: "A declared-editable field was edited through the generic edit seam",
288
291
  maxSampleRate: HIGH_FREQUENCY_SAMPLE_MS
289
292
  }), WorkflowInstanceTicked = defineWorkflowEvent({
290
- name: "Editorial Workflows Instance Ticked",
293
+ name: "Workflows Instance Ticked",
291
294
  version: 1,
292
295
  description: "An instance was re-evaluated for auto-transitions and due waits",
293
296
  maxSampleRate: HIGH_FREQUENCY_SAMPLE_MS
294
297
  }), WorkflowEffectsDrained = defineWorkflowEvent({
295
- name: "Editorial Workflows Effects Drained",
298
+ name: "Workflows Effects Drained",
296
299
  version: 1,
297
300
  description: "A drain pass ran — drainedCount/drainedEffects report the successful dispatches. Unsampled when non-empty (outcome counts must be complete; volume is bounded by real effect work); empty polls are machine-cadence noise, throttled engine-side to at most one per minute"
298
301
  }), WorkflowEffectStateReported = defineWorkflowEvent({
299
- name: "Editorial Workflows Effect State Reported",
302
+ name: "Workflows Effect State Reported",
300
303
  version: 1,
301
304
  description: "A running effect handler committed mid-dispatch field state through commitEffectOps. Sampled (high-frequency by design — a dispatch may report many times): an adoption and usage signal, not an exact per-run report count",
302
305
  maxSampleRate: HIGH_FREQUENCY_SAMPLE_MS
303
306
  }), WorkflowEffectCompleted = defineWorkflowEvent({
304
- name: "Editorial Workflows Effect Completed",
307
+ name: "Workflows Effect Completed",
305
308
  version: 1,
306
- description: "An effect outcome was recorded — reported directly through completeEffect, or cancelled by the abort verb (external runtimes; engine-drained effects surface via Editorial Workflows Effects Drained instead — each outcome counts once)"
309
+ description: "An effect outcome was recorded — reported directly through completeEffect, or cancelled by the abort verb (external runtimes; engine-drained effects surface via Workflows Effects Drained instead — each outcome counts once)"
307
310
  }), WorkflowInstanceAborted = defineWorkflowEvent({
308
- name: "Editorial Workflows Instance Aborted",
311
+ name: "Workflows Instance Aborted",
309
312
  version: 1,
310
313
  description: "The abort admin override was invoked (changed: false = instance already terminal)"
311
314
  }), WorkflowStageSet = defineWorkflowEvent({
312
- name: "Editorial Workflows Stage Set",
315
+ name: "Workflows Stage Set",
313
316
  version: 1,
314
317
  description: "The set-stage admin override was invoked (changed: false = already at the target stage)"
315
318
  }), WorkflowActivityReset = defineWorkflowEvent({
316
- name: "Editorial Workflows Activity Reset",
319
+ name: "Workflows Activity Reset",
317
320
  version: 1,
318
321
  description: "The reset-activity admin override was invoked (changed: false = already at the target status, or the instance was terminal)"
319
322
  }), WorkflowDefinitionDeleted = defineWorkflowEvent({
320
- name: "Editorial Workflows Definition Deleted",
323
+ name: "Workflows Definition Deleted",
321
324
  version: 1,
322
325
  description: "A deployed definition (or one version of it) was removed via the admin verb"
323
326
  });
@@ -435,438 +438,131 @@ function fieldEditedData(args) {
435
438
  };
436
439
  }
437
440
 
438
- const DATA_MODEL_VERSION = 7, DATA_MODEL_MIN_READER = 4, READER_MODEL_ROLLOUT_URL = "https://www.sanity.io/docs/editorial-workflows/prerelease";
441
+ function effectSites(def) {
442
+ const sites = [];
443
+ for (const stage of def.stages ?? []) for (const activity of stage.activities ?? []) for (const action of activity.actions ?? []) for (const effect of action.effects ?? []) sites.push({
444
+ effect: effect,
445
+ location: `stage[${stage.name}].activity[${activity.name}].action[${action.name}].effects`
446
+ });
447
+ return sites;
448
+ }
439
449
 
440
- class ReaderModelAcknowledgementError extends WorkflowError {
441
- code="WORKFLOW_READER_MODEL_ACKNOWLEDGEMENT_MISMATCH";
442
- expectedMinReaderModel;
443
- engineMinReaderModel=DATA_MODEL_MIN_READER;
444
- engineModelVersion=DATA_MODEL_VERSION;
445
- documentationUrl=READER_MODEL_ROLLOUT_URL;
446
- constructor(expectedMinReaderModel, context = "Deployment") {
447
- const expected = expectedMinReaderModel === void 0 ? "missing" : String(expectedMinReaderModel);
448
- super("reader-model-acknowledgement", `${context} expected reader floor ${expected}; the installed engine requires acknowledgement ${DATA_MODEL_MIN_READER}.\nDo not change the acknowledgement yet: accepting ${DATA_MODEL_MIN_READER} authorizes this engine to write documents that older readers will refuse.\nUpgrade every Studio, CLI, MCP server, Function, and other runtime that reads engine-owned documents; verify that rollout in every environment sharing the workflow resource; then change the literal in deployment configuration and deploy the writer.\nRollout guide: ${READER_MODEL_ROLLOUT_URL}`),
449
- this.name = "ReaderModelAcknowledgementError", this.expectedMinReaderModel = expectedMinReaderModel;
450
- }
450
+ function findEffect(def, name) {
451
+ return effectSites(def).find(site => site.effect.name === name)?.effect;
451
452
  }
452
453
 
453
- function assertReaderModelAcknowledgement(expectedMinReaderModel, context) {
454
- if (typeof expectedMinReaderModel != "number" || !Number.isFinite(expectedMinReaderModel) || !Number.isInteger(expectedMinReaderModel) || expectedMinReaderModel < 0 || expectedMinReaderModel !== DATA_MODEL_MIN_READER) throw new ReaderModelAcknowledgementError(expectedMinReaderModel, context);
454
+ function rolesGateOf(atom) {
455
+ const node = atomNode(atom);
456
+ if (atom.negated || node.type !== "OpCall" || node.op !== ">" || node.right.type !== "Value" || node.right.value !== 0) return;
457
+ const count = node.left;
458
+ if (!(count.type !== "FuncCall" || count.name !== "count" || count.args.length !== 1)) return rolesFilterList(count.args[0]);
455
459
  }
456
460
 
457
- const DATA_MODEL_CHANGES = Object.freeze([ Object.freeze({
458
- id: "governed-model-stamps",
459
- introducedInModel: 1,
460
- minReaderModel: 0,
461
- documentTypes: Object.freeze([ "definition", "instance" ]),
462
- compatibility: "additive",
463
- applicability: "unconditional",
464
- summary: "Definition and instance documents carry model provenance and reader-floor stamps."
465
- }), Object.freeze({
466
- id: "subject-field-kind",
467
- introducedInModel: 2,
468
- minReaderModel: 0,
469
- documentTypes: Object.freeze([ "definition", "instance" ]),
470
- compatibility: "additive",
471
- applicability: "detectable",
472
- summary: "A workflow-level subject field identifies the document a workflow is about."
473
- }), Object.freeze({
474
- id: "typed-scalar-choice-lists",
475
- introducedInModel: 2,
476
- minReaderModel: 2,
477
- documentTypes: Object.freeze([ "definition", "instance" ]),
478
- compatibility: "reader-floor",
479
- applicability: "detectable",
480
- summary: "Scalar fields may constrain writes to a persisted typed choice list."
481
- }), Object.freeze({
482
- id: "action-semantics",
483
- introducedInModel: 2,
484
- minReaderModel: 0,
485
- documentTypes: Object.freeze([ "definition" ]),
486
- compatibility: "additive",
487
- applicability: "detectable",
488
- summary: "Ordinary actions may carry advisory workflow semantics."
489
- }), Object.freeze({
490
- id: "inclusive-scalar-bounds",
491
- introducedInModel: 2,
492
- minReaderModel: 2,
493
- documentTypes: Object.freeze([ "definition", "instance" ]),
494
- compatibility: "reader-floor",
495
- applicability: "detectable",
496
- summary: "String, text, and number values may carry persisted inclusive bounds."
497
- }), Object.freeze({
498
- id: "progress-field-kind",
499
- introducedInModel: 3,
500
- minReaderModel: 0,
501
- documentTypes: Object.freeze([ "definition", "instance" ]),
502
- compatibility: "additive",
503
- applicability: "detectable",
504
- summary: "A progress field kind carries application-defined 0–100 completion."
505
- }), Object.freeze({
506
- id: "effect-claim-tokens",
507
- introducedInModel: 3,
508
- minReaderModel: 0,
509
- documentTypes: Object.freeze([ "instance" ]),
510
- compatibility: "additive",
511
- applicability: "detectable",
512
- summary: "Pending-effect claims carry an exact-claim token gating mid-dispatch state reports."
513
- }), Object.freeze({
514
- id: "classified-principal-ids",
515
- introducedInModel: 4,
516
- minReaderModel: 4,
517
- documentTypes: Object.freeze([ "instance" ]),
518
- compatibility: "reader-floor",
519
- applicability: "unconditional",
520
- summary: "Principal ids are namespace-classified: actor and assignee writes carry the account-global user id only, and readers resolve legacy project-scoped ids through the prefix classifier at the instance read funnel."
521
- }), Object.freeze({
522
- id: "readiness-requirements",
523
- introducedInModel: 4,
524
- minReaderModel: 4,
525
- documentTypes: Object.freeze([ "definition" ]),
526
- compatibility: "reader-floor",
527
- applicability: "detectable",
528
- summary: "Start and activity readiness use named polymorphic requirement arrays."
529
- }), Object.freeze({
530
- id: "due-date-field-kinds",
531
- introducedInModel: 5,
532
- minReaderModel: 0,
533
- documentTypes: Object.freeze([ "definition", "instance" ]),
534
- compatibility: "additive",
535
- applicability: "detectable",
536
- summary: "Due-date field kinds (dueDate, dueDatetime) mark a level deadline, elevated aliases of date/datetime carrying the same stored value."
537
- }), Object.freeze({
538
- id: "node-semantics",
539
- introducedInModel: 6,
540
- minReaderModel: 0,
541
- documentTypes: Object.freeze([ "definition" ]),
542
- compatibility: "additive",
543
- applicability: "detectable",
544
- summary: "Workflow, stage, activity, and action nodes may carry signal or custom advisory semantics."
545
- }), Object.freeze({
546
- id: "field-patch-ops",
547
- introducedInModel: 6,
548
- minReaderModel: 0,
549
- documentTypes: Object.freeze([ "definition", "instance" ]),
550
- compatibility: "additive",
551
- applicability: "detectable",
552
- summary: "Field ops may increment, decrement, or initialize a missing field value."
553
- }), Object.freeze({
554
- id: "attributes-condition-var",
555
- introducedInModel: 7,
556
- minReaderModel: 0,
557
- documentTypes: Object.freeze([ "definition" ]),
558
- compatibility: "additive",
559
- applicability: "unconditional",
560
- summary: "Caller-bound $attributes condition variable binds the acting token's org-level User Attributes (advisory; absent when unavailable)."
561
- }) ]);
461
+ function rolesFilterList(node) {
462
+ if (node.type !== "Filter") return;
463
+ const base = node.base;
464
+ if (!(base.type === "AccessAttribute" && base.name === "roles" && base.base?.type === "Parameter" && base.base.name === "actor")) return;
465
+ const expr = node.expr;
466
+ if (expr.type !== "OpCall" || expr.op !== "in" || expr.left.type !== "This" || expr.right.type !== "Array") return;
467
+ const roles = expr.right.elements.flatMap(element => !element.isSplat && element.value.type === "Value" && typeof element.value.value == "string" ? [ element.value.value ] : []);
468
+ if (roles.length === expr.right.elements.length) return roles;
469
+ }
562
470
 
563
- function recordOf(value) {
564
- return value !== null && typeof value == "object" && !Array.isArray(value) ? value : void 0;
471
+ function deriveWorkflowAutonomy(definition, options = {}) {
472
+ return workflowAutonomy({
473
+ definition: definition,
474
+ children: options.children ?? /* @__PURE__ */ new Map,
475
+ lineage: /* @__PURE__ */ new Set
476
+ });
565
477
  }
566
478
 
567
- function recordsAt(record, key) {
568
- const value = record[key];
569
- return Array.isArray(value) ? value.map(recordOf).filter(item => item !== void 0) : [];
479
+ function stageAutonomyOf(autonomy, stageName) {
480
+ const stage = autonomy.stages.find(candidate => candidate.stage === stageName);
481
+ if (stage === void 0) throw new Error(`Autonomy rollup is missing stage "${stageName}"`);
482
+ return stage;
570
483
  }
571
484
 
572
- function nestedFieldEntries(entries) {
573
- return entries.flatMap(entry => [ entry, ...nestedFieldEntries(recordsAt(entry, "fields")), ...nestedFieldEntries(recordsAt(entry, "of")) ]);
485
+ function activityAutonomyOf(stageAutonomy2, activityName) {
486
+ const answer = stageAutonomy2.activities[activityName];
487
+ if (answer === void 0) throw new Error(`Autonomy rollup is missing activity "${activityName}" in stage "${stageAutonomy2.stage}"`);
488
+ return answer;
574
489
  }
575
490
 
576
- function parsedDefinitionSnapshot(root) {
577
- if (typeof root.definitionSnapshot == "string") return recordOf(parseDefinitionSnapshotValue({
578
- _id: typeof root._id == "string" ? root._id : "<unknown instance>",
579
- definitionSnapshot: root.definitionSnapshot
580
- }));
491
+ const AUTONOMOUS = {
492
+ completesWithoutCaller: "yes",
493
+ waitsOn: []
494
+ }, UNDECIDABLE = {
495
+ completesWithoutCaller: "conditional",
496
+ waitsOn: []
497
+ }, CALLER = {
498
+ completesWithoutCaller: "no",
499
+ waitsOn: []
500
+ }, VERDICT_RANK = {
501
+ yes: 0,
502
+ conditional: 1,
503
+ no: 2
504
+ };
505
+
506
+ function allOf(deps) {
507
+ return {
508
+ completesWithoutCaller: deps.map(dep => dep.completesWithoutCaller).reduce((worst, verdict) => VERDICT_RANK[verdict] > VERDICT_RANK[worst] ? verdict : worst, "yes"),
509
+ waitsOn: mergeWaits(deps)
510
+ };
581
511
  }
582
512
 
583
- function persistedDefinitionTree(document) {
584
- const root = recordOf(document);
585
- if (root === void 0) return;
586
- const snapshot = parsedDefinitionSnapshot(root), roots = snapshot === void 0 ? [ root ] : [ root, snapshot ], {stages: stages, activities: activities, actions: actions} = definitionDescendants(roots);
513
+ function anyOf(deps) {
514
+ const [first, ...rest] = deps;
515
+ if (first === void 0) throw new Error("anyOf needs at least one route — callers guard empties");
587
516
  return {
588
- roots: roots,
589
- stages: stages,
590
- activities: activities,
591
- actions: actions
517
+ completesWithoutCaller: rest.every(dep => dep.completesWithoutCaller === first.completesWithoutCaller) ? first.completesWithoutCaller : "conditional",
518
+ waitsOn: mergeWaits(deps)
592
519
  };
593
520
  }
594
521
 
595
- function persistedFieldEntries(document) {
596
- const tree = persistedDefinitionTree(document);
597
- if (tree === void 0) return [];
598
- const {roots: roots, stages: stages, activities: activities, actions: actions} = tree, effects = actions.flatMap(action => recordsAt(action, "effects"));
599
- return nestedFieldEntries([ ...roots.flatMap(candidate => recordsAt(candidate, "fields")), ...stages.flatMap(stage => recordsAt(stage, "fields")), ...activities.flatMap(activity => recordsAt(activity, "fields")), ...actions.flatMap(action => recordsAt(action, "params")), ...effects.flatMap(effect => recordsAt(effect, "outputs")) ]);
522
+ function mergeWaits(deps) {
523
+ return dedupeBy(deps.flatMap(dep => dep.waitsOn), wait => JSON.stringify(wait));
600
524
  }
601
525
 
602
- function definitionDescendants(roots) {
603
- const stages = roots.flatMap(root => recordsAt(root, "stages")), activities = stages.flatMap(stage => recordsAt(stage, "activities")), actions = activities.flatMap(activity => recordsAt(activity, "actions"));
526
+ function analysisCtx(args) {
527
+ const memo = /* @__PURE__ */ new Map, visiting = /* @__PURE__ */ new Set;
604
528
  return {
605
- stages: stages,
606
- activities: activities,
607
- actions: actions
529
+ ...args,
530
+ memoized: (key, compute) => {
531
+ const hit = memo.get(key);
532
+ if (hit !== void 0) return hit;
533
+ if (visiting.has(key)) return UNDECIDABLE;
534
+ visiting.add(key);
535
+ try {
536
+ const answer = compute();
537
+ return memo.set(key, answer), answer;
538
+ } finally {
539
+ visiting.delete(key);
540
+ }
541
+ }
608
542
  };
609
543
  }
610
544
 
611
- function hasChoiceList(document) {
612
- return persistedFieldEntries(document).some(entry => {
613
- const options = recordOf(entry.options);
614
- return options !== void 0 && Array.isArray(options.list);
615
- });
616
- }
617
-
618
- function hasFieldKind(document, kind) {
619
- return persistedFieldEntries(document).some(entry => entry.type === kind || entry._type === kind);
545
+ function workflowAutonomy(args) {
546
+ const ctx = analysisCtx({
547
+ definition: args.definition,
548
+ children: args.children,
549
+ lineage: /* @__PURE__ */ new Set([ ...args.lineage, args.definition.name ])
550
+ }), stages = ctx.definition.stages.map(stage => stageAutonomy(stage, ctx));
551
+ return {
552
+ ...allOf(stages),
553
+ stages: stages
554
+ };
620
555
  }
621
556
 
622
- function definitionNodes(document) {
623
- const root = recordOf(document);
624
- if (root !== void 0) return {
625
- root: root,
626
- ...definitionDescendants([ root ])
627
- };
628
- }
629
-
630
- function hasActionSemantics(document) {
631
- return definitionNodes(document)?.actions.some(hasSemantics) ?? !1;
632
- }
633
-
634
- function hasNodeSemantics(document) {
635
- const nodes = definitionNodes(document);
636
- return nodes === void 0 ? !1 : [ nodes.root, ...nodes.stages, ...nodes.activities ].some(hasSemantics) ? !0 : nodes.actions.some(action => hasSemantics(action) && action.semantics.some(isNodeSemanticValue));
637
- }
638
-
639
- function isNodeSemanticValue(semantic) {
640
- return typeof semantic == "string" && (semantic.startsWith("signal.") || semantic.startsWith("custom."));
641
- }
642
-
643
- function hasSemantics(node) {
644
- return Array.isArray(node.semantics);
645
- }
646
-
647
- function hasPersistedOpType(document, types) {
648
- const tree = persistedDefinitionTree(document);
649
- return tree === void 0 ? !1 : tree.actions.flatMap(action => recordsAt(action, "ops")).some(op => typeof op.type == "string" && types.includes(op.type)) ? !0 : tree.roots.some(root => recordsAt(root, "history").some(entry => entry._type === "opApplied" && typeof entry.opType == "string" && types.includes(entry.opType)));
650
- }
651
-
652
- function hasScalarValidation(document) {
653
- return persistedFieldEntries(document).some(entry => {
654
- const validation = recordOf(entry.validation);
655
- return typeof validation?.min == "number" || typeof validation?.max == "number";
656
- });
657
- }
658
-
659
- function hasClaimTokens(document) {
660
- const root = recordOf(document);
661
- return root === void 0 ? !1 : recordsAt(root, "pendingEffects").some(entry => {
662
- const claim = recordOf(entry.claim);
663
- return claim !== void 0 && typeof claim.claimToken == "string";
664
- });
665
- }
666
-
667
- function hasReadinessRequirements(document) {
668
- const root = recordOf(document);
669
- return root === void 0 ? !1 : Array.isArray(recordOf(root.start)?.requirements) ? !0 : recordsAt(root, "stages").some(stage => recordsAt(stage, "activities").some(activity => Array.isArray(activity.requirements)));
670
- }
671
-
672
- const featureDetectors = {
673
- "governed-model-stamps": () => !0,
674
- "subject-field-kind": document => hasFieldKind(document, "subject"),
675
- "typed-scalar-choice-lists": hasChoiceList,
676
- "action-semantics": hasActionSemantics,
677
- "inclusive-scalar-bounds": hasScalarValidation,
678
- "progress-field-kind": document => hasFieldKind(document, "progress"),
679
- "effect-claim-tokens": hasClaimTokens,
680
- "classified-principal-ids": () => !0,
681
- "readiness-requirements": hasReadinessRequirements,
682
- "due-date-field-kinds": document => hasFieldKind(document, "dueDate") || hasFieldKind(document, "dueDatetime"),
683
- "node-semantics": hasNodeSemantics,
684
- "field-patch-ops": document => hasPersistedOpType(document, [ "field.inc", "field.dec", "field.setIfMissing" ]),
685
- "attributes-condition-var": () => !0
686
- };
687
-
688
- function requiredModelFeatures(documentType, document) {
689
- return DATA_MODEL_CHANGES.filter(change => change.documentTypes.some(candidate => candidate === documentType) && featureDetectors[change.id](document));
690
- }
691
-
692
- function requiredReaderModel(documentType, document) {
693
- return Math.max(0, ...requiredModelFeatures(documentType, document).map(change => change.minReaderModel));
694
- }
695
-
696
- function modelStampFor(args) {
697
- return {
698
- modelVersion: DATA_MODEL_VERSION,
699
- minReaderModel: Math.max(DATA_MODEL_MIN_READER, args.storedMinReaderModel ?? 0, requiredReaderModel(args.documentType, args.document))
700
- };
701
- }
702
-
703
- function fieldTreeShape(value) {
704
- if (Array.isArray(value)) return value.map(fieldTreeShape);
705
- if (value === null) return "null";
706
- if (typeof value == "object") {
707
- const record = value;
708
- return Object.fromEntries(Object.keys(record).toSorted().map(key => [ key, fieldTreeShape(record[key]) ]));
709
- }
710
- return typeof value;
711
- }
712
-
713
- function modelVersionOf(doc) {
714
- const stamp = doc.modelVersion;
715
- return typeof stamp == "number" ? stamp : 0;
716
- }
717
-
718
- function minReaderModelOf(doc) {
719
- const floor = doc.minReaderModel;
720
- return typeof floor == "number" ? floor : modelVersionOf(doc);
721
- }
722
-
723
- class ModelVersionAheadError extends WorkflowError {
724
- documentId;
725
- documentModelVersion;
726
- requiredReaderModel;
727
- engineModelVersion;
728
- constructor(args) {
729
- super("model-version-ahead", `Document "${args.documentId}" was written by engine data model ${args.documentModelVersion} and requires a reader at model ${args.requiredReaderModel} or newer; this engine reads up to model ${DATA_MODEL_VERSION}. Upgrade @sanity/workflow-engine to a version that understands it.`),
730
- this.name = "ModelVersionAheadError", this.documentId = args.documentId, this.documentModelVersion = args.documentModelVersion,
731
- this.requiredReaderModel = args.requiredReaderModel, this.engineModelVersion = DATA_MODEL_VERSION;
732
- }
733
- }
734
-
735
- function assertReadableModel(doc) {
736
- const documentReaderModel = minReaderModelOf(doc);
737
- if (documentReaderModel > DATA_MODEL_VERSION) throw new ModelVersionAheadError({
738
- documentId: doc._id,
739
- documentModelVersion: modelVersionOf(doc),
740
- requiredReaderModel: documentReaderModel
741
- });
742
- return doc;
743
- }
744
-
745
- function effectSites(def) {
746
- const sites = [];
747
- for (const stage of def.stages ?? []) for (const activity of stage.activities ?? []) for (const action of activity.actions ?? []) for (const effect of action.effects ?? []) sites.push({
748
- effect: effect,
749
- location: `stage[${stage.name}].activity[${activity.name}].action[${action.name}].effects`
750
- });
751
- return sites;
752
- }
753
-
754
- function findEffect(def, name) {
755
- return effectSites(def).find(site => site.effect.name === name)?.effect;
756
- }
757
-
758
- function rolesGateOf(atom) {
759
- const node = atomNode(atom);
760
- if (atom.negated || node.type !== "OpCall" || node.op !== ">" || node.right.type !== "Value" || node.right.value !== 0) return;
761
- const count = node.left;
762
- if (!(count.type !== "FuncCall" || count.name !== "count" || count.args.length !== 1)) return rolesFilterList(count.args[0]);
763
- }
764
-
765
- function rolesFilterList(node) {
766
- if (node.type !== "Filter") return;
767
- const base = node.base;
768
- if (!(base.type === "AccessAttribute" && base.name === "roles" && base.base?.type === "Parameter" && base.base.name === "actor")) return;
769
- const expr = node.expr;
770
- if (expr.type !== "OpCall" || expr.op !== "in" || expr.left.type !== "This" || expr.right.type !== "Array") return;
771
- const roles = expr.right.elements.flatMap(element => !element.isSplat && element.value.type === "Value" && typeof element.value.value == "string" ? [ element.value.value ] : []);
772
- if (roles.length === expr.right.elements.length) return roles;
773
- }
774
-
775
- function deriveWorkflowAutonomy(definition, options = {}) {
776
- return workflowAutonomy({
777
- definition: definition,
778
- children: options.children ?? /* @__PURE__ */ new Map,
779
- lineage: /* @__PURE__ */ new Set
780
- });
781
- }
782
-
783
- function stageAutonomyOf(autonomy, stageName) {
784
- const stage = autonomy.stages.find(candidate => candidate.stage === stageName);
785
- if (stage === void 0) throw new Error(`Autonomy rollup is missing stage "${stageName}"`);
786
- return stage;
787
- }
788
-
789
- function activityAutonomyOf(stageAutonomy2, activityName) {
790
- const answer = stageAutonomy2.activities[activityName];
791
- if (answer === void 0) throw new Error(`Autonomy rollup is missing activity "${activityName}" in stage "${stageAutonomy2.stage}"`);
792
- return answer;
793
- }
794
-
795
- const AUTONOMOUS = {
796
- completesWithoutCaller: "yes",
797
- waitsOn: []
798
- }, UNDECIDABLE = {
799
- completesWithoutCaller: "conditional",
800
- waitsOn: []
801
- }, CALLER = {
802
- completesWithoutCaller: "no",
803
- waitsOn: []
804
- }, VERDICT_RANK = {
805
- yes: 0,
806
- conditional: 1,
807
- no: 2
808
- };
809
-
810
- function allOf(deps) {
811
- return {
812
- completesWithoutCaller: deps.map(dep => dep.completesWithoutCaller).reduce((worst, verdict) => VERDICT_RANK[verdict] > VERDICT_RANK[worst] ? verdict : worst, "yes"),
813
- waitsOn: mergeWaits(deps)
814
- };
815
- }
816
-
817
- function anyOf(deps) {
818
- const [first, ...rest] = deps;
819
- if (first === void 0) throw new Error("anyOf needs at least one route — callers guard empties");
820
- return {
821
- completesWithoutCaller: rest.every(dep => dep.completesWithoutCaller === first.completesWithoutCaller) ? first.completesWithoutCaller : "conditional",
822
- waitsOn: mergeWaits(deps)
823
- };
824
- }
825
-
826
- function mergeWaits(deps) {
827
- return dedupeBy(deps.flatMap(dep => dep.waitsOn), wait => JSON.stringify(wait));
828
- }
829
-
830
- function analysisCtx(args) {
831
- const memo = /* @__PURE__ */ new Map, visiting = /* @__PURE__ */ new Set;
832
- return {
833
- ...args,
834
- memoized: (key, compute) => {
835
- const hit = memo.get(key);
836
- if (hit !== void 0) return hit;
837
- if (visiting.has(key)) return UNDECIDABLE;
838
- visiting.add(key);
839
- try {
840
- const answer = compute();
841
- return memo.set(key, answer), answer;
842
- } finally {
843
- visiting.delete(key);
844
- }
845
- }
846
- };
847
- }
848
-
849
- function workflowAutonomy(args) {
850
- const ctx = analysisCtx({
851
- definition: args.definition,
852
- children: args.children,
853
- lineage: /* @__PURE__ */ new Set([ ...args.lineage, args.definition.name ])
854
- }), stages = ctx.definition.stages.map(stage => stageAutonomy(stage, ctx));
855
- return {
856
- ...allOf(stages),
857
- stages: stages
858
- };
859
- }
860
-
861
- function stageAutonomy(stage, ctx) {
862
- const activities = Object.fromEntries((stage.activities ?? []).map(activity => [ activity.name, activityCompletion({
863
- stage: stage,
864
- activity: activity
865
- }, ctx) ]));
866
- return {
867
- ...stageProgress(stage, ctx),
868
- stage: stage.name,
869
- activities: activities
557
+ function stageAutonomy(stage, ctx) {
558
+ const activities = Object.fromEntries((stage.activities ?? []).map(activity => [ activity.name, activityCompletion({
559
+ stage: stage,
560
+ activity: activity
561
+ }, ctx) ]));
562
+ return {
563
+ ...stageProgress(stage, ctx),
564
+ stage: stage.name,
565
+ activities: activities
870
566
  };
871
567
  }
872
568
 
@@ -2157,10 +1853,6 @@ function derefBase(ref, snapshot) {
2157
1853
  };
2158
1854
  }
2159
1855
 
2160
- function isRecord(value) {
2161
- return typeof value == "object" && value !== null && !Array.isArray(value);
2162
- }
2163
-
2164
1856
  function buildParams(args) {
2165
1857
  const {instance: instance, now: now, snapshot: snapshot, extra: extra} = args, currentActivities2 = findOpenStageEntry(instance)?.activities ?? [];
2166
1858
  return {
@@ -2696,38 +2388,7 @@ function isFieldOp(summary) {
2696
2388
 
2697
2389
  function validateActionParams({action: action, activityName: activityName, callerParams: callerParams}) {
2698
2390
  const declared = action.params ?? [], params = callerParams ?? {}, issues = [];
2699
- for (const decl of declared) {
2700
- const value = params[decl.name], present = decl.name in params && value !== void 0 && value !== null;
2701
- if (decl.required === !0 && !present) {
2702
- issues.push({
2703
- param: decl.name,
2704
- reason: "required but missing"
2705
- });
2706
- continue;
2707
- }
2708
- if (!present) continue;
2709
- if (!checkParamType(value, decl)) {
2710
- issues.push({
2711
- param: decl.name,
2712
- reason: `expected type=${decl.type}, got ${typeof value}`
2713
- });
2714
- continue;
2715
- }
2716
- const choiceIssues = choiceValueIssues(decl.options, value);
2717
- choiceIssues !== void 0 && issues.push({
2718
- param: decl.name,
2719
- reason: choiceIssues.join("; ")
2720
- });
2721
- const validationIssues = scalarValidationIssues({
2722
- entryType: decl.type,
2723
- validation: decl.validation,
2724
- value: value
2725
- });
2726
- validationIssues !== void 0 && issues.push({
2727
- param: decl.name,
2728
- reason: validationIssues.join("; ")
2729
- });
2730
- }
2391
+ for (const decl of declared) issues.push(...declaredParamIssues(decl, params));
2731
2392
  if (issues.length > 0) throw new ActionParamsInvalidError({
2732
2393
  action: action.name,
2733
2394
  activity: activityName,
@@ -2736,8 +2397,32 @@ function validateActionParams({action: action, activityName: activityName, calle
2736
2397
  return params;
2737
2398
  }
2738
2399
 
2739
- function hasStringField(value, field) {
2740
- return typeof value == "object" && value !== null && field in value && typeof value[field] == "string";
2400
+ function declaredParamIssues(decl, params) {
2401
+ const value = params[decl.name];
2402
+ if (!(decl.name in params && value !== void 0 && value !== null)) return decl.required === !0 ? [ {
2403
+ param: decl.name,
2404
+ reason: "required but missing"
2405
+ } ] : [];
2406
+ if (!checkParamType(value, decl)) return [ {
2407
+ param: decl.name,
2408
+ reason: `expected type=${decl.type}, got ${typeof value}`
2409
+ } ];
2410
+ const choiceIssues = choiceValueIssues(decl.options, value), validationIssues = scalarValidationIssues({
2411
+ entryType: decl.type,
2412
+ validation: decl.validation,
2413
+ value: value
2414
+ });
2415
+ return [ ...choiceIssues === void 0 ? [] : [ {
2416
+ param: decl.name,
2417
+ reason: choiceIssues.join("; ")
2418
+ } ], ...validationIssues === void 0 ? [] : [ {
2419
+ param: decl.name,
2420
+ reason: validationIssues.join("; ")
2421
+ } ] ];
2422
+ }
2423
+
2424
+ function hasStringField(value, field) {
2425
+ return typeof value == "object" && value !== null && field in value && typeof value[field] == "string";
2741
2426
  }
2742
2427
 
2743
2428
  function checkParamType(value, decl) {
@@ -2787,7 +2472,9 @@ async function runOps(args) {
2787
2472
  now: now,
2788
2473
  snapshot: snapshot,
2789
2474
  refSurface: refSurface,
2790
- opsFromDefinition: opsFromDefinition
2475
+ opsFromDefinition: opsFromDefinition,
2476
+ memberRoles: args.memberRoles,
2477
+ roleAliases: args.roleAliases
2791
2478
  });
2792
2479
  summaries.push(summary), shouldRecordOpApplied(summary) && mutation.history.push(opAppliedEntry({
2793
2480
  origin: origin,
@@ -2908,7 +2595,12 @@ function applyFieldSet(op, ctx) {
2908
2595
  entryType: entry._type,
2909
2596
  entryName: entry.name,
2910
2597
  value: value,
2911
- ...entryShape(entry)
2598
+ ...entryShape(entry),
2599
+ memberRoles: ctx.memberRoles,
2600
+ roleAliases: ctx.roleAliases,
2601
+ ...entry._type === "assignees" || entry._type === "object" || entry._type === "array" ? {
2602
+ previousValue: entry.value
2603
+ } : {}
2912
2604
  });
2913
2605
  return assertRuntimeRefsWithinSurface({
2914
2606
  entryType: entry._type,
@@ -3005,7 +2697,17 @@ function entryShape(entry) {
3005
2697
  of: entry.of
3006
2698
  } : isSingleDocRefEntry(entry) || entry._type === "doc.refs" ? entry.types !== void 0 ? {
3007
2699
  types: entry.types
3008
- } : {} : {
2700
+ } : {} : isAssignmentFieldEntry(entry) ? assignmentEntryShape(entry) : scalarEntryShape(entry);
2701
+ }
2702
+
2703
+ function assignmentEntryShape(entry) {
2704
+ return entry.roles !== void 0 ? {
2705
+ roles: entry.roles
2706
+ } : {};
2707
+ }
2708
+
2709
+ function scalarEntryShape(entry) {
2710
+ return {
3009
2711
  ...entry.options !== void 0 ? {
3010
2712
  options: entry.options
3011
2713
  } : {},
@@ -3053,7 +2755,10 @@ function applyFieldAppend(op, ctx) {
3053
2755
  entryName: entry.name,
3054
2756
  item: item,
3055
2757
  types: entry._type === "doc.refs" ? entry.types : void 0,
3056
- of: entry._type === "array" ? entry.of : void 0
2758
+ of: entry._type === "array" ? entry.of : void 0,
2759
+ roles: entry._type === "assignees" ? entry.roles : void 0,
2760
+ memberRoles: ctx.memberRoles,
2761
+ roleAliases: ctx.roleAliases
3057
2762
  });
3058
2763
  assertRuntimeRefsWithinSurface({
3059
2764
  entryType: entry._type === "doc.refs" ? "doc.ref" : "object",
@@ -3101,6 +2806,13 @@ async function applyFieldUpdateWhere(op, ctx) {
3101
2806
  merge: mergeRecord,
3102
2807
  entry: entry,
3103
2808
  op: op
2809
+ }), validateFieldValue({
2810
+ entryType: "array",
2811
+ entryName: entry.name,
2812
+ value: [ mergeRecord ],
2813
+ of: entry.of,
2814
+ memberRoles: ctx.memberRoles,
2815
+ roleAliases: ctx.roleAliases
3104
2816
  });
3105
2817
  const matches = await rowMatches({
3106
2818
  where: op.where,
@@ -3217,18 +2929,6 @@ function subSlot(target, field) {
3217
2929
  function resolveOpValue(args) {
3218
2930
  const {src: src, ctx: ctx, target: target} = args;
3219
2931
  switch (src.type) {
3220
- case "literal":
3221
- case "param":
3222
- case "actor":
3223
- case "now":
3224
- return resolveStaticValueExpr(src, ctx);
3225
-
3226
- case "self":
3227
- return ctx.self;
3228
-
3229
- case "stage":
3230
- return ctx.stage;
3231
-
3232
2932
  case "fieldRead":
3233
2933
  {
3234
2934
  const entry = readEntryFromMutation(ctx, src);
@@ -3258,6 +2958,25 @@ function resolveOpValue(args) {
3258
2958
  }
3259
2959
  return out;
3260
2960
  }
2961
+
2962
+ default:
2963
+ return resolveAtomicOpValue(src, ctx);
2964
+ }
2965
+ }
2966
+
2967
+ function resolveAtomicOpValue(src, ctx) {
2968
+ switch (src.type) {
2969
+ case "literal":
2970
+ case "param":
2971
+ case "actor":
2972
+ case "now":
2973
+ return resolveStaticValueExpr(src, ctx);
2974
+
2975
+ case "self":
2976
+ return ctx.self;
2977
+
2978
+ case "stage":
2979
+ return ctx.stage;
3261
2980
  }
3262
2981
  }
3263
2982
 
@@ -3699,13 +3418,354 @@ async function instanceWriteDenials(args) {
3699
3418
  });
3700
3419
  }
3701
3420
 
3702
- async function assertInstanceWriteAllowed(args) {
3703
- const denied = await instanceWriteDenials(args);
3704
- if (denied.length !== 0) throw MutationGuardDeniedError.fromGuards({
3705
- documentId: args.instance._id,
3706
- action: "update",
3707
- guards: denied
3421
+ async function assertInstanceWriteAllowed(args) {
3422
+ const denied = await instanceWriteDenials(args);
3423
+ if (denied.length !== 0) throw MutationGuardDeniedError.fromGuards({
3424
+ documentId: args.instance._id,
3425
+ action: "update",
3426
+ guards: denied
3427
+ });
3428
+ }
3429
+
3430
+ const DATA_MODEL_VERSION = 8, DATA_MODEL_MIN_READER = 4, DATA_MODEL_MAX_READER = 8, READER_MODEL_ROLLOUT_URL = "https://www.sanity.io/docs/workflows/prerelease";
3431
+
3432
+ class ReaderModelAcknowledgementError extends WorkflowError {
3433
+ code="WORKFLOW_READER_MODEL_ACKNOWLEDGEMENT_MISMATCH";
3434
+ expectedMinReaderModel;
3435
+ requiredMinReaderModel;
3436
+ engineMinReaderModel=DATA_MODEL_MIN_READER;
3437
+ engineMaxReaderModel=DATA_MODEL_MAX_READER;
3438
+ engineModelVersion=DATA_MODEL_VERSION;
3439
+ documentationUrl=READER_MODEL_ROLLOUT_URL;
3440
+ constructor(expectedMinReaderModel, options = {}) {
3441
+ const {context: context = "Deployment", requiredMinReaderModel: requiredMinReaderModel = DATA_MODEL_MIN_READER} = options, expected = expectedMinReaderModel === void 0 ? "missing" : String(expectedMinReaderModel);
3442
+ super("reader-model-acknowledgement", `${context} acknowledges reader model ${expected}; the submitted definitions require at least ${requiredMinReaderModel}, and this writer supports acknowledgements through ${DATA_MODEL_MAX_READER}.\nUse a reviewed numeric literal in that range. Before raising it, ensure every runtime sharing the workflow resource can read the required model.\nRollout guide: ${READER_MODEL_ROLLOUT_URL}`),
3443
+ this.name = "ReaderModelAcknowledgementError", this.expectedMinReaderModel = expectedMinReaderModel,
3444
+ this.requiredMinReaderModel = requiredMinReaderModel;
3445
+ }
3446
+ }
3447
+
3448
+ function assertReaderModelAcknowledgement(expectedMinReaderModel, options) {
3449
+ const {context: context, requiredMinReaderModel: requiredMinReaderModel} = options;
3450
+ if (typeof expectedMinReaderModel != "number" || !Number.isFinite(expectedMinReaderModel) || !Number.isInteger(expectedMinReaderModel) || expectedMinReaderModel < 0 || expectedMinReaderModel < requiredMinReaderModel || expectedMinReaderModel > DATA_MODEL_MAX_READER) throw new ReaderModelAcknowledgementError(expectedMinReaderModel, {
3451
+ requiredMinReaderModel: requiredMinReaderModel,
3452
+ ...context !== void 0 ? {
3453
+ context: context
3454
+ } : {}
3455
+ });
3456
+ }
3457
+
3458
+ const DATA_MODEL_CHANGES = Object.freeze([ Object.freeze({
3459
+ id: "governed-model-stamps",
3460
+ introducedInModel: 1,
3461
+ minReaderModel: 0,
3462
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3463
+ compatibility: "additive",
3464
+ applicability: "unconditional",
3465
+ summary: "Definition and instance documents carry model provenance and reader-floor stamps."
3466
+ }), Object.freeze({
3467
+ id: "subject-field-kind",
3468
+ introducedInModel: 2,
3469
+ minReaderModel: 0,
3470
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3471
+ compatibility: "additive",
3472
+ applicability: "detectable",
3473
+ summary: "A workflow-level subject field identifies the document a workflow is about."
3474
+ }), Object.freeze({
3475
+ id: "typed-scalar-choice-lists",
3476
+ introducedInModel: 2,
3477
+ minReaderModel: 2,
3478
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3479
+ compatibility: "reader-floor",
3480
+ applicability: "detectable",
3481
+ summary: "Scalar fields may constrain writes to a persisted typed choice list."
3482
+ }), Object.freeze({
3483
+ id: "action-semantics",
3484
+ introducedInModel: 2,
3485
+ minReaderModel: 0,
3486
+ documentTypes: Object.freeze([ "definition" ]),
3487
+ compatibility: "additive",
3488
+ applicability: "detectable",
3489
+ summary: "Ordinary actions may carry advisory workflow semantics."
3490
+ }), Object.freeze({
3491
+ id: "inclusive-scalar-bounds",
3492
+ introducedInModel: 2,
3493
+ minReaderModel: 2,
3494
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3495
+ compatibility: "reader-floor",
3496
+ applicability: "detectable",
3497
+ summary: "String, text, and number values may carry persisted inclusive bounds."
3498
+ }), Object.freeze({
3499
+ id: "progress-field-kind",
3500
+ introducedInModel: 3,
3501
+ minReaderModel: 0,
3502
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3503
+ compatibility: "additive",
3504
+ applicability: "detectable",
3505
+ summary: "A progress field kind carries application-defined 0–100 completion."
3506
+ }), Object.freeze({
3507
+ id: "effect-claim-tokens",
3508
+ introducedInModel: 3,
3509
+ minReaderModel: 0,
3510
+ documentTypes: Object.freeze([ "instance" ]),
3511
+ compatibility: "additive",
3512
+ applicability: "detectable",
3513
+ summary: "Pending-effect claims carry an exact-claim token gating mid-dispatch state reports."
3514
+ }), Object.freeze({
3515
+ id: "classified-principal-ids",
3516
+ introducedInModel: 4,
3517
+ minReaderModel: 4,
3518
+ documentTypes: Object.freeze([ "instance" ]),
3519
+ compatibility: "reader-floor",
3520
+ applicability: "unconditional",
3521
+ summary: "Principal ids are namespace-classified: actor and assignee writes carry the account-global user id only, and readers resolve legacy project-scoped ids through the prefix classifier at the instance read funnel."
3522
+ }), Object.freeze({
3523
+ id: "readiness-requirements",
3524
+ introducedInModel: 4,
3525
+ minReaderModel: 4,
3526
+ documentTypes: Object.freeze([ "definition" ]),
3527
+ compatibility: "reader-floor",
3528
+ applicability: "detectable",
3529
+ summary: "Start and activity readiness use named polymorphic requirement arrays."
3530
+ }), Object.freeze({
3531
+ id: "due-date-field-kinds",
3532
+ introducedInModel: 5,
3533
+ minReaderModel: 0,
3534
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3535
+ compatibility: "additive",
3536
+ applicability: "detectable",
3537
+ summary: "Due-date field kinds (dueDate, dueDatetime) mark a level deadline, elevated aliases of date/datetime carrying the same stored value."
3538
+ }), Object.freeze({
3539
+ id: "node-semantics",
3540
+ introducedInModel: 6,
3541
+ minReaderModel: 0,
3542
+ documentTypes: Object.freeze([ "definition" ]),
3543
+ compatibility: "additive",
3544
+ applicability: "detectable",
3545
+ summary: "Workflow, stage, activity, and action nodes may carry signal or custom advisory semantics."
3546
+ }), Object.freeze({
3547
+ id: "field-patch-ops",
3548
+ introducedInModel: 6,
3549
+ minReaderModel: 0,
3550
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3551
+ compatibility: "additive",
3552
+ applicability: "detectable",
3553
+ summary: "Field ops may increment, decrement, or initialize a missing field value."
3554
+ }), Object.freeze({
3555
+ id: "attributes-condition-var",
3556
+ introducedInModel: 7,
3557
+ minReaderModel: 0,
3558
+ documentTypes: Object.freeze([ "definition" ]),
3559
+ compatibility: "additive",
3560
+ applicability: "unconditional",
3561
+ summary: "Caller-bound $attributes condition variable binds the acting token's org-level User Attributes (advisory; absent when unavailable)."
3562
+ }), Object.freeze({
3563
+ id: "role-constrained-assignment-fields",
3564
+ introducedInModel: 8,
3565
+ minReaderModel: 8,
3566
+ documentTypes: Object.freeze([ "definition", "instance" ]),
3567
+ compatibility: "reader-floor",
3568
+ applicability: "detectable",
3569
+ summary: "Assignee fields may restrict newly assigned users and collective roles by role."
3570
+ }) ]);
3571
+
3572
+ function recordOf(value) {
3573
+ return value !== null && typeof value == "object" && !Array.isArray(value) ? value : void 0;
3574
+ }
3575
+
3576
+ function recordsAt(record, key) {
3577
+ const value = record[key];
3578
+ return Array.isArray(value) ? value.map(recordOf).filter(item => item !== void 0) : [];
3579
+ }
3580
+
3581
+ function nestedFieldEntries(entries) {
3582
+ return entries.flatMap(entry => [ entry, ...nestedFieldEntries(recordsAt(entry, "fields")), ...nestedFieldEntries(recordsAt(entry, "of")) ]);
3583
+ }
3584
+
3585
+ function parsedDefinitionSnapshot(root) {
3586
+ if (typeof root.definitionSnapshot == "string") return recordOf(parseDefinitionSnapshotValue({
3587
+ _id: typeof root._id == "string" ? root._id : "<unknown instance>",
3588
+ definitionSnapshot: root.definitionSnapshot
3589
+ }));
3590
+ }
3591
+
3592
+ function persistedDefinitionTree(document) {
3593
+ const root = recordOf(document);
3594
+ if (root === void 0) return;
3595
+ const snapshot = parsedDefinitionSnapshot(root), roots = snapshot === void 0 ? [ root ] : [ root, snapshot ], {stages: stages, activities: activities, actions: actions} = definitionDescendants(roots);
3596
+ return {
3597
+ roots: roots,
3598
+ stages: stages,
3599
+ activities: activities,
3600
+ actions: actions
3601
+ };
3602
+ }
3603
+
3604
+ function persistedFieldEntries(document) {
3605
+ const tree = persistedDefinitionTree(document);
3606
+ if (tree === void 0) return [];
3607
+ const {roots: roots, stages: stages, activities: activities, actions: actions} = tree, effects = actions.flatMap(action => recordsAt(action, "effects"));
3608
+ return nestedFieldEntries([ ...roots.flatMap(candidate => recordsAt(candidate, "fields")), ...stages.flatMap(stage => recordsAt(stage, "fields")), ...activities.flatMap(activity => recordsAt(activity, "fields")), ...actions.flatMap(action => recordsAt(action, "params")), ...effects.flatMap(effect => recordsAt(effect, "outputs")) ]);
3609
+ }
3610
+
3611
+ function definitionDescendants(roots) {
3612
+ const stages = roots.flatMap(root => recordsAt(root, "stages")), activities = stages.flatMap(stage => recordsAt(stage, "activities")), actions = activities.flatMap(activity => recordsAt(activity, "actions"));
3613
+ return {
3614
+ stages: stages,
3615
+ activities: activities,
3616
+ actions: actions
3617
+ };
3618
+ }
3619
+
3620
+ function hasChoiceList(document) {
3621
+ return persistedFieldEntries(document).some(entry => {
3622
+ const options = recordOf(entry.options);
3623
+ return options !== void 0 && Array.isArray(options.list);
3624
+ });
3625
+ }
3626
+
3627
+ function entryHasKind(entry, kind) {
3628
+ return entryKindMatches(entry, candidate => candidate === kind);
3629
+ }
3630
+
3631
+ function entryKindMatches(entry, accepts) {
3632
+ return [ entry.type, entry._type ].some(kind => typeof kind == "string" && accepts(kind));
3633
+ }
3634
+
3635
+ function hasFieldKind(document, kind) {
3636
+ return persistedFieldEntries(document).some(entry => entryHasKind(entry, kind));
3637
+ }
3638
+
3639
+ function definitionNodes(document) {
3640
+ const root = recordOf(document);
3641
+ if (root !== void 0) return {
3642
+ root: root,
3643
+ ...definitionDescendants([ root ])
3644
+ };
3645
+ }
3646
+
3647
+ function hasActionSemantics(document) {
3648
+ return definitionNodes(document)?.actions.some(hasSemantics) ?? !1;
3649
+ }
3650
+
3651
+ function hasNodeSemantics(document) {
3652
+ const nodes = definitionNodes(document);
3653
+ return nodes === void 0 ? !1 : [ nodes.root, ...nodes.stages, ...nodes.activities ].some(hasSemantics) ? !0 : nodes.actions.some(action => hasSemantics(action) && action.semantics.some(isNodeSemanticValue));
3654
+ }
3655
+
3656
+ function isNodeSemanticValue(semantic) {
3657
+ return typeof semantic == "string" && (semantic.startsWith("signal.") || semantic.startsWith("custom."));
3658
+ }
3659
+
3660
+ function hasSemantics(node) {
3661
+ return Array.isArray(node.semantics);
3662
+ }
3663
+
3664
+ function hasPersistedOpType(document, types) {
3665
+ const tree = persistedDefinitionTree(document);
3666
+ return tree === void 0 ? !1 : tree.actions.flatMap(action => recordsAt(action, "ops")).some(op => typeof op.type == "string" && types.includes(op.type)) ? !0 : tree.roots.some(root => recordsAt(root, "history").some(entry => entry._type === "opApplied" && typeof entry.opType == "string" && types.includes(entry.opType)));
3667
+ }
3668
+
3669
+ function hasScalarValidation(document) {
3670
+ return persistedFieldEntries(document).some(entry => {
3671
+ const validation = recordOf(entry.validation);
3672
+ return typeof validation?.min == "number" || typeof validation?.max == "number";
3673
+ });
3674
+ }
3675
+
3676
+ function hasClaimTokens(document) {
3677
+ const root = recordOf(document);
3678
+ return root === void 0 ? !1 : recordsAt(root, "pendingEffects").some(entry => {
3679
+ const claim = recordOf(entry.claim);
3680
+ return claim !== void 0 && typeof claim.claimToken == "string";
3681
+ });
3682
+ }
3683
+
3684
+ function hasReadinessRequirements(document) {
3685
+ const root = recordOf(document);
3686
+ return root === void 0 ? !1 : Array.isArray(recordOf(root.start)?.requirements) ? !0 : recordsAt(root, "stages").some(stage => recordsAt(stage, "activities").some(activity => Array.isArray(activity.requirements)));
3687
+ }
3688
+
3689
+ function hasRoleConstrainedAssignments(document) {
3690
+ return persistedFieldEntries(document).some(entry => entryKindMatches(entry, assignmentKindAcceptsRoles) && Array.isArray(entry.roles) && entry.roles.length > 0);
3691
+ }
3692
+
3693
+ const featureDetectors = {
3694
+ "governed-model-stamps": () => !0,
3695
+ "subject-field-kind": document => hasFieldKind(document, "subject"),
3696
+ "typed-scalar-choice-lists": hasChoiceList,
3697
+ "action-semantics": hasActionSemantics,
3698
+ "inclusive-scalar-bounds": hasScalarValidation,
3699
+ "progress-field-kind": document => hasFieldKind(document, "progress"),
3700
+ "effect-claim-tokens": hasClaimTokens,
3701
+ "classified-principal-ids": () => !0,
3702
+ "readiness-requirements": hasReadinessRequirements,
3703
+ "due-date-field-kinds": document => hasFieldKind(document, "dueDate") || hasFieldKind(document, "dueDatetime"),
3704
+ "role-constrained-assignment-fields": hasRoleConstrainedAssignments,
3705
+ "node-semantics": hasNodeSemantics,
3706
+ "field-patch-ops": document => hasPersistedOpType(document, [ "field.inc", "field.dec", "field.setIfMissing" ]),
3707
+ "attributes-condition-var": () => !0
3708
+ };
3709
+
3710
+ function requiredModelFeatures(documentType, document) {
3711
+ return DATA_MODEL_CHANGES.filter(change => change.documentTypes.some(candidate => candidate === documentType) && featureDetectors[change.id](document));
3712
+ }
3713
+
3714
+ function requiredReaderModel(documentType, document) {
3715
+ return Math.max(0, ...requiredModelFeatures(documentType, document).map(change => change.minReaderModel));
3716
+ }
3717
+
3718
+ function requiredDefinitionReaderModel(definitions) {
3719
+ return Math.max(DATA_MODEL_MIN_READER, ...definitions.map(definition => requiredReaderModel("definition", definition)));
3720
+ }
3721
+
3722
+ function modelStampFor(args) {
3723
+ return {
3724
+ modelVersion: DATA_MODEL_VERSION,
3725
+ minReaderModel: Math.max(DATA_MODEL_MIN_READER, args.storedMinReaderModel ?? 0, requiredReaderModel(args.documentType, args.document))
3726
+ };
3727
+ }
3728
+
3729
+ function fieldTreeShape(value) {
3730
+ if (Array.isArray(value)) return value.map(fieldTreeShape);
3731
+ if (value === null) return "null";
3732
+ if (typeof value == "object") {
3733
+ const record = value;
3734
+ return Object.fromEntries(Object.keys(record).toSorted().map(key => [ key, fieldTreeShape(record[key]) ]));
3735
+ }
3736
+ return typeof value;
3737
+ }
3738
+
3739
+ function modelVersionOf(doc) {
3740
+ const stamp = doc.modelVersion;
3741
+ return typeof stamp == "number" ? stamp : 0;
3742
+ }
3743
+
3744
+ function minReaderModelOf(doc) {
3745
+ const floor = doc.minReaderModel;
3746
+ return typeof floor == "number" ? floor : modelVersionOf(doc);
3747
+ }
3748
+
3749
+ class ModelVersionAheadError extends WorkflowError {
3750
+ documentId;
3751
+ documentModelVersion;
3752
+ requiredReaderModel;
3753
+ engineModelVersion;
3754
+ constructor(args) {
3755
+ super("model-version-ahead", `Document "${args.documentId}" was written by engine data model ${args.documentModelVersion} and requires a reader at model ${args.requiredReaderModel} or newer; this engine reads up to model ${DATA_MODEL_VERSION}. Upgrade @sanity/workflow-engine to a version that understands it.`),
3756
+ this.name = "ModelVersionAheadError", this.documentId = args.documentId, this.documentModelVersion = args.documentModelVersion,
3757
+ this.requiredReaderModel = args.requiredReaderModel, this.engineModelVersion = DATA_MODEL_VERSION;
3758
+ }
3759
+ }
3760
+
3761
+ function assertReadableModel(doc) {
3762
+ const documentReaderModel = minReaderModelOf(doc);
3763
+ if (documentReaderModel > DATA_MODEL_VERSION) throw new ModelVersionAheadError({
3764
+ documentId: doc._id,
3765
+ documentModelVersion: modelVersionOf(doc),
3766
+ requiredReaderModel: documentReaderModel
3708
3767
  });
3768
+ return doc;
3709
3769
  }
3710
3770
 
3711
3771
  async function renderConditionScope(source, opts) {
@@ -3970,7 +4030,207 @@ function isClaimExpired(claim, now) {
3970
4030
  return claim.leaseExpiresAt === void 0 || hasPassed(claim.leaseExpiresAt, now);
3971
4031
  }
3972
4032
 
3973
- const EFFECT_RUN_STATUSES = [ "done", "failed", "cancelled" ], EXECUTION_KINDS = {
4033
+ const EFFECT_RUN_STATUSES = [ "done", "failed", "cancelled" ];
4034
+
4035
+ function userLoginProvider(user) {
4036
+ return user?.provider ?? user?.loginProvider;
4037
+ }
4038
+
4039
+ function optionalString(value) {
4040
+ return value === void 0 || typeof value == "string";
4041
+ }
4042
+
4043
+ function isClientProjectUser(value) {
4044
+ return isRecord(value) && typeof value.id == "string" && optionalString(value.sanityUserId) && optionalString(value.displayName) && optionalString(value.email) && (value.imageUrl === null || optionalString(value.imageUrl)) && optionalString(value.provider) && optionalString(value.loginProvider);
4045
+ }
4046
+
4047
+ function objectProperty(value, property) {
4048
+ if (!isRecord(value)) return;
4049
+ const propertyValue = value[property];
4050
+ return typeof propertyValue == "object" && propertyValue !== null ? propertyValue : void 0;
4051
+ }
4052
+
4053
+ function stringProperty(value, property) {
4054
+ const propertyValue = Reflect.get(value, property);
4055
+ return typeof propertyValue == "string" ? propertyValue : void 0;
4056
+ }
4057
+
4058
+ function apiErrorType(error) {
4059
+ const response = objectProperty(error, "response"), body = objectProperty(response, "body");
4060
+ if (!body) return;
4061
+ const nestedError = objectProperty(body, "error");
4062
+ return (nestedError ? stringProperty(nestedError, "type") : void 0) ?? stringProperty(body, "type");
4063
+ }
4064
+
4065
+ function isProjectUserNotFoundError(error) {
4066
+ return apiErrorType(error) === "projectUserNotFoundError";
4067
+ }
4068
+
4069
+ const memberJoinCache = /* @__PURE__ */ new WeakMap;
4070
+
4071
+ function joinCacheFor(client) {
4072
+ let cache = memberJoinCache.get(client);
4073
+ return cache === void 0 && (cache = /* @__PURE__ */ new Map, memberJoinCache.set(client, cache)),
4074
+ cache;
4075
+ }
4076
+
4077
+ function isClientProjectMember(value) {
4078
+ return isRecord(value) && typeof value.id == "string";
4079
+ }
4080
+
4081
+ async function requestProjectMembers(request, projectId) {
4082
+ const project = await request({
4083
+ uri: `/projects/${encodeURIComponent(projectId)}`
4084
+ }), members = isRecord(project) ? project.members : void 0;
4085
+ if (!Array.isArray(members) || !members.every(isClientProjectMember)) throw new Error(`Project member directory response is invalid for project "${projectId}"`);
4086
+ return members;
4087
+ }
4088
+
4089
+ async function requestProjectUsers(args) {
4090
+ const {request: request, projectId: projectId, memberIds: memberIds} = args, response = await request({
4091
+ uri: `/projects/${encodeURIComponent(projectId)}/users/${memberIds.map(encodeURIComponent).join(",")}`
4092
+ }), rows = Array.isArray(response) ? response : [ response ];
4093
+ if (!rows.every(isClientProjectUser)) throw new Error(`Project user directory response is invalid for project "${projectId}"`);
4094
+ const requested = new Set(memberIds);
4095
+ return rows.filter(row => requested.has(row.id));
4096
+ }
4097
+
4098
+ async function requestProjectMemberDirectory(args) {
4099
+ const {request: request, projectId: projectId} = args, members = await requestProjectMembers(request, projectId), memberIds = members.map(member => member.id).filter(id => classifyPrincipalId(id).namespace === "project");
4100
+ if (memberIds.length === 0) return {
4101
+ members: members,
4102
+ globalUsers: []
4103
+ };
4104
+ const users = await requestProjectUsers({
4105
+ request: request,
4106
+ projectId: projectId,
4107
+ memberIds: memberIds
4108
+ });
4109
+ return {
4110
+ members: members,
4111
+ globalUsers: users.flatMap(user => {
4112
+ const globalId = directoryBridgeId(user.sanityUserId);
4113
+ return globalId === void 0 ? [] : [ {
4114
+ memberId: user.id,
4115
+ globalId: globalId,
4116
+ user: user
4117
+ } ];
4118
+ })
4119
+ };
4120
+ }
4121
+
4122
+ async function resolveGlobalProjectUser(args) {
4123
+ const {client: client, request: request, projectId: projectId, id: id} = args, cache = joinCacheFor(client), key = `${projectId}:${id}`, hit = cache.get(key);
4124
+ if (hit !== void 0) return hit === null ? {
4125
+ status: "missing"
4126
+ } : {
4127
+ status: "resolved",
4128
+ user: hit
4129
+ };
4130
+ try {
4131
+ await ingestMemberJoin({
4132
+ request: request,
4133
+ projectId: projectId,
4134
+ cache: cache
4135
+ });
4136
+ const found = cache.get(key);
4137
+ return found != null ? {
4138
+ status: "resolved",
4139
+ user: found
4140
+ } : (cache.set(key, null), {
4141
+ status: "missing"
4142
+ });
4143
+ } catch (cause) {
4144
+ return {
4145
+ status: "inaccessible",
4146
+ cause: cause
4147
+ };
4148
+ }
4149
+ }
4150
+
4151
+ async function ingestMemberJoin(args) {
4152
+ const {request: request, projectId: projectId, cache: cache} = args, snapshot = await requestProjectMemberDirectory({
4153
+ request: request,
4154
+ projectId: projectId
4155
+ });
4156
+ for (const {globalId: globalId, user: user} of snapshot.globalUsers) cache.set(`${projectId}:${globalId}`, user);
4157
+ }
4158
+
4159
+ function clientProjectUserDirectory(client, projectId) {
4160
+ return {
4161
+ findById: async id => {
4162
+ if (!client.request) return {
4163
+ status: "inaccessible",
4164
+ cause: new Error("Project-user resolution requires WorkflowClient.request")
4165
+ };
4166
+ if (classifyPrincipalId(id).namespace === "global") return resolveGlobalProjectUser({
4167
+ client: client,
4168
+ request: client.request,
4169
+ projectId: projectId,
4170
+ id: id
4171
+ });
4172
+ try {
4173
+ const response = await client.request({
4174
+ uri: `/projects/${encodeURIComponent(projectId)}/users/${encodeURIComponent(id)}`
4175
+ }), candidate = Array.isArray(response) ? response[0] : response;
4176
+ return candidate == null ? {
4177
+ status: "missing"
4178
+ } : isClientProjectUser(candidate) ? candidate.id !== id ? {
4179
+ status: "inaccessible",
4180
+ cause: new Error(`Project-user response answered id "${candidate.id}", not the requested "${id}"`)
4181
+ } : {
4182
+ status: "resolved",
4183
+ user: candidate
4184
+ } : {
4185
+ status: "inaccessible",
4186
+ cause: new Error("Project-user response had an invalid shape")
4187
+ };
4188
+ } catch (cause) {
4189
+ return isProjectUserNotFoundError(cause) ? {
4190
+ status: "missing"
4191
+ } : {
4192
+ status: "inaccessible",
4193
+ cause: cause
4194
+ };
4195
+ }
4196
+ }
4197
+ };
4198
+ }
4199
+
4200
+ function resolveClientActor(client, args) {
4201
+ return resolveActor(clientProjectUserDirectory(client, args.projectId), args.actor);
4202
+ }
4203
+
4204
+ async function resolveActor(directory, actor) {
4205
+ if (actor.kind !== "person") return {
4206
+ status: "not-person",
4207
+ actor: actor
4208
+ };
4209
+ const personActor = {
4210
+ ...actor,
4211
+ kind: "person"
4212
+ }, lookup = await directory.findById(personActor.id);
4213
+ return lookup.status === "resolved" ? {
4214
+ status: "resolved",
4215
+ actor: personActor,
4216
+ user: lookup.user
4217
+ } : lookup.status === "inaccessible" ? {
4218
+ status: "inaccessible",
4219
+ actor: personActor,
4220
+ ...lookup.cause === void 0 ? {} : {
4221
+ cause: lookup.cause
4222
+ }
4223
+ } : {
4224
+ status: "missing",
4225
+ actor: personActor
4226
+ };
4227
+ }
4228
+
4229
+ function assertRoleConstrainedAssignmentResource(args) {
4230
+ if (hasRoleConstrainedAssignments(args.definition) && args.workflowResource.type !== "dataset") throw new Error(`${args.context}: definition "${args.definition.name}" uses role-constrained assignment fields, which require a dataset workflow resource; received resource type "${args.workflowResource.type}"`);
4231
+ }
4232
+
4233
+ const EXECUTION_KINDS = {
3974
4234
  interactive: "interactive",
3975
4235
  server: "server",
3976
4236
  cli: "cli",
@@ -4393,6 +4653,9 @@ function buildResolvedEntry({entry: entry, value: value, _key: _key, now: now})
4393
4653
  ...entry.validation !== void 0 ? {
4394
4654
  validation: entry.validation
4395
4655
  } : {},
4656
+ ...entry.roles !== void 0 ? {
4657
+ roles: entry.roles
4658
+ } : {},
4396
4659
  value: value,
4397
4660
  ...entry.initialValue?.type === "query" ? {
4398
4661
  resolvedAt: now
@@ -4424,7 +4687,10 @@ async function resolveOneEntry({entry: entry, initialFields: initialFields, ctx:
4424
4687
  fields: entry.fields,
4425
4688
  of: entry.of,
4426
4689
  options: entry.options,
4427
- validation: entry.validation
4690
+ validation: entry.validation,
4691
+ roles: entry.roles,
4692
+ memberRoles: ctx.memberRoles,
4693
+ roleAliases: ctx.roleAliases
4428
4694
  });
4429
4695
  return "issues" in check ? (ctx.recordDiscard?.({
4430
4696
  field: entry.name,
@@ -4449,7 +4715,10 @@ async function resolveOneEntry({entry: entry, initialFields: initialFields, ctx:
4449
4715
  fields: entry.fields,
4450
4716
  of: entry.of,
4451
4717
  options: entry.options,
4452
- validation: entry.validation
4718
+ validation: entry.validation,
4719
+ roles: entry.roles,
4720
+ memberRoles: ctx.memberRoles,
4721
+ roleAliases: ctx.roleAliases
4453
4722
  });
4454
4723
  return entry.initialValue?.type === "input" && ctx.inputProvenance !== "definition" && assertRefsWithinSurface({
4455
4724
  entryType: entry.type,
@@ -4543,7 +4812,7 @@ function coerceToGdr(raw, workflowResource) {
4543
4812
  } : null;
4544
4813
  }
4545
4814
 
4546
- const NonEmpty = NonEmptyString, UnknownRecord = v.record(v.string(), v.unknown()), PersistedChoiceOptionsSchema = v.looseObject({
4815
+ const NonEmpty = NonEmptyString, PersistedAssignmentRolesSchema = v.pipe(v.array(NonEmptyString), v.minLength(1, "assignment roles must not be empty")), UnknownRecord = v.record(v.string(), v.unknown()), PersistedChoiceOptionsSchema = v.looseObject({
4547
4816
  list: v.array(v.looseObject({
4548
4817
  title: v.string(),
4549
4818
  value: v.union([ v.string(), v.number() ])
@@ -4558,6 +4827,7 @@ const NonEmpty = NonEmptyString, UnknownRecord = v.record(v.string(), v.unknown(
4558
4827
  description: v.optional(v.string()),
4559
4828
  options: v.optional(PersistedChoiceOptionsSchema),
4560
4829
  validation: v.optional(PersistedScalarValidationSchema),
4830
+ roles: v.optional(PersistedAssignmentRolesSchema),
4561
4831
  fields: v.optional(v.array(PersistedFieldShapeSchema)),
4562
4832
  of: v.optional(v.array(PersistedFieldShapeSchema))
4563
4833
  }))), ExecutionContextSchema = tolerantObject()({
@@ -4603,7 +4873,13 @@ const OptionalRefTypes = v.exactOptional(v.array(v.string())), ResolvedFieldEntr
4603
4873
  })), v.looseObject(tolerantEntries()({
4604
4874
  ...fieldArm("subject", fieldValueSchemas.subject),
4605
4875
  types: OptionalRefTypes
4606
- })), v.looseObject(tolerantEntries()(fieldArm("release.ref", fieldValueSchemas["release.ref"]))), v.looseObject(tolerantEntries()(fieldArm("string", fieldValueSchemas.string))), v.looseObject(tolerantEntries()(fieldArm("text", fieldValueSchemas.text))), v.looseObject(tolerantEntries()(fieldArm("number", fieldValueSchemas.number))), v.looseObject(tolerantEntries()(fieldArm("progress", fieldValueSchemas.progress))), v.looseObject(tolerantEntries()(fieldArm("boolean", fieldValueSchemas.boolean))), v.looseObject(tolerantEntries()(fieldArm("date", fieldValueSchemas.date))), v.looseObject(tolerantEntries()(fieldArm("dueDate", fieldValueSchemas.dueDate))), v.looseObject(tolerantEntries()(fieldArm("datetime", fieldValueSchemas.datetime))), v.looseObject(tolerantEntries()(fieldArm("dueDatetime", fieldValueSchemas.dueDatetime))), v.looseObject(tolerantEntries()(fieldArm("url", fieldValueSchemas.url))), v.looseObject(tolerantEntries()(fieldArm("actor", fieldValueSchemas.actor))), v.looseObject(tolerantEntries()(fieldArm("assignee", fieldValueSchemas.assignee))), v.looseObject(tolerantEntries()(fieldArm("assignees", fieldValueSchemas.assignees))), v.looseObject(tolerantEntries()({
4876
+ })), v.looseObject(tolerantEntries()(fieldArm("release.ref", fieldValueSchemas["release.ref"]))), v.looseObject(tolerantEntries()(fieldArm("string", fieldValueSchemas.string))), v.looseObject(tolerantEntries()(fieldArm("text", fieldValueSchemas.text))), v.looseObject(tolerantEntries()(fieldArm("number", fieldValueSchemas.number))), v.looseObject(tolerantEntries()(fieldArm("progress", fieldValueSchemas.progress))), v.looseObject(tolerantEntries()(fieldArm("boolean", fieldValueSchemas.boolean))), v.looseObject(tolerantEntries()(fieldArm("date", fieldValueSchemas.date))), v.looseObject(tolerantEntries()(fieldArm("dueDate", fieldValueSchemas.dueDate))), v.looseObject(tolerantEntries()(fieldArm("datetime", fieldValueSchemas.datetime))), v.looseObject(tolerantEntries()(fieldArm("dueDatetime", fieldValueSchemas.dueDatetime))), v.looseObject(tolerantEntries()(fieldArm("url", fieldValueSchemas.url))), v.looseObject(tolerantEntries()(fieldArm("actor", fieldValueSchemas.actor))), v.looseObject(tolerantEntries()({
4877
+ ...fieldArm("assignee", fieldValueSchemas.assignee),
4878
+ roles: v.exactOptional(PersistedAssignmentRolesSchema)
4879
+ })), v.looseObject(tolerantEntries()({
4880
+ ...fieldArm("assignees", fieldValueSchemas.assignees),
4881
+ roles: v.exactOptional(PersistedAssignmentRolesSchema)
4882
+ })), v.looseObject(tolerantEntries()({
4607
4883
  ...fieldArm("object", v.union([ v.null(), UnknownRecord ])),
4608
4884
  fields: v.array(PersistedFieldShapeSchema)
4609
4885
  })), v.looseObject(tolerantEntries()({
@@ -4854,6 +5130,37 @@ function parseInstanceDocument(doc) {
4854
5130
  });
4855
5131
  }
4856
5132
 
5133
+ const WorkflowInstancePreviewEffectSchema = tolerantObject()({
5134
+ name: NonEmpty,
5135
+ title: v.exactOptional(v.string())
5136
+ }), WorkflowInstancePreviewSchema = v.looseObject(tolerantEntries()({
5137
+ _id: NonEmpty,
5138
+ _type: v.literal(WORKFLOW_INSTANCE_TYPE),
5139
+ modelVersion: v.exactOptional(v.number()),
5140
+ minReaderModel: v.exactOptional(v.number()),
5141
+ workflowResource: WorkflowResourceSchema,
5142
+ definition: NonEmpty,
5143
+ pinnedVersion: v.number(),
5144
+ fields: v.array(ResolvedFieldEntrySchema),
5145
+ ancestors: v.array(GdrShape),
5146
+ perspective: v.exactOptional(WorkflowPerspectiveSchema),
5147
+ currentStage: NonEmpty,
5148
+ stages: v.array(StageEntrySchema),
5149
+ claimedEffects: v.array(WorkflowInstancePreviewEffectSchema),
5150
+ failedEffects: v.array(WorkflowInstancePreviewEffectSchema),
5151
+ startedAt: IsoTimestamp,
5152
+ completedAt: v.exactOptional(IsoTimestamp),
5153
+ abortedAt: v.exactOptional(IsoTimestamp)
5154
+ }));
5155
+
5156
+ function parseInstancePreviewDocument(doc) {
5157
+ return parsePersistedDoc({
5158
+ schema: WorkflowInstancePreviewSchema,
5159
+ doc: doc,
5160
+ docType: WORKFLOW_INSTANCE_TYPE
5161
+ });
5162
+ }
5163
+
4857
5164
  const SYNC_COMMIT = {
4858
5165
  visibility: "sync"
4859
5166
  }, ENGINE_API_VERSION = "2026-04-29", REQUEST_TAG = {
@@ -5301,6 +5608,40 @@ function readInstanceDoc(doc) {
5301
5608
  return parseInstanceDocument(assertReadableModel(doc));
5302
5609
  }
5303
5610
 
5611
+ function readInstancePreviewDoc(doc) {
5612
+ return hasDocumentId(doc) ? parseInstancePreviewDocument(withoutProjectedNulls(assertReadableModel(doc))) : parseInstancePreviewDocument(doc);
5613
+ }
5614
+
5615
+ function hasDocumentId(doc) {
5616
+ return typeof doc == "object" && doc !== null && typeof doc._id == "string";
5617
+ }
5618
+
5619
+ function withoutProjectedNulls(doc) {
5620
+ const row = withoutNullMembers(doc);
5621
+ if (typeof row != "object" || row === null) return row;
5622
+ const out = {
5623
+ ...row
5624
+ };
5625
+ return Array.isArray(out.stages) && (out.stages = out.stages.map(withoutStageEntryNulls)),
5626
+ Array.isArray(out.claimedEffects) && (out.claimedEffects = out.claimedEffects.map(withoutNullMembers)),
5627
+ Array.isArray(out.failedEffects) && (out.failedEffects = out.failedEffects.map(withoutNullMembers)),
5628
+ out;
5629
+ }
5630
+
5631
+ function withoutStageEntryNulls(entry) {
5632
+ const stage = withoutNullMembers(entry);
5633
+ if (typeof stage != "object" || stage === null) return stage;
5634
+ const out = {
5635
+ ...stage
5636
+ };
5637
+ return Array.isArray(out.activities) && (out.activities = out.activities.map(withoutNullMembers)),
5638
+ out;
5639
+ }
5640
+
5641
+ function withoutNullMembers(value) {
5642
+ return value === null || typeof value != "object" || Array.isArray(value) ? value : Object.fromEntries(Object.entries(value).filter(([, member]) => member !== null));
5643
+ }
5644
+
5304
5645
  async function reload({client: client, instanceId: instanceId, tag: tag}) {
5305
5646
  const doc = await getInstanceDocument(client, instanceId);
5306
5647
  if (!doc) throw new InstanceNotFoundError({
@@ -5547,7 +5888,8 @@ function loadCallContext({client: client, instanceId: instanceId, options: optio
5547
5888
  } : {},
5548
5889
  ...options.telemetry ? {
5549
5890
  telemetry: options.telemetry
5550
- } : {}
5891
+ } : {},
5892
+ memberRolesLoader: options.memberRolesLoader
5551
5893
  }
5552
5894
  });
5553
5895
  }
@@ -5592,6 +5934,7 @@ async function loadContext({client: client, instanceId: instanceId, options: opt
5592
5934
  ...options.telemetry !== void 0 ? {
5593
5935
  telemetry: options.telemetry
5594
5936
  } : {},
5937
+ memberRolesLoader: options.memberRolesLoader,
5595
5938
  ...options.overlay !== void 0 ? {
5596
5939
  overlay: options.overlay
5597
5940
  } : {},
@@ -5627,7 +5970,10 @@ async function ctxEvaluateCondition({ctx: ctx, condition: condition, opts: opts}
5627
5970
  }
5628
5971
 
5629
5972
  async function buildEngineContext(args) {
5630
- const {client: client, clientForGdr: clientForGdr, refSurface: refSurface, instance: instance, definition: definition} = args, clock = args.clock ?? wallClock;
5973
+ const {client: client, clientForGdr: clientForGdr, refSurface: refSurface, instance: instance, definition: definition} = args, clock = args.clock ?? wallClock, memberRolesLoader = args.memberRolesLoader, memberRoles = await memberRolesLoader({
5974
+ workflowResource: instance.workflowResource,
5975
+ definition: definition
5976
+ });
5631
5977
  return {
5632
5978
  client: client,
5633
5979
  clientForGdr: clientForGdr,
@@ -5644,6 +5990,10 @@ async function buildEngineContext(args) {
5644
5990
  } : {},
5645
5991
  instance: instance,
5646
5992
  definition: definition,
5993
+ memberRolesLoader: memberRolesLoader,
5994
+ ...memberRoles !== void 0 ? {
5995
+ memberRoles: memberRoles
5996
+ } : {},
5647
5997
  snapshot: await hydrateSnapshot({
5648
5998
  client: client,
5649
5999
  clientForGdr: clientForGdr,
@@ -5655,6 +6005,62 @@ async function buildEngineContext(args) {
5655
6005
  };
5656
6006
  }
5657
6007
 
6008
+ function createAssignmentMemberRolesLoader(client) {
6009
+ const byProjectId = /* @__PURE__ */ new Map;
6010
+ return async ({workflowResource: workflowResource, definition: definition}) => {
6011
+ if (!hasRoleConstrainedAssignments(definition)) return;
6012
+ assertRoleConstrainedAssignmentResource({
6013
+ context: "workflow",
6014
+ definition: definition,
6015
+ workflowResource: workflowResource
6016
+ });
6017
+ const projectId = datasetResourceParts(workflowResource.id).projectId;
6018
+ let pending = byProjectId.get(projectId);
6019
+ return pending === void 0 && (pending = client.request === void 0 ? Promise.reject(new Error(`Definition "${definition.name}" has role-constrained assignments, which require project-directory access for project "${projectId}"; the client cannot issue requests`)) : loadProjectMemberRoles({
6020
+ request: client.request,
6021
+ projectId: projectId
6022
+ }), byProjectId.set(projectId, pending)), pending;
6023
+ };
6024
+ }
6025
+
6026
+ async function loadProjectMemberRoles(args) {
6027
+ const {request: request, projectId: projectId} = args, snapshot = await requestProjectMemberDirectory({
6028
+ request: request,
6029
+ projectId: projectId
6030
+ }), rolesByProjectId = projectMemberRoles({
6031
+ members: snapshot.members,
6032
+ projectId: projectId
6033
+ });
6034
+ return globalizeMemberRoles({
6035
+ snapshot: snapshot,
6036
+ rolesByProjectId: rolesByProjectId
6037
+ });
6038
+ }
6039
+
6040
+ function globalizeMemberRoles(args) {
6041
+ const {snapshot: snapshot, rolesByProjectId: rolesByProjectId} = args, humanIds = [ ...rolesByProjectId.keys() ].filter(id => classifyPrincipalId(id).namespace === "project");
6042
+ for (const {globalId: globalId, memberId: memberId} of snapshot.globalUsers) {
6043
+ const roles = rolesByProjectId.get(memberId);
6044
+ roles !== void 0 && rolesByProjectId.set(globalId, roles);
6045
+ }
6046
+ for (const id of humanIds) rolesByProjectId.delete(id);
6047
+ return Object.fromEntries(rolesByProjectId);
6048
+ }
6049
+
6050
+ function projectMemberRoles(args) {
6051
+ const result = /* @__PURE__ */ new Map;
6052
+ for (const member of args.members) {
6053
+ const {id: id, roles: roles} = member;
6054
+ if (!Array.isArray(roles) || !roles.every(isProjectMemberRole)) throw new Error(`Project member role directory response is invalid for project "${args.projectId}" and member "${id}"`);
6055
+ result.set(id, roles.map(role => role.name));
6056
+ }
6057
+ return result;
6058
+ }
6059
+
6060
+ function isProjectMemberRole(role) {
6061
+ return isRecord(role) && typeof role.name == "string";
6062
+ }
6063
+
5658
6064
  function findStage(definition, stageName) {
5659
6065
  const stage = definition.stages.find(s => s.name === stageName);
5660
6066
  if (stage === void 0) throw new Error(`Stage "${stageName}" not found in definition ${definition.name}`);
@@ -5674,6 +6080,8 @@ async function resolveStageFieldEntries(args) {
5674
6080
  tag: instance.tag,
5675
6081
  stageName: stage.name,
5676
6082
  workflowResource: instance.workflowResource,
6083
+ memberRoles: args.memberRoles,
6084
+ roleAliases: args.roleAliases,
5677
6085
  workflowFields: instance.fields ?? [],
5678
6086
  ...instance.perspective !== void 0 ? {
5679
6087
  perspective: instance.perspective
@@ -5700,6 +6108,8 @@ async function resolveActivityFieldEntries(args) {
5700
6108
  stageName: stage.name,
5701
6109
  workflowResource: instance.workflowResource,
5702
6110
  activityName: activity.name,
6111
+ memberRoles: args.memberRoles,
6112
+ roleAliases: args.roleAliases,
5703
6113
  workflowFields: instance.fields ?? [],
5704
6114
  ...instance.perspective !== void 0 ? {
5705
6115
  perspective: instance.perspective
@@ -5855,167 +6265,6 @@ function resolveMetadata(metadata, ctx) {
5855
6265
  return out;
5856
6266
  }
5857
6267
 
5858
- function userLoginProvider(user) {
5859
- return user?.provider ?? user?.loginProvider;
5860
- }
5861
-
5862
- function optionalString(value) {
5863
- return value === void 0 || typeof value == "string";
5864
- }
5865
-
5866
- function isClientProjectUser(value) {
5867
- return isRecord(value) && typeof value.id == "string" && optionalString(value.sanityUserId) && optionalString(value.displayName) && optionalString(value.email) && (value.imageUrl === null || optionalString(value.imageUrl)) && optionalString(value.provider) && optionalString(value.loginProvider);
5868
- }
5869
-
5870
- function objectProperty(value, property) {
5871
- if (!isRecord(value)) return;
5872
- const propertyValue = value[property];
5873
- return typeof propertyValue == "object" && propertyValue !== null ? propertyValue : void 0;
5874
- }
5875
-
5876
- function stringProperty(value, property) {
5877
- const propertyValue = Reflect.get(value, property);
5878
- return typeof propertyValue == "string" ? propertyValue : void 0;
5879
- }
5880
-
5881
- function apiErrorType(error) {
5882
- const response = objectProperty(error, "response"), body = objectProperty(response, "body");
5883
- if (!body) return;
5884
- const nestedError = objectProperty(body, "error");
5885
- return (nestedError ? stringProperty(nestedError, "type") : void 0) ?? stringProperty(body, "type");
5886
- }
5887
-
5888
- function isProjectUserNotFoundError(error) {
5889
- return apiErrorType(error) === "projectUserNotFoundError";
5890
- }
5891
-
5892
- const memberJoinCache = /* @__PURE__ */ new WeakMap;
5893
-
5894
- function joinCacheFor(client) {
5895
- let cache = memberJoinCache.get(client);
5896
- return cache === void 0 && (cache = /* @__PURE__ */ new Map, memberJoinCache.set(client, cache)),
5897
- cache;
5898
- }
5899
-
5900
- async function projectMemberIds(request, projectId) {
5901
- const project = await request({
5902
- uri: `/projects/${encodeURIComponent(projectId)}`
5903
- }), members = isRecord(project) ? project.members : void 0;
5904
- return Array.isArray(members) ? members.map(member => isRecord(member) ? member.id : void 0).filter(id => typeof id == "string") : [];
5905
- }
5906
-
5907
- async function resolveGlobalProjectUser(args) {
5908
- const {client: client, request: request, projectId: projectId, id: id} = args, cache = joinCacheFor(client), key = `${projectId}:${id}`, hit = cache.get(key);
5909
- if (hit !== void 0) return hit === null ? {
5910
- status: "missing"
5911
- } : {
5912
- status: "resolved",
5913
- user: hit
5914
- };
5915
- try {
5916
- await ingestMemberJoin({
5917
- request: request,
5918
- projectId: projectId,
5919
- cache: cache
5920
- });
5921
- const found = cache.get(key);
5922
- return found != null ? {
5923
- status: "resolved",
5924
- user: found
5925
- } : (cache.set(key, null), {
5926
- status: "missing"
5927
- });
5928
- } catch (cause) {
5929
- return {
5930
- status: "inaccessible",
5931
- cause: cause
5932
- };
5933
- }
5934
- }
5935
-
5936
- async function ingestMemberJoin(args) {
5937
- const {request: request, projectId: projectId, cache: cache} = args, memberIds = await projectMemberIds(request, projectId);
5938
- if (memberIds.length === 0) return;
5939
- const requested = new Set(memberIds), response = await request({
5940
- uri: `/projects/${encodeURIComponent(projectId)}/users/${memberIds.map(encodeURIComponent).join(",")}`
5941
- });
5942
- for (const row of Array.isArray(response) ? response : [ response ]) {
5943
- if (!isClientProjectUser(row) || !requested.has(row.id)) continue;
5944
- const globalId = directoryBridgeId(row.sanityUserId);
5945
- globalId !== void 0 && cache.set(`${projectId}:${globalId}`, row);
5946
- }
5947
- }
5948
-
5949
- function clientProjectUserDirectory(client, projectId) {
5950
- return {
5951
- findById: async id => {
5952
- if (!client.request) return {
5953
- status: "inaccessible",
5954
- cause: new Error("Project-user resolution requires WorkflowClient.request")
5955
- };
5956
- if (classifyPrincipalId(id).namespace === "global") return resolveGlobalProjectUser({
5957
- client: client,
5958
- request: client.request,
5959
- projectId: projectId,
5960
- id: id
5961
- });
5962
- try {
5963
- const response = await client.request({
5964
- uri: `/projects/${encodeURIComponent(projectId)}/users/${encodeURIComponent(id)}`
5965
- }), candidate = Array.isArray(response) ? response[0] : response;
5966
- return candidate == null ? {
5967
- status: "missing"
5968
- } : isClientProjectUser(candidate) ? candidate.id !== id ? {
5969
- status: "inaccessible",
5970
- cause: new Error(`Project-user response answered id "${candidate.id}", not the requested "${id}"`)
5971
- } : {
5972
- status: "resolved",
5973
- user: candidate
5974
- } : {
5975
- status: "inaccessible",
5976
- cause: new Error("Project-user response had an invalid shape")
5977
- };
5978
- } catch (cause) {
5979
- return isProjectUserNotFoundError(cause) ? {
5980
- status: "missing"
5981
- } : {
5982
- status: "inaccessible",
5983
- cause: cause
5984
- };
5985
- }
5986
- }
5987
- };
5988
- }
5989
-
5990
- function resolveClientActor(client, args) {
5991
- return resolveActor(clientProjectUserDirectory(client, args.projectId), args.actor);
5992
- }
5993
-
5994
- async function resolveActor(directory, actor) {
5995
- if (actor.kind !== "person") return {
5996
- status: "not-person",
5997
- actor: actor
5998
- };
5999
- const personActor = {
6000
- ...actor,
6001
- kind: "person"
6002
- }, lookup = await directory.findById(personActor.id);
6003
- return lookup.status === "resolved" ? {
6004
- status: "resolved",
6005
- actor: personActor,
6006
- user: lookup.user
6007
- } : lookup.status === "inaccessible" ? {
6008
- status: "inaccessible",
6009
- actor: personActor,
6010
- ...lookup.cause === void 0 ? {} : {
6011
- cause: lookup.cause
6012
- }
6013
- } : {
6014
- status: "missing",
6015
- actor: personActor
6016
- };
6017
- }
6018
-
6019
6268
  const IDENTITY_KINDS = /* @__PURE__ */ new Set([ "actor", "assignee", "assignees" ]);
6020
6269
 
6021
6270
  async function localizeGuardMetadata(args) {
@@ -6661,6 +6910,8 @@ async function buildActivityEntry({ctx: ctx, stage: stage, activity: activity, r
6661
6910
  activity: activity,
6662
6911
  now: ctx.now,
6663
6912
  refSurface: ctx.refSurface,
6913
+ memberRoles: ctx.memberRoles,
6914
+ roleAliases: ctx.definition.roleAliases,
6664
6915
  ...recordDiscard !== void 0 ? {
6665
6916
  recordDiscard: recordDiscard
6666
6917
  } : {}
@@ -6863,7 +7114,8 @@ async function spawnRow({ctx: ctx, mutation: mutation, activity: activity, actio
6863
7114
  context: context,
6864
7115
  actor: actor,
6865
7116
  now: now,
6866
- refSurface: ctx.refSurface
7117
+ refSurface: ctx.refSurface,
7118
+ memberRolesLoader: ctx.memberRolesLoader
6867
7119
  });
6868
7120
  mutation.pendingCreates.push({
6869
7121
  body: body,
@@ -7085,13 +7337,16 @@ async function resolveDefinitionRef({client: client, ref: ref, tag: tag}) {
7085
7337
  }
7086
7338
 
7087
7339
  async function prepareChildInstance(args) {
7088
- const {client: client, parent: parent, definition: definition, initialFields: initialFields, context: context, actor: actor, now: now, refSurface: refSurface} = args, childTag = parent.tag, workflowResource = parent.workflowResource, childDocId = instanceDocId(childTag), childRef = {
7340
+ const {client: client, parent: parent, definition: definition, initialFields: initialFields, context: context, actor: actor, now: now, refSurface: refSurface, memberRolesLoader: memberRolesLoader} = args, childTag = parent.tag, workflowResource = parent.workflowResource, childDocId = instanceDocId(childTag), childRef = {
7089
7341
  id: gdrFromResource(workflowResource, childDocId),
7090
7342
  type: WORKFLOW_INSTANCE_TYPE
7091
7343
  }, ancestors = [ ...parent.ancestors, {
7092
7344
  id: selfGdr(parent),
7093
7345
  type: WORKFLOW_INSTANCE_TYPE
7094
- } ], inheritedPerspective = parent.perspective, fieldDiscards = [], childFields = await resolveDeclaredFields({
7346
+ } ], inheritedPerspective = parent.perspective, fieldDiscards = [], memberRoles = await memberRolesLoader({
7347
+ workflowResource: workflowResource,
7348
+ definition: definition
7349
+ }), childFields = await resolveDeclaredFields({
7095
7350
  entryDefs: definition.fields,
7096
7351
  initialFields: initialFields,
7097
7352
  ctx: {
@@ -7102,6 +7357,8 @@ async function prepareChildInstance(args) {
7102
7357
  workflowResource: workflowResource,
7103
7358
  definitionName: definition.name,
7104
7359
  refSurface: refSurface,
7360
+ memberRoles: memberRoles,
7361
+ roleAliases: definition.roleAliases,
7105
7362
  inputProvenance: "definition",
7106
7363
  ...inheritedPerspective !== void 0 ? {
7107
7364
  perspective: inheritedPerspective
@@ -7172,6 +7429,8 @@ async function enterStage({ctx: ctx, mutation: mutation, nextStage: nextStage, a
7172
7429
  stage: nextStage,
7173
7430
  now: at,
7174
7431
  refSurface: ctx.refSurface,
7432
+ memberRoles: ctx.memberRoles,
7433
+ roleAliases: ctx.definition.roleAliases,
7175
7434
  recordDiscard: recordFieldDiscards({
7176
7435
  target: mutation.history,
7177
7436
  scope: "stage",
@@ -8009,7 +8268,9 @@ async function applyActionFire({ctx: ctx, mutation: mutation, activity: activity
8009
8268
  self: selfGdr(ctx.instance),
8010
8269
  now: ctx.now,
8011
8270
  snapshot: ctx.snapshot,
8012
- refSurface: ctx.refSurface
8271
+ refSurface: ctx.refSurface,
8272
+ memberRoles: ctx.memberRoles,
8273
+ roleAliases: ctx.definition.roleAliases
8013
8274
  });
8014
8275
  if (await queueEffects({
8015
8276
  ctx: ctx,
@@ -8192,6 +8453,8 @@ async function primeInitialStage(args) {
8192
8453
  stage: stage,
8193
8454
  now: now,
8194
8455
  refSurface: refSurface,
8456
+ memberRoles: ctx.memberRoles,
8457
+ roleAliases: ctx.definition.roleAliases,
8195
8458
  recordDiscard: recordFieldDiscards({
8196
8459
  target: discards,
8197
8460
  scope: "stage",
@@ -8251,7 +8514,7 @@ async function primeInitialStage(args) {
8251
8514
 
8252
8515
  const CASCADE_LIMIT = 100;
8253
8516
 
8254
- async function runCascadeHop({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, executionContext: executionContext, telemetry: telemetry, overlay: overlay, settlingCohorts: settlingCohorts, instance: instance}) {
8517
+ async function runCascadeHop({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, executionContext: executionContext, telemetry: telemetry, overlay: overlay, settlingCohorts: settlingCohorts, instance: instance}) {
8255
8518
  const contextOptions = {
8256
8519
  clientForGdr: clientForGdr,
8257
8520
  refSurface: refSurface,
@@ -8272,7 +8535,8 @@ async function runCascadeHop({client: client, instanceId: instanceId, actor: act
8272
8535
  } : {},
8273
8536
  ...settlingCohorts ? {
8274
8537
  settlingCohorts: settlingCohorts
8275
- } : {}
8538
+ } : {},
8539
+ memberRolesLoader: memberRolesLoader
8276
8540
  }, ctx = instance === void 0 ? await loadContext({
8277
8541
  client: client,
8278
8542
  instanceId: instanceId,
@@ -8311,7 +8575,7 @@ async function runCascadeHop({client: client, instanceId: instanceId, actor: act
8311
8575
  });
8312
8576
  }
8313
8577
 
8314
- async function cascadeAutoTransitions({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, executionContext: executionContext, telemetry: telemetry, overlay: overlay, settlingCohorts: settlingCohorts}) {
8578
+ async function cascadeAutoTransitions({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, executionContext: executionContext, telemetry: telemetry, overlay: overlay, settlingCohorts: settlingCohorts}) {
8315
8579
  let count = 0;
8316
8580
  for (;;) {
8317
8581
  const drained = await drainCondemnedChildren({
@@ -8320,6 +8584,7 @@ async function cascadeAutoTransitions({client: client, instanceId: instanceId, a
8320
8584
  actor: actor,
8321
8585
  clientForGdr: clientForGdr,
8322
8586
  refSurface: refSurface,
8587
+ memberRolesLoader: memberRolesLoader,
8323
8588
  clock: clock,
8324
8589
  executionContext: executionContext,
8325
8590
  telemetry: telemetry
@@ -8330,6 +8595,7 @@ async function cascadeAutoTransitions({client: client, instanceId: instanceId, a
8330
8595
  actor: actor,
8331
8596
  clientForGdr: clientForGdr,
8332
8597
  refSurface: refSurface,
8598
+ memberRolesLoader: memberRolesLoader,
8333
8599
  clock: clock,
8334
8600
  executionContext: executionContext,
8335
8601
  telemetry: telemetry,
@@ -8346,7 +8612,7 @@ async function cascadeAutoTransitions({client: client, instanceId: instanceId, a
8346
8612
  }
8347
8613
  }
8348
8614
 
8349
- async function drainCondemnedChildren({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, executionContext: executionContext, telemetry: telemetry, draining: draining = /* @__PURE__ */ new Set, instance: preloadedInstance}) {
8615
+ async function drainCondemnedChildren({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, executionContext: executionContext, telemetry: telemetry, draining: draining = /* @__PURE__ */ new Set, instance: preloadedInstance}) {
8350
8616
  if (draining.has(instanceId)) return {
8351
8617
  instance: preloadedInstance,
8352
8618
  drained: !1
@@ -8369,6 +8635,7 @@ async function drainCondemnedChildren({client: client, instanceId: instanceId, a
8369
8635
  actor: actor,
8370
8636
  clientForGdr: clientForGdr,
8371
8637
  refSurface: refSurface,
8638
+ memberRolesLoader: memberRolesLoader,
8372
8639
  clock: clock,
8373
8640
  executionContext: executionContext,
8374
8641
  telemetry: telemetry,
@@ -8386,7 +8653,7 @@ async function drainCondemnedChildren({client: client, instanceId: instanceId, a
8386
8653
  };
8387
8654
  }
8388
8655
 
8389
- async function settleCondemnedRow({client: client, ownerId: ownerId, row: row, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, executionContext: executionContext, telemetry: telemetry, draining: draining}) {
8656
+ async function settleCondemnedRow({client: client, ownerId: ownerId, row: row, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, executionContext: executionContext, telemetry: telemetry, draining: draining}) {
8390
8657
  const childId = toBareId(row.ref.id);
8391
8658
  try {
8392
8659
  const result = await abortInstance({
@@ -8399,6 +8666,7 @@ async function settleCondemnedRow({client: client, ownerId: ownerId, row: row, a
8399
8666
  } : {},
8400
8667
  clientForGdr: clientForGdr,
8401
8668
  refSurface: refSurface,
8669
+ memberRolesLoader: memberRolesLoader,
8402
8670
  ...clock ? {
8403
8671
  clock: clock
8404
8672
  } : {},
@@ -8416,6 +8684,7 @@ async function settleCondemnedRow({client: client, ownerId: ownerId, row: row, a
8416
8684
  actor: actor,
8417
8685
  clientForGdr: clientForGdr,
8418
8686
  refSurface: refSurface,
8687
+ memberRolesLoader: memberRolesLoader,
8419
8688
  clock: clock,
8420
8689
  executionContext: executionContext,
8421
8690
  telemetry: telemetry,
@@ -8566,7 +8835,8 @@ async function buildCascadeStepContext(args, instance) {
8566
8835
  } : {},
8567
8836
  ...args.settlingCohorts ? {
8568
8837
  settlingCohorts: args.settlingCohorts
8569
- } : {}
8838
+ } : {},
8839
+ memberRolesLoader: args.memberRolesLoader
8570
8840
  });
8571
8841
  }
8572
8842
 
@@ -8794,6 +9064,7 @@ function spawnStepArgs(ctx, args) {
8794
9064
  actor: args.actor,
8795
9065
  clientForGdr: ctx.clientForGdr,
8796
9066
  refSurface: ctx.refSurface,
9067
+ memberRolesLoader: ctx.memberRolesLoader,
8797
9068
  clock: ctx.clock,
8798
9069
  executionContext: ctx.executionContext,
8799
9070
  telemetry: ctx.telemetry,
@@ -8935,7 +9206,11 @@ function validateEffectOutputs(args) {
8935
9206
  issues.push(`"${key}" is not a declared output`);
8936
9207
  continue;
8937
9208
  }
8938
- const check = effectOutputCheck(shape, value);
9209
+ const check = effectOutputCheck({
9210
+ shape: shape,
9211
+ value: value,
9212
+ eligibility: args
9213
+ });
8939
9214
  "issues" in check ? issues.push(...check.issues.map(i => `"${key}": ${i}`)) : normalized[key] = check.output;
8940
9215
  }
8941
9216
  if (issues.length > 0) throw new EffectOutputsInvalidError({
@@ -8945,7 +9220,8 @@ function validateEffectOutputs(args) {
8945
9220
  return normalized;
8946
9221
  }
8947
9222
 
8948
- function effectOutputCheck(shape, value) {
9223
+ function effectOutputCheck(args) {
9224
+ const {shape: shape, value: value, eligibility: eligibility} = args;
8949
9225
  return parseFieldValue({
8950
9226
  entryType: shape.type,
8951
9227
  value: value,
@@ -8960,7 +9236,12 @@ function effectOutputCheck(shape, value) {
8960
9236
  } : {},
8961
9237
  ...shape.validation !== void 0 ? {
8962
9238
  validation: shape.validation
8963
- } : {}
9239
+ } : {},
9240
+ ...shape.roles !== void 0 ? {
9241
+ roles: shape.roles
9242
+ } : {},
9243
+ memberRoles: eligibility.memberRoles,
9244
+ roleAliases: eligibility.roleAliases
8964
9245
  });
8965
9246
  }
8966
9247
 
@@ -8983,7 +9264,7 @@ function requirePendingEffect(instance, effectKey) {
8983
9264
  });
8984
9265
  }
8985
9266
 
8986
- function validateCompletionInput({pending: pending, definition: definition, status: status, ops: ops, outputs: outputs}) {
9267
+ function validateCompletionInput({pending: pending, definition: definition, status: status, ops: ops, outputs: outputs, memberRoles: memberRoles, roleAliases: roleAliases}) {
8987
9268
  if (status === "failed" && ops !== void 0 && ops.length > 0) throw new EffectOpsInvalidError({
8988
9269
  effect: pending.name,
8989
9270
  issues: [ "ops cannot accompany a failed completion — field.set the outcome on a done completion instead" ]
@@ -8995,7 +9276,9 @@ function validateCompletionInput({pending: pending, definition: definition, stat
8995
9276
  const normalizedOutputs = outputs !== void 0 ? validateEffectOutputs({
8996
9277
  outputs: outputs,
8997
9278
  declared: findEffect(definition, pending.name)?.outputs ?? [],
8998
- effectName: pending.name
9279
+ effectName: pending.name,
9280
+ memberRoles: memberRoles,
9281
+ roleAliases: roleAliases
8999
9282
  }) : void 0;
9000
9283
  return {
9001
9284
  ops: ops !== void 0 ? validateEffectOps(ops, pending.name) : [],
@@ -9014,7 +9297,9 @@ async function commitCompleteEffect({ctx: ctx, effectKey: effectKey, status: sta
9014
9297
  definition: ctx.definition,
9015
9298
  status: status,
9016
9299
  ops: ops,
9017
- outputs: outputs
9300
+ outputs: outputs,
9301
+ memberRoles: ctx.memberRoles,
9302
+ roleAliases: ctx.definition.roleAliases
9018
9303
  }), mutation = startMutation(ctx.instance);
9019
9304
  recordProcessedRequest({
9020
9305
  mutation: mutation,
@@ -9045,7 +9330,9 @@ async function commitCompleteEffect({ctx: ctx, effectKey: effectKey, status: sta
9045
9330
  self: selfGdr(ctx.instance),
9046
9331
  now: ranAt,
9047
9332
  snapshot: ctx.snapshot,
9048
- refSurface: ctx.refSurface
9333
+ refSurface: ctx.refSurface,
9334
+ memberRoles: ctx.memberRoles,
9335
+ roleAliases: ctx.definition.roleAliases
9049
9336
  }), needsGuardRefresh = wroteEffectOutputs || ranOps.some(isFieldOp);
9050
9337
  return await persistThenMaybeRefresh({
9051
9338
  ctx: ctx,
@@ -9214,7 +9501,9 @@ async function commitReport({ctx: ctx, effectKey: effectKey, claimToken: claimTo
9214
9501
  self: selfGdr(ctx.instance),
9215
9502
  now: ctx.now,
9216
9503
  snapshot: ctx.snapshot,
9217
- refSurface: ctx.refSurface
9504
+ refSurface: ctx.refSurface,
9505
+ memberRoles: ctx.memberRoles,
9506
+ roleAliases: ctx.definition.roleAliases
9218
9507
  }), await persistThenMaybeRefresh({
9219
9508
  ctx: ctx,
9220
9509
  mutation: mutation,
@@ -9709,6 +9998,12 @@ async function evaluateEditableFields(args) {
9709
9998
  ...site.validation !== void 0 ? {
9710
9999
  validation: site.validation
9711
10000
  } : {},
10001
+ ...site.roles !== void 0 ? {
10002
+ roles: site.roles,
10003
+ ...definition.roleAliases !== void 0 ? {
10004
+ roleAliases: definition.roleAliases
10005
+ } : {}
10006
+ } : {},
9712
10007
  value: value,
9713
10008
  editable: reason === void 0,
9714
10009
  ...reason !== void 0 ? {
@@ -10059,23 +10354,63 @@ function idsArm(filter, params) {
10059
10354
  }
10060
10355
  }
10061
10356
 
10062
- function instancesQuery(args) {
10063
- const {tag: tag, filter: filter = {}} = args;
10064
- if (validateTag(tag), filter.limit !== void 0 && (!Number.isInteger(filter.limit) || filter.limit <= 0)) throw new ContractViolationError(`instancesQuery: limit must be a positive integer; got ${JSON.stringify(filter.limit)}`);
10065
- const conditions = [ `_type == "${WORKFLOW_INSTANCE_TYPE}"`, tagScopeFilter() ], params = {
10066
- tag: tag
10067
- };
10357
+ function beforeArm(filter, params) {
10358
+ const before = filter.before;
10359
+ if (before !== void 0) {
10360
+ if (filter.limit === void 0) throw new ContractViolationError("instancesQuery: `before` requires `limit` — a cursor pages the newest-first sliced read");
10361
+ if (before.id === "" || before.startedAt === "") throw new ContractViolationError(`instancesQuery: \`before\` needs a non-empty id and startedAt; got ${JSON.stringify(before)}`);
10362
+ return params.beforeStartedAt = before.startedAt, params.beforeId = before.id, "(startedAt < $beforeStartedAt || (startedAt == $beforeStartedAt && _id > $beforeId))";
10363
+ }
10364
+ }
10365
+
10366
+ function compiledConditions(filter, params) {
10367
+ if (filter.limit !== void 0 && (!Number.isInteger(filter.limit) || filter.limit <= 0)) throw new ContractViolationError(`instancesQuery: limit must be a positive integer; got ${JSON.stringify(filter.limit)}`);
10368
+ const conditions = [ `_type == "${WORKFLOW_INSTANCE_TYPE}"`, tagScopeFilter() ];
10068
10369
  filter.includeCompleted !== !0 && conditions.push(inFlightFilter()), filter.definition !== void 0 && (conditions.push("definition == $definition"),
10069
10370
  params.definition = filter.definition), filter.stage !== void 0 && (conditions.push("currentStage == $stage"),
10070
10371
  params.stage = filter.stage);
10372
+ const cursor = beforeArm(filter, params);
10373
+ cursor !== void 0 && conditions.push(cursor);
10071
10374
  const arms = [ documentArm(filter, params), idsArm(filter, params) ].filter(arm => arm !== void 0);
10072
- arms.length > 0 && conditions.push(`(${arms.join(" || ")})`);
10073
- const body = `*[${conditions.join(" && ")}]`;
10074
- return filter.limit !== void 0 ? {
10075
- query: `${body} | order(startedAt desc) [0...${filter.limit}]`,
10375
+ return arms.length > 0 && conditions.push(`(${arms.join(" || ")})`), conditions;
10376
+ }
10377
+
10378
+ function orderedSlice(filter) {
10379
+ return filter.limit !== void 0 ? ` | order(startedAt desc, _id asc) [0...${filter.limit}]` : " | order(startedAt asc, _id asc)";
10380
+ }
10381
+
10382
+ function instancesQuery(args) {
10383
+ const {tag: tag, filter: filter = {}} = args;
10384
+ validateTag(tag);
10385
+ const params = {
10386
+ tag: tag
10387
+ };
10388
+ return {
10389
+ query: `*[${compiledConditions(filter, params).join(" && ")}]${orderedSlice(filter)}`,
10076
10390
  params: params
10077
- } : {
10078
- query: `${body} | order(startedAt asc)`,
10391
+ };
10392
+ }
10393
+
10394
+ function instanceChangesQuery(args) {
10395
+ return validateTag(args.tag), {
10396
+ query: `*[_type == "${WORKFLOW_INSTANCE_TYPE}" && ${tagScopeFilter()}]`,
10397
+ params: {
10398
+ tag: args.tag
10399
+ }
10400
+ };
10401
+ }
10402
+
10403
+ const PREVIEW_FIELD_TYPES = [ "actor", "assignee", "assignees", "date", "datetime", "doc.ref", "doc.refs", "dueDate", "dueDatetime", "release.ref", "subject" ], PREVIEW_PROJECTION = `{\n _id, _type, modelVersion, minReaderModel, workflowResource, definition, pinnedVersion,\n currentStage, startedAt, completedAt, abortedAt, perspective, ancestors,\n "fields": fields[_type in $previewFieldTypes],\n "stages": stages[!defined(exitedAt) && name == ^.currentStage]{\n _key, name, enteredAt,\n "fields": fields[_type in $previewFieldTypes],\n "activities": activities[]{\n _key, name, status, completedBy,\n "fields": fields[_type in $previewFieldTypes]\n }\n },\n "claimedEffects": pendingEffects[defined(claim)]{name, title},\n "failedEffects": effectHistory[status == "failed"]{name, title}\n}`.replaceAll(/\s+/g, " ").trim();
10404
+
10405
+ function instancePreviewsQuery(args) {
10406
+ const {tag: tag, filter: filter = {}} = args;
10407
+ validateTag(tag);
10408
+ const params = {
10409
+ tag: tag,
10410
+ previewFieldTypes: PREVIEW_FIELD_TYPES
10411
+ };
10412
+ return {
10413
+ query: `*[${compiledConditions(filter, params).join(" && ")}]${orderedSlice(filter)} ${PREVIEW_PROJECTION}`,
10079
10414
  params: params
10080
10415
  };
10081
10416
  }
@@ -10260,6 +10595,11 @@ function hashDefinitionContent(def) {
10260
10595
  }
10261
10596
 
10262
10597
  function planDefinitionDeploy({def: def, latest: latest, target: target}) {
10598
+ assertRoleConstrainedAssignmentResource({
10599
+ context: "workflow.deployDefinitions",
10600
+ definition: def,
10601
+ workflowResource: target.workflowResource
10602
+ });
10263
10603
  const expanded = expandResourceAliases(def, target.resourceAliases), contentHash = hashDefinitionContent(expanded), unchanged = latest !== void 0 && latest.contentHash === contentHash, version = unchanged ? latest.version : (latest?.version ?? 0) + 1, docId = definitionDocId({
10264
10604
  tag: target.tag,
10265
10605
  definition: expanded.name,
@@ -10452,7 +10792,9 @@ async function commitEdit({ctx: ctx, target: target, mode: mode, value: value, r
10452
10792
  self: selfGdr(ctx.instance),
10453
10793
  now: ctx.now,
10454
10794
  snapshot: ctx.snapshot,
10455
- refSurface: ctx.refSurface
10795
+ refSurface: ctx.refSurface,
10796
+ memberRoles: ctx.memberRoles,
10797
+ roleAliases: ctx.definition.roleAliases
10456
10798
  });
10457
10799
  return await persistThenMaybeRefresh({
10458
10800
  ctx: ctx,
@@ -10551,6 +10893,7 @@ async function resolveOperationContext(args) {
10551
10893
  return {
10552
10894
  access: access,
10553
10895
  actor: access.actor,
10896
+ memberRolesLoader: createAssignmentMemberRolesLoader(args.client),
10554
10897
  clientForGdr: buildClientForGdr({
10555
10898
  client: args.client,
10556
10899
  workflowResource: args.workflowResource,
@@ -10583,6 +10926,7 @@ async function runCommitVerb(params) {
10583
10926
  actor: context.actor,
10584
10927
  clientForGdr: context.clientForGdr,
10585
10928
  refSurface: context.refSurface,
10929
+ memberRolesLoader: context.memberRolesLoader,
10586
10930
  clock: clock,
10587
10931
  executionContext: args.executionContext,
10588
10932
  telemetry: args.telemetry,
@@ -10607,7 +10951,7 @@ function requestRecordFor(args) {
10607
10951
  }
10608
10952
 
10609
10953
  async function runDeduped(args) {
10610
- const {client: client, tag: tag, instanceId: instanceId, record: record, before: before, now: now, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, run: run} = args, {clock: clock, executionContext: executionContext, telemetry: telemetry} = args, replay = async () => {
10954
+ const {client: client, tag: tag, instanceId: instanceId, record: record, before: before, now: now, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, run: run} = args, {clock: clock, executionContext: executionContext, telemetry: telemetry} = args, replay = async () => {
10611
10955
  const pre = await reload({
10612
10956
  client: client,
10613
10957
  instanceId: instanceId,
@@ -10619,6 +10963,7 @@ async function runDeduped(args) {
10619
10963
  actor: actor,
10620
10964
  clientForGdr: clientForGdr,
10621
10965
  refSurface: refSurface,
10966
+ memberRolesLoader: memberRolesLoader,
10622
10967
  clock: clock,
10623
10968
  executionContext: executionContext,
10624
10969
  telemetry: telemetry
@@ -10642,13 +10987,14 @@ async function runDeduped(args) {
10642
10987
  }
10643
10988
  }
10644
10989
 
10645
- async function cascade({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, executionContext: executionContext, telemetry: telemetry, overlay: overlay}) {
10990
+ async function cascade({client: client, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, executionContext: executionContext, telemetry: telemetry, overlay: overlay}) {
10646
10991
  const count = await cascadeAutoTransitions({
10647
10992
  client: client,
10648
10993
  instanceId: instanceId,
10649
10994
  actor: actor,
10650
10995
  clientForGdr: clientForGdr,
10651
10996
  refSurface: refSurface,
10997
+ memberRolesLoader: memberRolesLoader,
10652
10998
  ...clock !== void 0 ? {
10653
10999
  clock: clock
10654
11000
  } : {},
@@ -10668,6 +11014,7 @@ async function cascade({client: client, instanceId: instanceId, actor: actor, cl
10668
11014
  actor: actor,
10669
11015
  clientForGdr: clientForGdr,
10670
11016
  refSurface: refSurface,
11017
+ memberRolesLoader: memberRolesLoader,
10671
11018
  ...clock !== void 0 ? {
10672
11019
  clock: clock
10673
11020
  } : {},
@@ -10681,7 +11028,7 @@ async function cascade({client: client, instanceId: instanceId, actor: actor, cl
10681
11028
  }
10682
11029
 
10683
11030
  async function cascadeAndReload(args) {
10684
- const {client: client, tag: tag, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock} = args;
11031
+ const {client: client, tag: tag, instanceId: instanceId, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock} = args;
10685
11032
  return {
10686
11033
  cascaded: await cascade({
10687
11034
  client: client,
@@ -10689,6 +11036,7 @@ async function cascadeAndReload(args) {
10689
11036
  actor: actor,
10690
11037
  clientForGdr: clientForGdr,
10691
11038
  refSurface: refSurface,
11039
+ memberRolesLoader: memberRolesLoader,
10692
11040
  clock: clock,
10693
11041
  ...args.executionContext !== void 0 ? {
10694
11042
  executionContext: args.executionContext
@@ -10712,6 +11060,7 @@ async function settleStart(args) {
10712
11060
  actor: args.actor,
10713
11061
  clientForGdr: args.clientForGdr,
10714
11062
  refSurface: args.refSurface,
11063
+ memberRolesLoader: args.memberRolesLoader,
10715
11064
  clock: args.clock,
10716
11065
  ...args.executionContext !== void 0 ? {
10717
11066
  executionContext: args.executionContext
@@ -10754,31 +11103,20 @@ function resumeMismatch(args) {
10754
11103
  }
10755
11104
 
10756
11105
  async function resumeStart(args) {
10757
- const {existing: existing} = args, mismatch = resumeMismatch({
11106
+ const {existing: existing, definition: definition, version: version, initialFieldCount: initialFieldCount, ...settlementArgs} = args, mismatch = resumeMismatch({
10758
11107
  existing: existing,
10759
- definition: args.definition,
10760
- version: args.version
11108
+ definition: definition,
11109
+ version: version
10761
11110
  });
10762
11111
  if (mismatch !== void 0) throw new ContractViolationError(`startInstance: instanceId "${existing._id}" already exists and ${mismatch}. A supplied instanceId is start's idempotency key — reuse one only to retry the same start.`);
10763
11112
  if (existing.stages.length === 0 && terminalState(existing) !== "in-flight") throw new ContractViolationError(`startInstance: instanceId "${existing._id}" belongs to a start that was discarded (aborted before it finished starting) — mint a new id to start again.`);
10764
11113
  const completesStart = isUnprimed(existing), emitStarted = () => resolveTelemetry(args.telemetry).log(WorkflowInstanceStarted, instanceStartedDataFor({
10765
11114
  instance: existing,
10766
- initialFieldCount: args.initialFieldCount,
11115
+ initialFieldCount: initialFieldCount,
10767
11116
  viaSpawn: !1
10768
11117
  })), cascaded = await settleStart({
10769
- client: args.client,
10770
- tag: args.tag,
11118
+ ...settlementArgs,
10771
11119
  instanceId: existing._id,
10772
- actor: args.actor,
10773
- clientForGdr: args.clientForGdr,
10774
- refSurface: args.refSurface,
10775
- clock: args.clock,
10776
- ...args.executionContext !== void 0 ? {
10777
- executionContext: args.executionContext
10778
- } : {},
10779
- ...args.telemetry !== void 0 ? {
10780
- telemetry: args.telemetry
10781
- } : {},
10782
11120
  ...completesStart ? {
10783
11121
  emitStarted: emitStarted
10784
11122
  } : {}
@@ -10794,7 +11132,7 @@ async function resumeStart(args) {
10794
11132
  };
10795
11133
  }
10796
11134
 
10797
- function engineOptionsForActor({actor: actor, clock: clock, clientForGdr: clientForGdr, refSurface: refSurface, executionContext: executionContext, telemetry: telemetry}) {
11135
+ function engineOptionsForActor({actor: actor, clock: clock, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, executionContext: executionContext, telemetry: telemetry}) {
10798
11136
  return {
10799
11137
  ...actor !== void 0 ? {
10800
11138
  actor: actor
@@ -10802,6 +11140,7 @@ function engineOptionsForActor({actor: actor, clock: clock, clientForGdr: client
10802
11140
  clock: clock,
10803
11141
  clientForGdr: clientForGdr,
10804
11142
  refSurface: refSurface,
11143
+ memberRolesLoader: memberRolesLoader,
10805
11144
  ...executionContext !== void 0 ? {
10806
11145
  executionContext: executionContext
10807
11146
  } : {},
@@ -10812,7 +11151,7 @@ function engineOptionsForActor({actor: actor, clock: clock, clientForGdr: client
10812
11151
  }
10813
11152
 
10814
11153
  async function abortAndPropagate(args) {
10815
- const {client: client, instanceId: instanceId, reason: reason, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, executionContext: executionContext, telemetry: telemetry, requestRecord: requestRecord} = args, result = await abortInstance({
11154
+ const {client: client, instanceId: instanceId, reason: reason, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, executionContext: executionContext, telemetry: telemetry, requestRecord: requestRecord} = args, result = await abortInstance({
10816
11155
  client: client,
10817
11156
  instanceId: instanceId,
10818
11157
  ...reason !== void 0 ? {
@@ -10826,6 +11165,7 @@ async function abortAndPropagate(args) {
10826
11165
  clock: clock,
10827
11166
  clientForGdr: clientForGdr,
10828
11167
  refSurface: refSurface,
11168
+ memberRolesLoader: memberRolesLoader,
10829
11169
  executionContext: executionContext,
10830
11170
  telemetry: telemetry
10831
11171
  })
@@ -10835,6 +11175,7 @@ async function abortAndPropagate(args) {
10835
11175
  actor: actor,
10836
11176
  clientForGdr: clientForGdr,
10837
11177
  refSurface: refSurface,
11178
+ memberRolesLoader: memberRolesLoader,
10838
11179
  clock: clock,
10839
11180
  ...executionContext !== void 0 ? {
10840
11181
  executionContext: executionContext
@@ -10852,6 +11193,7 @@ async function abortAndPropagate(args) {
10852
11193
  actor: actor,
10853
11194
  clientForGdr: clientForGdr,
10854
11195
  refSurface: refSurface,
11196
+ memberRolesLoader: memberRolesLoader,
10855
11197
  clock: clock,
10856
11198
  ...executionContext !== void 0 ? {
10857
11199
  executionContext: executionContext
@@ -10893,6 +11235,7 @@ async function dispatchGatedWrite(args) {
10893
11235
  actor: args.actor,
10894
11236
  clientForGdr: args.clientForGdr,
10895
11237
  refSurface: args.refSurface,
11238
+ memberRolesLoader: args.memberRolesLoader,
10896
11239
  clock: args.clock,
10897
11240
  executionContext: args.executionContext,
10898
11241
  telemetry: args.telemetry
@@ -10968,6 +11311,7 @@ function buildEngineCallOptions(args) {
10968
11311
  actor: args.actor,
10969
11312
  clientForGdr: args.clientForGdr,
10970
11313
  refSurface: args.refSurface,
11314
+ memberRolesLoader: args.memberRolesLoader,
10971
11315
  ...args.localPrincipalId !== void 0 ? {
10972
11316
  localPrincipalId: args.localPrincipalId
10973
11317
  } : {},
@@ -11007,7 +11351,7 @@ async function applyAction(args) {
11007
11351
  }
11008
11352
 
11009
11353
  async function deleteDefinition(args) {
11010
- const {client: client, tag: tag, definition: definition, version: version, cascade: cascade2, reason: reason, executionContext: executionContext, telemetry: telemetry} = args, {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface} = await resolveOperationContext(args), clock = args.clock ?? wallClock, versions = await loadDefinitionVersionsOrThrow({
11354
+ const {client: client, tag: tag, definition: definition, version: version, cascade: cascade2, reason: reason, executionContext: executionContext, telemetry: telemetry} = args, {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader} = await resolveOperationContext(args), clock = args.clock ?? wallClock, versions = await loadDefinitionVersionsOrThrow({
11011
11355
  client: client,
11012
11356
  definition: definition,
11013
11357
  tag: tag
@@ -11046,6 +11390,7 @@ async function deleteDefinition(args) {
11046
11390
  actor: actor,
11047
11391
  clientForGdr: clientForGdr,
11048
11392
  refSurface: refSurface,
11393
+ memberRolesLoader: memberRolesLoader,
11049
11394
  clock: clock,
11050
11395
  executionContext: executionContext,
11051
11396
  telemetry: telemetry
@@ -11104,6 +11449,7 @@ async function abortInstances(args) {
11104
11449
  actor: actor,
11105
11450
  clientForGdr: clientForGdr,
11106
11451
  refSurface: args.refSurface,
11452
+ memberRolesLoader: args.memberRolesLoader,
11107
11453
  clock: clock,
11108
11454
  ...executionContext !== void 0 ? {
11109
11455
  executionContext: executionContext
@@ -11136,11 +11482,12 @@ async function fetchStartSlice(args) {
11136
11482
 
11137
11483
  const workflow = {
11138
11484
  deployDefinitions: async rawArgs => {
11139
- assertReaderModelAcknowledgement(rawArgs.expectedMinReaderModel);
11140
- const args = taggedScope(rawArgs, REQUEST_TAG.deploy), {client: client, tag: tag, resourceAliases: resourceAliases} = args;
11485
+ const args = taggedScope(rawArgs, REQUEST_TAG.deploy), {client: client, tag: tag, workflowResource: workflowResource, resourceAliases: resourceAliases} = args;
11141
11486
  validateTag(tag);
11142
11487
  const definitions = args.definitions.map(def => parseDefinitionInput(def, "workflow.deployDefinitions"));
11143
- definitions.forEach(validateDefinition);
11488
+ definitions.forEach(validateDefinition), assertReaderModelAcknowledgement(args.expectedMinReaderModel, {
11489
+ requiredMinReaderModel: requiredDefinitionReaderModel(definitions)
11490
+ });
11144
11491
  const ordered = await sortByDependencies({
11145
11492
  client: client,
11146
11493
  definitions: definitions,
@@ -11159,6 +11506,7 @@ const workflow = {
11159
11506
  latest: latest,
11160
11507
  target: {
11161
11508
  tag: tag,
11509
+ workflowResource: workflowResource,
11162
11510
  ...resourceAliases !== void 0 ? {
11163
11511
  resourceAliases: resourceAliases
11164
11512
  } : {}
@@ -11209,7 +11557,7 @@ const workflow = {
11209
11557
  }), result;
11210
11558
  },
11211
11559
  startInstance: async rawArgs => {
11212
- const args = taggedScope(rawArgs, REQUEST_TAG.start), {client: client, tag: tag, definition: definitionName, version: version, initialFields: initialFields, instanceId: instanceId, executionContext: executionContext} = args, operationContext = await resolveOperationContext(args), {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface} = operationContext, clock = args.clock ?? wallClock, seedFields = initialFields ?? [], existing = instanceId !== void 0 ? await getInstanceDocument(client, instanceId) : void 0;
11560
+ const args = taggedScope(rawArgs, REQUEST_TAG.start), {client: client, tag: tag, definition: definitionName, version: version, initialFields: initialFields, instanceId: instanceId, executionContext: executionContext} = args, operationContext = await resolveOperationContext(args), {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader} = operationContext, clock = args.clock ?? wallClock, seedFields = initialFields ?? [], existing = instanceId !== void 0 ? await getInstanceDocument(client, instanceId) : void 0;
11213
11561
  return existing !== void 0 && existing.tag === tag ? resumeStart({
11214
11562
  client: client,
11215
11563
  tag: tag,
@@ -11220,6 +11568,7 @@ const workflow = {
11220
11568
  actor: actor,
11221
11569
  clientForGdr: clientForGdr,
11222
11570
  refSurface: refSurface,
11571
+ memberRolesLoader: memberRolesLoader,
11223
11572
  clock: clock,
11224
11573
  ...executionContext !== void 0 ? {
11225
11574
  executionContext: executionContext
@@ -11239,7 +11588,7 @@ const workflow = {
11239
11588
  return runCommitVerb({
11240
11589
  args: args,
11241
11590
  op: "fireAction",
11242
- run: async ({access: access, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, record: record, before: before}) => {
11591
+ run: async ({access: access, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, record: record, before: before}) => {
11243
11592
  if (findCurrentActivityEntry(before, activity) === void 0 && idempotent === !0) return {
11244
11593
  instance: before,
11245
11594
  cascaded: 0,
@@ -11253,6 +11602,7 @@ const workflow = {
11253
11602
  actor: actor,
11254
11603
  clientForGdr: clientForGdr,
11255
11604
  refSurface: refSurface,
11605
+ memberRolesLoader: memberRolesLoader,
11256
11606
  clock: clock,
11257
11607
  before: before,
11258
11608
  ...grantsFromPath !== void 0 ? {
@@ -11286,6 +11636,7 @@ const workflow = {
11286
11636
  clock: clock,
11287
11637
  clientForGdr: clientForGdr,
11288
11638
  refSurface: refSurface,
11639
+ memberRolesLoader: memberRolesLoader,
11289
11640
  ...executionContext !== void 0 ? {
11290
11641
  executionContext: executionContext
11291
11642
  } : {},
@@ -11314,7 +11665,7 @@ const workflow = {
11314
11665
  return runCommitVerb({
11315
11666
  args: args,
11316
11667
  op: "editField",
11317
- run: async ({access: access, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, record: record, before: before}) => {
11668
+ run: async ({access: access, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, record: record, before: before}) => {
11318
11669
  const result = await dispatchGatedWrite({
11319
11670
  client: client,
11320
11671
  tag: tag,
@@ -11323,6 +11674,7 @@ const workflow = {
11323
11674
  actor: actor,
11324
11675
  clientForGdr: clientForGdr,
11325
11676
  refSurface: refSurface,
11677
+ memberRolesLoader: memberRolesLoader,
11326
11678
  clock: clock,
11327
11679
  before: before,
11328
11680
  ...grantsFromPath !== void 0 ? {
@@ -11357,6 +11709,7 @@ const workflow = {
11357
11709
  clock: clock,
11358
11710
  clientForGdr: clientForGdr,
11359
11711
  refSurface: refSurface,
11712
+ memberRolesLoader: memberRolesLoader,
11360
11713
  ...executionContext !== void 0 ? {
11361
11714
  executionContext: executionContext
11362
11715
  } : {},
@@ -11377,7 +11730,7 @@ const workflow = {
11377
11730
  });
11378
11731
  },
11379
11732
  completeEffect: async rawArgs => {
11380
- const args = taggedScope(rawArgs, REQUEST_TAG.completeEffect), {client: client, tag: tag, instanceId: instanceId, effectKey: effectKey, status: status, outputs: outputs, ops: ops, detail: detail, error: error, durationMs: durationMs, executionContext: executionContext} = args, {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface} = await resolveOperationContext(args), clock = args.clock ?? wallClock, record = requestRecordFor({
11733
+ const args = taggedScope(rawArgs, REQUEST_TAG.completeEffect), {client: client, tag: tag, instanceId: instanceId, effectKey: effectKey, status: status, outputs: outputs, ops: ops, detail: detail, error: error, durationMs: durationMs, executionContext: executionContext} = args, operationContext = await resolveOperationContext(args), clock = args.clock ?? wallClock, record = requestRecordFor({
11381
11734
  idempotencyKey: args.idempotencyKey,
11382
11735
  op: "completeEffect",
11383
11736
  idempotencyTtlMs: args.idempotencyTtlMs
@@ -11388,9 +11741,7 @@ const workflow = {
11388
11741
  instanceId: instanceId,
11389
11742
  record: record,
11390
11743
  now: clock(),
11391
- actor: actor,
11392
- clientForGdr: clientForGdr,
11393
- refSurface: refSurface,
11744
+ ...operationContext,
11394
11745
  clock: clock,
11395
11746
  executionContext: executionContext,
11396
11747
  telemetry: args.telemetry,
@@ -11419,10 +11770,8 @@ const workflow = {
11419
11770
  requestRecord: record
11420
11771
  } : {},
11421
11772
  options: engineOptionsForActor({
11422
- actor: actor,
11773
+ ...operationContext,
11423
11774
  clock: clock,
11424
- clientForGdr: clientForGdr,
11425
- refSurface: refSurface,
11426
11775
  executionContext: executionContext,
11427
11776
  telemetry: args.telemetry
11428
11777
  })
@@ -11430,9 +11779,7 @@ const workflow = {
11430
11779
  client: client,
11431
11780
  tag: tag,
11432
11781
  instanceId: instanceId,
11433
- actor: actor,
11434
- clientForGdr: clientForGdr,
11435
- refSurface: refSurface,
11782
+ ...operationContext,
11436
11783
  clock: clock,
11437
11784
  executionContext: executionContext,
11438
11785
  telemetry: args.telemetry
@@ -11453,7 +11800,7 @@ const workflow = {
11453
11800
  });
11454
11801
  },
11455
11802
  commitEffectOps: async rawArgs => {
11456
- const args = taggedScope(rawArgs, REQUEST_TAG.commitEffectOps), {client: client, tag: tag, instanceId: instanceId, effectKey: effectKey, claimToken: claimToken, ops: ops, executionContext: executionContext} = args, {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface} = await resolveOperationContext(args), clock = args.clock ?? wallClock, record = requestRecordFor({
11803
+ const args = taggedScope(rawArgs, REQUEST_TAG.commitEffectOps), {client: client, tag: tag, instanceId: instanceId, effectKey: effectKey, claimToken: claimToken, ops: ops, executionContext: executionContext} = args, operationContext = await resolveOperationContext(args), clock = args.clock ?? wallClock, record = requestRecordFor({
11457
11804
  idempotencyKey: args.idempotencyKey,
11458
11805
  op: "commitEffectOps",
11459
11806
  idempotencyTtlMs: args.idempotencyTtlMs
@@ -11465,9 +11812,7 @@ const workflow = {
11465
11812
  instanceId: instanceId,
11466
11813
  record: record,
11467
11814
  now: clock(),
11468
- actor: actor,
11469
- clientForGdr: clientForGdr,
11470
- refSurface: refSurface,
11815
+ ...operationContext,
11471
11816
  clock: clock,
11472
11817
  executionContext: executionContext,
11473
11818
  telemetry: args.telemetry,
@@ -11481,10 +11826,8 @@ const workflow = {
11481
11826
  requestRecord: record,
11482
11827
  leaseMs: args.leaseMs ?? DEFAULT_EFFECT_LEASE_MS,
11483
11828
  options: engineOptionsForActor({
11484
- actor: actor,
11829
+ ...operationContext,
11485
11830
  clock: clock,
11486
- clientForGdr: clientForGdr,
11487
- refSurface: refSurface,
11488
11831
  executionContext: executionContext,
11489
11832
  telemetry: args.telemetry
11490
11833
  })
@@ -11492,9 +11835,7 @@ const workflow = {
11492
11835
  client: client,
11493
11836
  tag: tag,
11494
11837
  instanceId: instanceId,
11495
- actor: actor,
11496
- clientForGdr: clientForGdr,
11497
- refSurface: refSurface,
11838
+ ...operationContext,
11498
11839
  clock: clock,
11499
11840
  executionContext: executionContext,
11500
11841
  telemetry: args.telemetry
@@ -11513,7 +11854,7 @@ const workflow = {
11513
11854
  });
11514
11855
  },
11515
11856
  tick: async rawArgs => {
11516
- const args = taggedScope(rawArgs, REQUEST_TAG.tick), {client: client, tag: tag, instanceId: instanceId, executionContext: executionContext} = args, {access: access, actor: actor, clientForGdr: clientForGdr, refSurface: refSurface} = await resolveOperationContext(args), clock = args.clock ?? wallClock, current = await reload({
11857
+ const args = taggedScope(rawArgs, REQUEST_TAG.tick), {client: client, tag: tag, instanceId: instanceId, executionContext: executionContext} = args, operationContext = await resolveOperationContext(args), {access: access} = operationContext, clock = args.clock ?? wallClock, current = await reload({
11517
11858
  client: client,
11518
11859
  instanceId: instanceId,
11519
11860
  tag: tag
@@ -11527,9 +11868,7 @@ const workflow = {
11527
11868
  client: client,
11528
11869
  tag: tag,
11529
11870
  instanceId: instanceId,
11530
- actor: actor,
11531
- clientForGdr: clientForGdr,
11532
- refSurface: refSurface,
11871
+ ...operationContext,
11533
11872
  clock: clock,
11534
11873
  executionContext: executionContext,
11535
11874
  telemetry: args.telemetry
@@ -11549,7 +11888,7 @@ const workflow = {
11549
11888
  return runCommitVerb({
11550
11889
  args: args,
11551
11890
  op: "setStage",
11552
- run: async ({actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, record: record, before: before}) => {
11891
+ run: async ({actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, record: record, before: before}) => {
11553
11892
  const result = await setStage({
11554
11893
  client: client,
11555
11894
  instanceId: instanceId,
@@ -11565,6 +11904,7 @@ const workflow = {
11565
11904
  clock: clock,
11566
11905
  clientForGdr: clientForGdr,
11567
11906
  refSurface: refSurface,
11907
+ memberRolesLoader: memberRolesLoader,
11568
11908
  executionContext: executionContext,
11569
11909
  telemetry: args.telemetry
11570
11910
  })
@@ -11574,6 +11914,7 @@ const workflow = {
11574
11914
  actor: actor,
11575
11915
  clientForGdr: clientForGdr,
11576
11916
  refSurface: refSurface,
11917
+ memberRolesLoader: memberRolesLoader,
11577
11918
  clock: clock,
11578
11919
  ...executionContext !== void 0 ? {
11579
11920
  executionContext: executionContext
@@ -11603,7 +11944,7 @@ const workflow = {
11603
11944
  return runCommitVerb({
11604
11945
  args: args,
11605
11946
  op: "abortInstance",
11606
- run: async ({actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, record: record, before: before}) => {
11947
+ run: async ({actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, record: record, before: before}) => {
11607
11948
  const changed = await abortAndPropagate({
11608
11949
  client: client,
11609
11950
  instanceId: instanceId,
@@ -11611,6 +11952,7 @@ const workflow = {
11611
11952
  actor: actor,
11612
11953
  clientForGdr: clientForGdr,
11613
11954
  refSurface: refSurface,
11955
+ memberRolesLoader: memberRolesLoader,
11614
11956
  clock: clock,
11615
11957
  ...executionContext !== void 0 ? {
11616
11958
  executionContext: executionContext
@@ -11644,7 +11986,7 @@ const workflow = {
11644
11986
  return runCommitVerb({
11645
11987
  args: args,
11646
11988
  op: "resetActivity",
11647
- run: async ({actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, clock: clock, record: record, before: before}) => {
11989
+ run: async ({actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader, clock: clock, record: record, before: before}) => {
11648
11990
  const result = await resetActivity({
11649
11991
  client: client,
11650
11992
  instanceId: instanceId,
@@ -11658,6 +12000,7 @@ const workflow = {
11658
12000
  clock: clock,
11659
12001
  clientForGdr: clientForGdr,
11660
12002
  refSurface: refSurface,
12003
+ memberRolesLoader: memberRolesLoader,
11661
12004
  executionContext: executionContext,
11662
12005
  telemetry: args.telemetry
11663
12006
  })
@@ -11667,6 +12010,7 @@ const workflow = {
11667
12010
  actor: actor,
11668
12011
  clientForGdr: clientForGdr,
11669
12012
  refSurface: refSurface,
12013
+ memberRolesLoader: memberRolesLoader,
11670
12014
  clock: clock,
11671
12015
  ...executionContext !== void 0 ? {
11672
12016
  executionContext: executionContext
@@ -11972,7 +12316,7 @@ async function startRequirementVerdict(args) {
11972
12316
  }
11973
12317
 
11974
12318
  async function startFreshInstance(args) {
11975
- const {args: startArgs, operationContext: operationContext, clock: clock, seedFields: seedFields} = args, {client: client, tag: tag, workflowResource: workflowResource, definition: definitionName, version: version, ancestors: ancestors, context: context, instanceId: instanceId, perspective: perspective, executionContext: executionContext} = startArgs, {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface} = operationContext, definition = await loadDefinition({
12319
+ const {args: startArgs, operationContext: operationContext, clock: clock, seedFields: seedFields} = args, {client: client, tag: tag, workflowResource: workflowResource, definition: definitionName, version: version, ancestors: ancestors, context: context, instanceId: instanceId, perspective: perspective, executionContext: executionContext} = startArgs, {actor: actor, clientForGdr: clientForGdr, refSurface: refSurface, memberRolesLoader: memberRolesLoader} = operationContext, definition = await loadDefinition({
11976
12320
  client: client,
11977
12321
  definition: definitionName,
11978
12322
  version: version,
@@ -11996,6 +12340,7 @@ async function startFreshInstance(args) {
11996
12340
  id: id,
11997
12341
  now: now,
11998
12342
  refSurface: refSurface,
12343
+ memberRolesLoader: memberRolesLoader,
11999
12344
  ...perspective !== void 0 ? {
12000
12345
  perspective: perspective
12001
12346
  } : {}
@@ -12027,6 +12372,7 @@ async function startFreshInstance(args) {
12027
12372
  actor: actor,
12028
12373
  clientForGdr: clientForGdr,
12029
12374
  refSurface: refSurface,
12375
+ memberRolesLoader: memberRolesLoader,
12030
12376
  clock: clock,
12031
12377
  ...executionContext !== void 0 ? {
12032
12378
  executionContext: executionContext
@@ -12082,7 +12428,10 @@ async function assertStartInputs(args) {
12082
12428
  }
12083
12429
 
12084
12430
  async function resolveStartFields(args) {
12085
- const {client: client, tag: tag, workflowResource: workflowResource, definition: definition, initialFields: initialFields, id: id, now: now, refSurface: refSurface, perspective: perspective} = args, fieldDiscards = [];
12431
+ const {client: client, tag: tag, workflowResource: workflowResource, definition: definition, initialFields: initialFields, id: id, now: now, refSurface: refSurface, memberRolesLoader: memberRolesLoader, perspective: perspective} = args, fieldDiscards = [], memberRoles = await memberRolesLoader({
12432
+ workflowResource: workflowResource,
12433
+ definition: definition
12434
+ });
12086
12435
  return {
12087
12436
  resolvedFields: await resolveDeclaredFields({
12088
12437
  entryDefs: definition.fields ?? [],
@@ -12095,6 +12444,8 @@ async function resolveStartFields(args) {
12095
12444
  workflowResource: workflowResource,
12096
12445
  definitionName: definition.name,
12097
12446
  refSurface: refSurface,
12447
+ memberRoles: memberRoles,
12448
+ roleAliases: definition.roleAliases,
12098
12449
  ...perspective !== void 0 ? {
12099
12450
  perspective: perspective
12100
12451
  } : {},
@@ -12762,11 +13113,12 @@ function createInstanceSession(args) {
12762
13113
  attributes: attributes
12763
13114
  } : {}
12764
13115
  });
12765
- }, settleAfterApply = async ({actor: actor, held: held, ranOps: ranOps, scope: scope}) => {
13116
+ }, settleAfterApply = async ({actor: actor, held: held, ranOps: ranOps, scope: scope, memberRolesLoader: memberRolesLoader}) => {
12766
13117
  const cascaded = await cascadeHeld({
12767
13118
  scope: scope,
12768
13119
  actor: actor,
12769
- held: held
13120
+ held: held,
13121
+ memberRolesLoader: memberRolesLoader
12770
13122
  });
12771
13123
  return instance = await reload({
12772
13124
  client: scope.client,
@@ -12780,12 +13132,13 @@ function createInstanceSession(args) {
12780
13132
  ranOps: ranOps
12781
13133
  } : {}
12782
13134
  };
12783
- }, cascadeHeld = ({scope: scope, actor: actor, held: held}) => cascade({
13135
+ }, cascadeHeld = ({scope: scope, actor: actor, held: held, memberRolesLoader: memberRolesLoader}) => cascade({
12784
13136
  client: scope.client,
12785
13137
  instanceId: instance._id,
12786
13138
  actor: actor,
12787
13139
  clientForGdr: scope.clientForGdr,
12788
13140
  refSurface: scope.refSurface,
13141
+ memberRolesLoader: memberRolesLoader,
12789
13142
  ...clock !== void 0 ? {
12790
13143
  clock: clock
12791
13144
  } : {},
@@ -12882,6 +13235,7 @@ function createInstanceSession(args) {
12882
13235
  },
12883
13236
  tick() {
12884
13237
  return commit(async ({actor: actor, localPrincipalId: localPrincipalId}, held) => {
13238
+ const memberRolesLoader = createAssignmentMemberRolesLoader(tickScope.client);
12885
13239
  await assertInstanceWriteAllowed({
12886
13240
  instance: instance,
12887
13241
  guards: heldGuards,
@@ -12897,7 +13251,8 @@ function createInstanceSession(args) {
12897
13251
  }), cascaded = await cascadeHeld({
12898
13252
  scope: tickScope,
12899
13253
  actor: actor,
12900
- held: held
13254
+ held: held,
13255
+ memberRolesLoader: memberRolesLoader
12901
13256
  });
12902
13257
  return instance = await reload({
12903
13258
  client: tickScope.client,
@@ -12916,6 +13271,7 @@ function createInstanceSession(args) {
12916
13271
  },
12917
13272
  fireAction({activity: activity, action: action, params: params}) {
12918
13273
  return commit(async ({actor: actor, localPrincipalId: localPrincipalId}, held) => {
13274
+ const memberRolesLoader = createAssignmentMemberRolesLoader(fireScope.client);
12919
13275
  assertActionAllowed({
12920
13276
  evaluation: await evaluateWith({
12921
13277
  held: held,
@@ -12936,6 +13292,7 @@ function createInstanceSession(args) {
12936
13292
  } : {},
12937
13293
  clientForGdr: fireScope.clientForGdr,
12938
13294
  refSurface: fireScope.refSurface,
13295
+ memberRolesLoader: memberRolesLoader,
12939
13296
  ...grants !== void 0 ? {
12940
13297
  grants: grants
12941
13298
  } : {},
@@ -12955,7 +13312,8 @@ function createInstanceSession(args) {
12955
13312
  actor: actor,
12956
13313
  held: held,
12957
13314
  ranOps: ranOps,
12958
- scope: fireScope
13315
+ scope: fireScope,
13316
+ memberRolesLoader: memberRolesLoader
12959
13317
  });
12960
13318
  return telemetry.log(WorkflowActionFired, actionFiredData({
12961
13319
  instance: preOp,
@@ -12977,6 +13335,7 @@ function createInstanceSession(args) {
12977
13335
  return Promise.reject(err);
12978
13336
  }
12979
13337
  return commit(async ({actor: actor, localPrincipalId: localPrincipalId}, held) => {
13338
+ const memberRolesLoader = createAssignmentMemberRolesLoader(editScope.client);
12980
13339
  assertEditAllowed(await evaluateWith({
12981
13340
  held: held,
12982
13341
  guards: heldGuards,
@@ -12998,6 +13357,7 @@ function createInstanceSession(args) {
12998
13357
  } : {},
12999
13358
  clientForGdr: editScope.clientForGdr,
13000
13359
  refSurface: editScope.refSurface,
13360
+ memberRolesLoader: memberRolesLoader,
13001
13361
  ...grants !== void 0 ? {
13002
13362
  grants: grants
13003
13363
  } : {},
@@ -13014,7 +13374,8 @@ function createInstanceSession(args) {
13014
13374
  actor: actor,
13015
13375
  held: held,
13016
13376
  ranOps: ranOps,
13017
- scope: editScope
13377
+ scope: editScope,
13378
+ memberRolesLoader: memberRolesLoader
13018
13379
  });
13019
13380
  return telemetry.log(WorkflowFieldEdited, fieldEditedData({
13020
13381
  instance: preOp,
@@ -13333,8 +13694,11 @@ function attributeMember({member: member, group: group, chain: chain}) {
13333
13694
  }
13334
13695
 
13335
13696
  function diffEntry({def: rawDef, latestRaw: latestRaw, target: target}) {
13336
- assertReaderModelAcknowledgement(target.expectedMinReaderModel);
13337
- const def = parseDefinitionInput(rawDef, "diffEntry"), plan = planDefinitionDeploy({
13697
+ const def = parseDefinitionInput(rawDef, "diffEntry");
13698
+ assertReaderModelAcknowledgement(target.expectedMinReaderModel, {
13699
+ requiredMinReaderModel: requiredDefinitionReaderModel([ def ])
13700
+ });
13701
+ const plan = planDefinitionDeploy({
13338
13702
  def: def,
13339
13703
  latest: asLatest(latestRaw),
13340
13704
  target: target
@@ -13365,10 +13729,13 @@ function asLatest(raw) {
13365
13729
  }
13366
13730
 
13367
13731
  async function computeDiffEntries({client: client, defs: defs, target: target}) {
13368
- assertReaderModelAcknowledgement(target.expectedMinReaderModel);
13732
+ const definitions = defs.map(def => parseDefinitionInput(def, "computeDiffEntries"));
13733
+ assertReaderModelAcknowledgement(target.expectedMinReaderModel, {
13734
+ requiredMinReaderModel: requiredDefinitionReaderModel(definitions)
13735
+ });
13369
13736
  const entries = [];
13370
- for (const rawDef of defs) {
13371
- const def = parseDefinitionInput(rawDef, "computeDiffEntries"), latest = await loadLatestDeployed({
13737
+ for (const def of definitions) {
13738
+ const latest = await loadLatestDeployed({
13372
13739
  client: client,
13373
13740
  definition: def.name,
13374
13741
  tag: target.tag
@@ -13693,4 +14060,4 @@ function displayDescription(typeKey) {
13693
14060
  if (typeKey) return DISPLAY[typeKey]?.description;
13694
14061
  }
13695
14062
 
13696
- export { ACTION_SEMANTICS, ACTIVITY_KINDS, ACTIVITY_KIND_DISPLAY, ACTOR_KINDS, ANONYMOUS_IDENTITY, AUTHORING_DISPLAY, ActionDisabledError, ActionParamsInvalidError, CONDITION_VARS, CONTEXT_ENTRY_DISPLAY, CascadeLimitError, ConcurrentCommitEffectOpsError, ConcurrentCompleteEffectError, ConcurrentEditFieldError, ConcurrentFireActionError, ContractViolationError, DATA_MODEL_CHANGES, DATA_MODEL_MIN_READER, DATA_MODEL_VERSION, DECISION_SEMANTICS, DEFAULT_CONTENT_PERSPECTIVE, DEFAULT_EFFECT_LEASE_MS, DEFAULT_IDEMPOTENCY_TTL_MS, DEFAULT_TRANSITION_WHEN, DISPLAY, DRIVER_KINDS, DRIVER_KIND_DISPLAY, DefinitionInUseError, DefinitionNotFoundError, EFFECT_COMMIT_DISPATCH_CAP, EFFECT_COMMIT_QUEUE_DEPTH, ENGINE_API_VERSION, EXECUTION_KINDS, EXECUTOR_CLASSIFICATIONS, EXECUTOR_CLASSIFICATION_DISPLAY, EditFieldDeniedError, EffectCommitQueueOverflowError, EffectNotFoundError, EffectOpsInvalidError, EffectOutputsInvalidError, FIELD_KIND_DISPLAY, FILTER_SCOPE_VARS, FieldValueShapeError, GROUP_KINDS, GROUP_KIND_DISPLAY, GUARD_DOC_TYPE, GUARD_OWNER, GUARD_PREDICATE_VARS, HISTORY_DISPLAY, InitialFieldsInvalidError, InstanceNotFoundError, MAX_COUNTERFACTUAL_INDEX2 as MAX_COUNTERFACTUAL_INDEX, MissingHandlerError, ModelVersionAheadError, MutationGuardDeniedError, MutationGuardDocSchema, NEUTRAL_MARK, OP_DISPLAY, OUTCOME_MARKS, PartialGuardDeployError, PersistedDocShapeError, READER_MODEL_ROLLOUT_URL, RESERVED_CONDITION_VARS, ReaderModelAcknowledgementError, RefResourceUndeclaredError, RequiredFieldNotProvidedError, SIGNAL_SEMANTICS, START_FILTER_VARS, START_REQUIREMENT_VARS, SYSTEM_IDENTITY, SpawnContractsInvalidError, StaleEffectClaimError, StartNotAllowedError, StartNotPrimedError, StartNotSettledError, WORKFLOW_DEFINITION_TYPE, WORKFLOW_INSTANCE_TYPE, WorkflowActionFired, WorkflowActivityReset, WorkflowDefinitionDeleted, WorkflowDefinitionDeployed, WorkflowEffectCompleted, WorkflowEffectStateReported, WorkflowEffectsDrained, WorkflowError, WorkflowFieldEdited, WorkflowInstanceAborted, WorkflowInstanceSchema, WorkflowInstanceStarted, WorkflowInstanceTicked, WorkflowStageSet, WorkflowStageTransitioned, WorkflowStateDivergedError, abortReason, acceptsDocumentType, aclPathForResource, actionDisabledDetail, actionRendering, actionVerdict, activityAutonomyOf, analyzeCondition2 as analyzeCondition, applicableDefinitions, assertReadableModel, assertReaderModelAcknowledgement, atomReadsDataset2 as atomReadsDataset, autonomySummary, availableActions, buildInitialFields, buildSnapshot, checklistLines, classifyPrincipalId, clientConfigFromResource, clientProjectUserDirectory, compileGuard, computeDiffEntries, conditionFieldReadNames, conditionSitesOf, contentDocQuery, contentDraftFallback, contentReleaseName, contextMap, createEngine, createTelemetryIntake, datasetResourceParts, defaultLoggerFactory, definitionDeployedData, definitionLookupGroq, definitionTagsGroq, definitionsListGroq, deniedGuardLabels, deniedGuardRefs, denyingGuards, deployStageGuards, deployedTagsGroq, deriveActivityKind, deriveExecutorClassification, deriveWorkflowAutonomy, describeAtom, describeAutonomyWait, describeCondition, describeDefinition, describeFieldInsight, describeNode, describeSite, describeSiteHeading, diagnoseInputFromEvaluation, diagnoseInstance, diffEntry, displayDescription, displayTitle, documentActionDenials, documentPrefilter, documentStuckCause, driverKind, effectOutputsMap, entryDocRefs, errorMessage, evaluateFromSnapshot, evaluateMutationGuard, evaluateStartFilter, expandResourceAliases, explainCondition2 as explainCondition, explainStartRequirement, extractDocumentId, fieldTreeShape, findActivityNode, findCurrentActivityEntry, findOpenStageEntry, findStageNode, formatRead, gdrFromResource, gdrRef, gdrUri, groupMembershipNames, groupSitesOf, guardMatches, guardsForDefinition, guardsForInstance, guardsForResource, guillemets2 as guillemets, hasSingleSubjectRequirement, hashDefinitionContent, humanize2 as humanize, inFlightFilter, initialFieldIssues, instanceDocId, instanceGuardQuery, instanceWatchesDocument, instancesGuardQuery, instancesQuery, isCascadeFired, isClaimExpired, isClientProjectUser, isComparisonOp, isDefinitionApplicable, isFilterScopedOut, isGdr, isInputSourced, isNotesEntry, isProjectUserNotFoundError, isRevisionConflict, isSingleDocRefEntry, isSingleDocRefKind, isStartableDefinition, isSubjectEntry, isTelemetryEnvDenied, isTerminalActivityStatus, isTerminalStage, isTodoListEntry, isTodoListItem, isUnprimed, lakeGuardId, lakePrincipalId, latestDefinitionsGroq, latestDeployedDefinitions, lintEffectOutputs, minReaderModelOf, missingRequiredInputs, modelVersionOf, narrateAutonomyWaits, noopTelemetry, parentRef, parseDefinitionInput, parseDefinitionSnapshot, parseDefinitionSnapshotValue, parseGdr, parseGuardDocument, parseInstanceDocument, parseResourceGdr, processShellUserProperties, projectStartSliceRow, projectToWatchRef, quoted2 as quoted, readInstanceDoc, readsRaw, readsRootDocument, refCanvas, refDashboard, refDataset, refKindAcceptsTypes, refMediaLibrary, refsOf, rejectedRefTypes, releaseDocId, releaseRef, remediationsFor, requiredModelFeatures, requiredReaderModel, resolveAccess, resolveActor, resolveClientActor, resolveFieldEntry$1 as resolveFieldEntry, resolveUserAttributes, resourceAliasesToMap, resourceFromParsed, resourceGdr, retractStageGuards, sameResource, scalarValidationIssues, schemaTreeShape, sentenceCase, silentLogger, singleSubjectRequirementRefused, stageAutonomyOf, startFieldsParam, startKindOf, startRefusal, stripSystemFields, subjectDenialLabels, subscriptionDocument, subscriptionDocumentsForInstance, sweepStaleClaims, tagScopeFilter, terminalState, toBareId, tryParseGdr, unboundRequirementReads, unsatisfiedTransitionSummaries, userLoginProvider, validateDefinition, validateTag, verdictGuardsForInstance, wallClock, whatIfCondition2 as whatIfCondition, withAssignment, workflow };
14063
+ export { ACTION_SEMANTICS, ACTIVITY_KINDS, ACTIVITY_KIND_DISPLAY, ACTOR_KINDS, ANONYMOUS_IDENTITY, AUTHORING_DISPLAY, ActionDisabledError, ActionParamsInvalidError, CONDITION_VARS, CONTEXT_ENTRY_DISPLAY, CascadeLimitError, ConcurrentCommitEffectOpsError, ConcurrentCompleteEffectError, ConcurrentEditFieldError, ConcurrentFireActionError, ContractViolationError, DATA_MODEL_CHANGES, DATA_MODEL_MAX_READER, DATA_MODEL_MIN_READER, DATA_MODEL_VERSION, DECISION_SEMANTICS, DEFAULT_CONTENT_PERSPECTIVE, DEFAULT_EFFECT_LEASE_MS, DEFAULT_IDEMPOTENCY_TTL_MS, DEFAULT_TRANSITION_WHEN, DISPLAY, DRIVER_KINDS, DRIVER_KIND_DISPLAY, DefinitionInUseError, DefinitionNotFoundError, EFFECT_COMMIT_DISPATCH_CAP, EFFECT_COMMIT_QUEUE_DEPTH, ENGINE_API_VERSION, EXECUTION_KINDS, EXECUTOR_CLASSIFICATIONS, EXECUTOR_CLASSIFICATION_DISPLAY, EditFieldDeniedError, EffectCommitQueueOverflowError, EffectNotFoundError, EffectOpsInvalidError, EffectOutputsInvalidError, FIELD_KIND_DISPLAY, FILTER_SCOPE_VARS, FieldValueShapeError, GROUP_KINDS, GROUP_KIND_DISPLAY, GUARD_DOC_TYPE, GUARD_OWNER, GUARD_PREDICATE_VARS, HISTORY_DISPLAY, InitialFieldsInvalidError, InstanceNotFoundError, MAX_COUNTERFACTUAL_INDEX2 as MAX_COUNTERFACTUAL_INDEX, MissingHandlerError, ModelVersionAheadError, MutationGuardDeniedError, MutationGuardDocSchema, NEUTRAL_MARK, OP_DISPLAY, OUTCOME_MARKS, PartialGuardDeployError, PersistedDocShapeError, READER_MODEL_ROLLOUT_URL, RESERVED_CONDITION_VARS, ReaderModelAcknowledgementError, RefResourceUndeclaredError, RequiredFieldNotProvidedError, SIGNAL_SEMANTICS, START_FILTER_VARS, START_REQUIREMENT_VARS, SYSTEM_IDENTITY, SpawnContractsInvalidError, StaleEffectClaimError, StartNotAllowedError, StartNotPrimedError, StartNotSettledError, WORKFLOW_DEFINITION_TYPE, WORKFLOW_INSTANCE_TYPE, WorkflowActionFired, WorkflowActivityReset, WorkflowDefinitionDeleted, WorkflowDefinitionDeployed, WorkflowEffectCompleted, WorkflowEffectStateReported, WorkflowEffectsDrained, WorkflowError, WorkflowFieldEdited, WorkflowInstanceAborted, WorkflowInstancePreviewSchema, WorkflowInstanceSchema, WorkflowInstanceStarted, WorkflowInstanceTicked, WorkflowStageSet, WorkflowStageTransitioned, WorkflowStateDivergedError, abortReason, acceptsDocumentType, aclPathForResource, actionDisabledDetail, actionRendering, actionVerdict, activityAutonomyOf, actorFulfillsRole, analyzeCondition2 as analyzeCondition, applicableDefinitions, assertReadableModel, assertReaderModelAcknowledgement, atomReadsDataset2 as atomReadsDataset, autonomySummary, availableActions, buildInitialFields, buildSnapshot, checklistLines, classifyPrincipalId, clientConfigFromResource, clientProjectUserDirectory, compileGuard, computeDiffEntries, conditionFieldReadNames, conditionSitesOf, contentDocQuery, contentDraftFallback, contentReleaseName, contextMap, createEngine, createTelemetryIntake, datasetResourceParts, defaultLoggerFactory, definitionDeployedData, definitionLookupGroq, definitionTagsGroq, definitionsListGroq, deniedGuardLabels, deniedGuardRefs, denyingGuards, deployStageGuards, deployedTagsGroq, deriveActivityKind, deriveExecutorClassification, deriveWorkflowAutonomy, describeAtom, describeAutonomyWait, describeCondition, describeDefinition, describeFieldInsight, describeNode, describeSite, describeSiteHeading, diagnoseInputFromEvaluation, diagnoseInstance, diffEntry, displayDescription, displayTitle, documentActionDenials, documentPrefilter, documentStuckCause, driverKind, effectOutputsMap, entryDocRefs, errorMessage, evaluateFromSnapshot, evaluateMutationGuard, evaluateStartFilter, expandResourceAliases, explainCondition2 as explainCondition, explainStartRequirement, extractDocumentId, fieldTreeShape, findActivityNode, findCurrentActivityEntry, findOpenStageEntry, findStageNode, formatRead, gdrFromResource, gdrRef, gdrUri, groupMembershipNames, groupSitesOf, guardMatches, guardsForDefinition, guardsForInstance, guardsForResource, guillemets2 as guillemets, hasSingleSubjectRequirement, hashDefinitionContent, humanize2 as humanize, inFlightFilter, initialFieldIssues, instanceChangesQuery, instanceDocId, instanceGuardQuery, instancePreviewsQuery, instanceWatchesDocument, instancesGuardQuery, instancesQuery, isCascadeFired, isClaimExpired, isClientProjectUser, isComparisonOp, isDefinitionApplicable, isFilterScopedOut, isGdr, isInputSourced, isNotesEntry, isProjectUserNotFoundError, isRevisionConflict, isSingleDocRefEntry, isSingleDocRefKind, isStartableDefinition, isSubjectEntry, isTelemetryEnvDenied, isTerminalActivityStatus, isTerminalStage, isTodoListEntry, isTodoListItem, isUnprimed, lakeGuardId, lakePrincipalId, latestDefinitionsGroq, latestDeployedDefinitions, lintEffectOutputs, minReaderModelOf, missingRequiredInputs, modelVersionOf, narrateAutonomyWaits, noopTelemetry, parentRef, parseDefinitionInput, parseDefinitionSnapshot, parseDefinitionSnapshotValue, parseGdr, parseGuardDocument, parseInstanceDocument, parseInstancePreviewDocument, parseResourceGdr, processShellUserProperties, projectStartSliceRow, projectToWatchRef, quoted2 as quoted, readInstanceDoc, readInstancePreviewDoc, readsRaw, readsRootDocument, refCanvas, refDashboard, refDataset, refKindAcceptsTypes, refMediaLibrary, refsOf, rejectedRefTypes, releaseDocId, releaseRef, remediationsFor, requiredDefinitionReaderModel, requiredModelFeatures, requiredReaderModel, resolveAccess, resolveActor, resolveClientActor, resolveFieldEntry$1 as resolveFieldEntry, resolveUserAttributes, resourceAliasesToMap, resourceFromParsed, resourceGdr, retractStageGuards, sameResource, scalarValidationIssues, schemaTreeShape, sentenceCase, silentLogger, singleSubjectRequirementRefused, stageAutonomyOf, startFieldsParam, startKindOf, startRefusal, stripSystemFields, subjectDenialLabels, subscriptionDocument, subscriptionDocumentsForInstance, sweepStaleClaims, tagScopeFilter, terminalState, toBareId, tryParseGdr, unboundRequirementReads, unsatisfiedTransitionSummaries, userLoginProvider, validateDefinition, validateTag, verdictGuardsForInstance, wallClock, whatIfCondition2 as whatIfCondition, withAssignment, workflow };