@dudousxd/nestjs-durable-core 0.88.0 → 0.90.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.cjs CHANGED
@@ -120,6 +120,7 @@ __export(index_exports, {
120
120
  axisIsRunColumn: () => axisIsRunColumn,
121
121
  bindWorkflowClass: () => bindWorkflowClass,
122
122
  breakpointToken: () => breakpointToken,
123
+ bufferedEventReaches: () => bufferedEventReaches,
123
124
  buildWorkflowDirectory: () => buildWorkflowDirectory,
124
125
  canRoute: () => canRoute,
125
126
  capableWorkers: () => capableWorkers,
@@ -167,6 +168,7 @@ __export(index_exports, {
167
168
  hmacTenantVerifier: () => hmacTenantVerifier,
168
169
  indexWaitersByRun: () => indexWaitersByRun,
169
170
  info: () => info,
171
+ inheritTenant: () => inheritTenant,
170
172
  isAnyCheckpoint: () => isAnyCheckpoint,
171
173
  isAnyMember: () => isAnyMember,
172
174
  isEngineMintedTag: () => isEngineMintedTag,
@@ -193,6 +195,7 @@ __export(index_exports, {
193
195
  log: () => log,
194
196
  markRemoteEvent: () => markRemoteEvent,
195
197
  matchesAttributes: () => matchesAttributes,
198
+ matchesTenantPredicates: () => matchesTenantPredicates,
196
199
  mergeRunFacetRows: () => mergeRunFacetRows,
197
200
  mergeRunValueFacetRows: () => mergeRunValueFacetRows,
198
201
  missingCapabilities: () => missingCapabilities,
@@ -217,6 +220,7 @@ __export(index_exports, {
217
220
  prevCronFireMs: () => prevCronFireMs,
218
221
  prevRRuleFireMs: () => prevRRuleFireMs,
219
222
  queryCheckpointsOf: () => queryCheckpointsOf,
223
+ readBufferedEvent: () => readBufferedEvent,
220
224
  readRunsByIds: () => readRunsByIds,
221
225
  readSearchAttributes: () => readSearchAttributes,
222
226
  requiredCapabilities: () => requiredCapabilities,
@@ -228,6 +232,7 @@ __export(index_exports, {
228
232
  retentionKeeps: () => retentionKeeps,
229
233
  retiredHandoffName: () => retiredHandoffName,
230
234
  routeFor: () => routeFor,
235
+ rowTenant: () => rowTenant,
231
236
  runCompletedEvent: () => runCompletedEvent,
232
237
  runDetailEtag: () => runDetailEtag,
233
238
  runDurableExecution: () => runDurableExecution,
@@ -245,6 +250,8 @@ __export(index_exports, {
245
250
  sanitizeQueueToken: () => sanitizeQueueToken,
246
251
  scheduleRunIdAt: () => scheduleRunIdAt,
247
252
  scheduledRunId: () => scheduledRunId,
253
+ scopeBufferedEvent: () => scopeBufferedEvent,
254
+ scopeTenantQuery: () => scopeTenantQuery,
248
255
  settleResultsWithPlainCalls: () => settleResultsWithPlainCalls,
249
256
  signTenantToken: () => signTenantToken,
250
257
  singletonAdmissionDenialPatch: () => singletonAdmissionDenialPatch,
@@ -261,6 +268,8 @@ __export(index_exports, {
261
268
  summarizeRunFromStore: () => summarizeRunFromStore,
262
269
  summarizeTimeline: () => summarizeTimeline,
263
270
  tenantGroup: () => tenantGroup,
271
+ tenantIdsFor: () => tenantIdsFor,
272
+ tenantVisible: () => tenantVisible,
264
273
  toEventSubscription: () => toEventSubscription,
265
274
  traceIdOfTraceparent: () => traceIdOfTraceparent,
266
275
  triggerFailedSubscribersOf: () => triggerFailedSubscribersOf,
@@ -1044,7 +1053,7 @@ var TERMINAL_RUN_STATUSES = [
1044
1053
  ];
1045
1054
  function isNonEmptyRunScope(scope) {
1046
1055
  if (!scope) return false;
1047
- return scope.workflow !== void 0 || scope.workflows !== void 0 || scope.tag !== void 0 || scope.tags !== void 0 || scope.namespace !== void 0 || scope.namespaces !== void 0 || scope.attributes !== void 0 && scope.attributes.length > 0;
1056
+ return scope.workflow !== void 0 || scope.workflows !== void 0 || scope.tag !== void 0 || scope.tags !== void 0 || scope.namespace !== void 0 || scope.namespaces !== void 0 || scope.tenantId !== void 0 || scope.tenantIds !== void 0 || scope.attributes !== void 0 && scope.attributes.length > 0;
1048
1057
  }
1049
1058
  __name(isNonEmptyRunScope, "isNonEmptyRunScope");
1050
1059
  var PARENT_CLOSE_TAG_PREFIX = "parent-close:";
@@ -1117,6 +1126,31 @@ function acceptingSubscription(subscriptions, payload) {
1117
1126
  };
1118
1127
  }
1119
1128
  __name(acceptingSubscription, "acceptingSubscription");
1129
+ var BUFFERED_EVENT_TENANTS = "__durableEventTenants";
1130
+ function scopeBufferedEvent(payload, tenantIds) {
1131
+ return tenantIds === void 0 ? payload : {
1132
+ [BUFFERED_EVENT_TENANTS]: tenantIds,
1133
+ payload
1134
+ };
1135
+ }
1136
+ __name(scopeBufferedEvent, "scopeBufferedEvent");
1137
+ function readBufferedEvent(stored) {
1138
+ if (stored !== null && typeof stored === "object" && Array.isArray(stored[BUFFERED_EVENT_TENANTS]) && Object.keys(stored).length === 2 && "payload" in stored) {
1139
+ const scoped = stored;
1140
+ return {
1141
+ payload: scoped.payload,
1142
+ tenantIds: scoped[BUFFERED_EVENT_TENANTS]
1143
+ };
1144
+ }
1145
+ return {
1146
+ payload: stored
1147
+ };
1148
+ }
1149
+ __name(readBufferedEvent, "readBufferedEvent");
1150
+ function bufferedEventReaches(tenantIds, tenantId) {
1151
+ return tenantIds === void 0 || tenantIds.includes(tenantId ?? null);
1152
+ }
1153
+ __name(bufferedEventReaches, "bufferedEventReaches");
1120
1154
 
1121
1155
  // src/lifecycle-events.ts
1122
1156
  function runCompletedEvent(workflow) {
@@ -1906,7 +1940,8 @@ async function runStepHandler(task, handler) {
1906
1940
  workflow: void 0,
1907
1941
  name: task.name,
1908
1942
  seq: task.seq,
1909
- attempt: task.attempt
1943
+ attempt: task.attempt,
1944
+ context: task.context
1910
1945
  },
1911
1946
  // Outside any ambient workflow ctx: an in-process transport runs the handler on the parent
1912
1947
  // body's async path, but a handler is not the body (see `runOutsideWorkflowCtx`).
@@ -2247,10 +2282,14 @@ var Entities = class {
2247
2282
  };
2248
2283
 
2249
2284
  // src/event-accumulators.ts
2250
- function accumulatorRunId(target, key) {
2251
- if (key === void 0) return `__evtacc__:${target}`;
2252
- const escaped = encodeURIComponent(key).replace(/[~!'()*.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2253
- return `__evtacc__:${target}:${escaped}`;
2285
+ function escapeIdPart(value) {
2286
+ return encodeURIComponent(value).replace(/[~!'()*.]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
2287
+ }
2288
+ __name(escapeIdPart, "escapeIdPart");
2289
+ function accumulatorRunId(target, key, tenant) {
2290
+ const base = tenant === void 0 ? "__evtacc__" : `__evtacc__@${escapeIdPart(tenant)}`;
2291
+ if (key === void 0) return `${base}:${target}`;
2292
+ return `${base}:${target}:${escapeIdPart(key)}`;
2254
2293
  }
2255
2294
  __name(accumulatorRunId, "accumulatorRunId");
2256
2295
  var ACCUMULATOR_SEEN_MAX = 1e3;
@@ -2295,7 +2334,7 @@ var SeenEvents = class SeenEvents2 {
2295
2334
  } : rest;
2296
2335
  }
2297
2336
  };
2298
- var accToken = /* @__PURE__ */ __name((input) => accumulatorRunId(input.target, input.key), "accToken");
2337
+ var accToken = /* @__PURE__ */ __name((input) => accumulatorRunId(input.target, input.key, input.tenant), "accToken");
2299
2338
  var EventAccumulators = class {
2300
2339
  static {
2301
2340
  __name(this, "EventAccumulators");
@@ -2314,8 +2353,12 @@ var EventAccumulators = class {
2314
2353
  * Route an `onEvent` payload into its target's debounce/batch accumulator: the target's one, or
2315
2354
  * with a `key`, the one for `String(config.key(payload))`. A `key` that throws rejects the route.
2316
2355
  * With `id`, the accumulator counts the event once however many times it is routed.
2356
+ *
2357
+ * `tenant` is the tenant the event belongs to when tenancy is on: a tenant gets its own
2358
+ * accumulator, stamped with it (so its target runs are too); `null` routes into the shared one,
2359
+ * stamped with no tenant. Undefined (tenancy off) starts the accumulator as before.
2317
2360
  */
2318
- route(target, config, payload, id) {
2361
+ route(target, config, payload, id, tenant) {
2319
2362
  const input = {
2320
2363
  target,
2321
2364
  windowMs: config.windowMs,
@@ -2324,6 +2367,9 @@ var EventAccumulators = class {
2324
2367
  } : {},
2325
2368
  ...config.key ? {
2326
2369
  key: String(config.key(payload))
2370
+ } : {},
2371
+ ...tenant ? {
2372
+ tenant: tenant.id
2327
2373
  } : {}
2328
2374
  };
2329
2375
  const workflow = config.mode === "debounce" ? "__evt_debounce" : "__evt_batch";
@@ -2333,10 +2379,18 @@ var EventAccumulators = class {
2333
2379
  id,
2334
2380
  payload
2335
2381
  };
2382
+ const opts = tenant === void 0 ? void 0 : tenant === null ? {
2383
+ tenantId: null
2384
+ } : {
2385
+ tenantId: tenant.id,
2386
+ ...tenant.kind !== void 0 ? {
2387
+ tenantKind: tenant.kind
2388
+ } : {}
2389
+ };
2336
2390
  return this.host.signalWithStart(workflow, input, token, {
2337
2391
  token,
2338
2392
  payload: signal
2339
- });
2393
+ }, opts);
2340
2394
  }
2341
2395
  /** Fire the target with the LAST payload once events have been quiet for `windowMs`. */
2342
2396
  async debounce(ctx, input) {
@@ -3824,6 +3878,78 @@ function remember(memo, key, runId) {
3824
3878
  }
3825
3879
  __name(remember, "remember");
3826
3880
 
3881
+ // src/tenancy.ts
3882
+ function tenantVisible(row, filter) {
3883
+ const id = row.tenantId ?? null;
3884
+ switch (filter.mode) {
3885
+ case "system":
3886
+ case "all":
3887
+ return true;
3888
+ case "tenantless":
3889
+ return id === null;
3890
+ case "tenant":
3891
+ return id === filter.tenantId || id === null && filter.nullRows === "shared";
3892
+ }
3893
+ }
3894
+ __name(tenantVisible, "tenantVisible");
3895
+ function tenantIdsFor(filter) {
3896
+ switch (filter.mode) {
3897
+ case "system":
3898
+ case "all":
3899
+ return void 0;
3900
+ case "tenantless":
3901
+ return [
3902
+ null
3903
+ ];
3904
+ case "tenant":
3905
+ return filter.nullRows === "shared" ? [
3906
+ filter.tenantId,
3907
+ null
3908
+ ] : [
3909
+ filter.tenantId
3910
+ ];
3911
+ }
3912
+ }
3913
+ __name(tenantIdsFor, "tenantIdsFor");
3914
+ function scopeTenantQuery(query, filter) {
3915
+ const allowed = tenantIdsFor(filter);
3916
+ if (allowed === void 0) return query;
3917
+ const tenantIds = query.tenantIds ? query.tenantIds.filter((id) => allowed.includes(id)) : allowed;
3918
+ return {
3919
+ ...query,
3920
+ tenantIds
3921
+ };
3922
+ }
3923
+ __name(scopeTenantQuery, "scopeTenantQuery");
3924
+ function rowTenant(row) {
3925
+ if (row.tenantId == null) return void 0;
3926
+ return row.tenantKind != null ? {
3927
+ id: row.tenantId,
3928
+ kind: row.tenantKind
3929
+ } : {
3930
+ id: row.tenantId
3931
+ };
3932
+ }
3933
+ __name(rowTenant, "rowTenant");
3934
+ function inheritTenant(row) {
3935
+ return row.tenantId == null ? {
3936
+ tenantId: null
3937
+ } : {
3938
+ tenantId: row.tenantId,
3939
+ ...row.tenantKind != null ? {
3940
+ tenantKind: row.tenantKind
3941
+ } : {}
3942
+ };
3943
+ }
3944
+ __name(inheritTenant, "inheritTenant");
3945
+ function matchesTenantPredicates(row, query) {
3946
+ const id = row.tenantId ?? null;
3947
+ if (query.tenantId !== void 0 && id !== query.tenantId) return false;
3948
+ if (query.tenantIds !== void 0 && !query.tenantIds.includes(id)) return false;
3949
+ return true;
3950
+ }
3951
+ __name(matchesTenantPredicates, "matchesTenantPredicates");
3952
+
3827
3953
  // src/schedules.ts
3828
3954
  var ScheduleAlreadyExistsError = class extends Error {
3829
3955
  static {
@@ -3881,6 +4007,16 @@ var ScheduleClient = class {
3881
4007
  listSchedules: /* @__PURE__ */ __name((q) => s.listSchedules.call(s, q), "listSchedules")
3882
4008
  };
3883
4009
  }
4010
+ filter() {
4011
+ return this.host.tenantFilter?.() ?? {
4012
+ mode: "system"
4013
+ };
4014
+ }
4015
+ /** The schedule `id` if it exists and the caller may see it (tenancy), else null. */
4016
+ async visible(id) {
4017
+ const record = await this.requireStore().getSchedule(id);
4018
+ return record && tenantVisible(record, this.filter()) ? record : null;
4019
+ }
3884
4020
  /** Create a schedule. Throws {@link ScheduleAlreadyExistsError} if the id is taken. */
3885
4021
  async create(opts) {
3886
4022
  const store = this.requireStore();
@@ -3894,19 +4030,24 @@ var ScheduleClient = class {
3894
4030
  */
3895
4031
  async upsert(opts) {
3896
4032
  const store = this.requireStore();
3897
- return this.write(opts, await store.getSchedule(opts.id));
4033
+ const existing = await store.getSchedule(opts.id);
4034
+ if (existing && !tenantVisible(existing, this.filter())) {
4035
+ throw new ScheduleAlreadyExistsError(opts.id);
4036
+ }
4037
+ return this.write(opts, existing);
3898
4038
  }
3899
- /** The schedule `id`, or null. */
4039
+ /** The schedule `id`, or null (also null for another tenant's schedule). */
3900
4040
  async get(id) {
3901
- const record = await this.requireStore().getSchedule(id);
4041
+ const record = await this.visible(id);
3902
4042
  return record ? describe(record) : null;
3903
4043
  }
3904
- /** Schedules matching `query`, soonest-due first. */
4044
+ /** Schedules matching `query` (and visible to the caller's tenant), soonest-due first. */
3905
4045
  async list(query = {}) {
3906
- return (await this.requireStore().listSchedules(query)).map(describe);
4046
+ return (await this.requireStore().listSchedules(scopeTenantQuery(query, this.filter()))).map(describe);
3907
4047
  }
3908
4048
  /** Delete the schedule. Runs it already started are left alone. Returns whether it existed. */
3909
- delete(id) {
4049
+ async delete(id) {
4050
+ if (!await this.visible(id)) return false;
3910
4051
  return this.requireStore().deleteSchedule(id);
3911
4052
  }
3912
4053
  /** Stop firing until {@link resume}. `note` records why (shown by `get`/`list`). */
@@ -4041,10 +4182,34 @@ var ScheduleClient = class {
4041
4182
  return !!prev && !TERMINAL_RUN_STATUSES.includes(prev.status);
4042
4183
  }
4043
4184
  async mustGet(id) {
4044
- const record = await this.requireStore().getSchedule(id);
4185
+ const record = await this.visible(id);
4045
4186
  if (!record) throw new ScheduleNotFoundError(id);
4046
4187
  return record;
4047
4188
  }
4189
+ /** Explicit `opts.tenantId` → the existing schedule's tenant (upsert) → the context tenant → none. */
4190
+ scheduleTenant(opts, existing) {
4191
+ let tenant;
4192
+ if (opts.tenantId !== void 0) {
4193
+ tenant = opts.tenantId === null ? void 0 : {
4194
+ id: opts.tenantId,
4195
+ kind: opts.tenantKind
4196
+ };
4197
+ } else if (existing) {
4198
+ tenant = existing.tenantId == null ? void 0 : {
4199
+ id: existing.tenantId,
4200
+ kind: existing.tenantKind ?? void 0
4201
+ };
4202
+ } else {
4203
+ tenant = this.host.tenant?.();
4204
+ }
4205
+ if (!tenant) return {};
4206
+ return tenant.kind !== void 0 ? {
4207
+ tenantId: tenant.id,
4208
+ tenantKind: tenant.kind
4209
+ } : {
4210
+ tenantId: tenant.id
4211
+ };
4212
+ }
4048
4213
  async write(opts, existing) {
4049
4214
  const store = this.requireStore();
4050
4215
  const spec = toSpec(opts);
@@ -4063,6 +4228,7 @@ var ScheduleClient = class {
4063
4228
  ...existing?.state ?? {},
4064
4229
  window
4065
4230
  }),
4231
+ ...this.scheduleTenant(opts, existing),
4066
4232
  createdAt: existing?.createdAt ?? new Date(now),
4067
4233
  updatedAt: new Date(now)
4068
4234
  };
@@ -4145,7 +4311,10 @@ function startOptions(record) {
4145
4311
  namespace: record.namespace,
4146
4312
  searchAttributes: spec.searchAttributes,
4147
4313
  priority: spec.priority,
4148
- concurrency: spec.concurrency
4314
+ concurrency: spec.concurrency,
4315
+ // Every fire belongs to the schedule's customer (or explicitly to none), never to whichever
4316
+ // poller or request happened to fire it.
4317
+ ...inheritTenant(record)
4149
4318
  });
4150
4319
  }
4151
4320
  __name(startOptions, "startOptions");
@@ -4175,6 +4344,8 @@ function describe(record) {
4175
4344
  lastRunId: state.lastRunId,
4176
4345
  fires: state.fires ?? 0,
4177
4346
  lastError: state.lastError,
4347
+ tenantId: record.tenantId ?? void 0,
4348
+ tenantKind: record.tenantKind ?? void 0,
4178
4349
  createdAt: record.createdAt,
4179
4350
  updatedAt: record.updatedAt
4180
4351
  });
@@ -5528,8 +5699,14 @@ function createWorkflowCtx(host, runId, compensations, workflow = "", searchAttr
5528
5699
  }, "consumeBuffered");
5529
5700
  const consumeBufferedEvent = /* @__PURE__ */ __name(async (name, match, token, seq) => {
5530
5701
  const candidates = await store.listBufferedEvents(name, EVENT_BUFFER_SCAN_LIMIT);
5702
+ let runTenantId;
5531
5703
  for (const candidate of candidates) {
5532
- if (!eventMatches(candidate.payload, match ?? {})) continue;
5704
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
5705
+ if (!eventMatches(payload, match ?? {})) continue;
5706
+ if (tenantIds !== void 0) {
5707
+ runTenantId ??= store.getRun(runId).then((run) => run?.tenantId ?? null);
5708
+ if (!bufferedEventReaches(tenantIds, await runTenantId)) continue;
5709
+ }
5533
5710
  if (!await store.removeBufferedEvent(candidate.id)) continue;
5534
5711
  await store.removeSignalWaiter({
5535
5712
  token,
@@ -5541,10 +5718,10 @@ function createWorkflowCtx(host, runId, compensations, workflow = "", searchAttr
5541
5718
  seq,
5542
5719
  name: `signal:${token}`,
5543
5720
  kind: "signal",
5544
- output: candidate.payload
5721
+ output: payload
5545
5722
  }));
5546
5723
  return {
5547
- value: candidate.payload
5724
+ value: payload
5548
5725
  };
5549
5726
  }
5550
5727
  return null;
@@ -6709,6 +6886,8 @@ var WorkflowEngine = class _WorkflowEngine {
6709
6886
  context;
6710
6887
  /** Establish the originating context ambiently around a local step body (see {@link WorkflowEngineDeps.rehydrate}). Default passthrough. */
6711
6888
  rehydrate;
6889
+ /** Tenancy seam (see {@link WorkflowEngineDeps.tenancy}); undefined = off. */
6890
+ tenancy;
6712
6891
  compensationRetries;
6713
6892
  /** Persist a `running` checkpoint at the start of a local step body (see {@link WorkflowEngineDeps.trackStepStart}). */
6714
6893
  trackStepStart;
@@ -6726,6 +6905,10 @@ var WorkflowEngine = class _WorkflowEngine {
6726
6905
  workflows = /* @__PURE__ */ new Map();
6727
6906
  /** The newest registered version per workflow name — used to `start` new runs. */
6728
6907
  latest = /* @__PURE__ */ new Map();
6908
+ /** Workflows this instance starts but never runs, keyed `name@version` (like {@link workflows}), so every version stays startable. See {@link registerStartOnly}. */
6909
+ startOnly = /* @__PURE__ */ new Map();
6910
+ /** The latest start-only registration per name, for unpinned starts (like {@link latest}). */
6911
+ startOnlyLatest = /* @__PURE__ */ new Map();
6729
6912
  /** Event name → subscribing workflow name → that workflow's subscriptions to it. See `onEvent`. */
6730
6913
  eventTriggers = /* @__PURE__ */ new Map();
6731
6914
  /** Durable-entity subsystem (registers the `__entity` runner; see `registerEntity`). */
@@ -6914,6 +7097,7 @@ var WorkflowEngine = class _WorkflowEngine {
6914
7097
  this.traceparent = deps.traceparent;
6915
7098
  this.context = deps.context;
6916
7099
  this.rehydrate = deps.rehydrate ?? ((_carrier, fn) => fn());
7100
+ this.tenancy = deps.tenancy;
6917
7101
  this.compensationRetries = Math.max(1, deps.compensationRetries ?? 1);
6918
7102
  this.trackStepStart = deps.trackStepStart ?? true;
6919
7103
  this.localWork = new BoundedRunner(LOCAL_RUN_CONCURRENCY);
@@ -6943,7 +7127,9 @@ var WorkflowEngine = class _WorkflowEngine {
6943
7127
  this.schedules = new ScheduleClient(this.store, {
6944
7128
  start: /* @__PURE__ */ __name((workflow, input, runId, opts) => this.start(workflow, input, runId, opts), "start"),
6945
7129
  getRun: /* @__PURE__ */ __name((runId) => this.store.getRun(runId), "getRun"),
6946
- isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining")
7130
+ isDraining: /* @__PURE__ */ __name(() => this.draining, "isDraining"),
7131
+ tenant: /* @__PURE__ */ __name(() => this.tenancy?.current(), "tenant"),
7132
+ tenantFilter: /* @__PURE__ */ __name(() => this.tenantFilter(), "tenantFilter")
6947
7133
  }, {
6948
7134
  namespace: this.namespace,
6949
7135
  clock: this.clock
@@ -7047,7 +7233,18 @@ var WorkflowEngine = class _WorkflowEngine {
7047
7233
  }
7048
7234
  }
7049
7235
  });
7050
- this.accumulators = new EventAccumulators(this);
7236
+ this.accumulators = new EventAccumulators({
7237
+ register: /* @__PURE__ */ __name((name, version, fn, opts) => this.register(name, version, fn, opts), "register"),
7238
+ // The engine picks the accumulator's tenant itself, so its signal is the engine's own
7239
+ // delivery: not subject to the publisher's tenancy filter.
7240
+ signalWithStart: /* @__PURE__ */ __name(async (workflow, input, runId, signal, opts) => {
7241
+ await this.start(workflow, input, runId, opts);
7242
+ await this.signalUnchecked(signal.token, signal.payload);
7243
+ return {
7244
+ runId
7245
+ };
7246
+ }, "signalWithStart")
7247
+ });
7051
7248
  this.entities = new Entities(this, {
7052
7249
  bufferSignal: /* @__PURE__ */ __name((token, payload) => this.store.bufferSignal(token, payload), "bufferSignal"),
7053
7250
  wakeWaiter: /* @__PURE__ */ __name((token, payload) => this.wakeSignalWaiter(token, payload), "wakeWaiter"),
@@ -7246,7 +7443,7 @@ var WorkflowEngine = class _WorkflowEngine {
7246
7443
  if (!this.isRegisteredHere(run) && !await this.canResolveWorkflow(run)) {
7247
7444
  const result = await this.settleUnregistered(run, nowMs);
7248
7445
  if (result) settled?.set(run.id, result);
7249
- else if (result === void 0) this.logUnregisteredSkip(run);
7446
+ else if (result === void 0 && !this.isStartOnlyHere(run)) this.logUnregisteredSkip(run);
7250
7447
  continue;
7251
7448
  }
7252
7449
  try {
@@ -7392,6 +7589,34 @@ var WorkflowEngine = class _WorkflowEngine {
7392
7589
  }
7393
7590
  }
7394
7591
  /**
7592
+ * Let {@link start} create runs of `name@version` on this instance without registering a body here:
7593
+ * the run is stored and left for an instance that {@link register}ed the workflow, and this one
7594
+ * never executes it. For a process that only emits work (an API pod) while workers run it.
7595
+ *
7596
+ * Runs this instance picks up anyway (a driving poll, the run queue) are released for another
7597
+ * instance without a log line, and dead-lettered after `unregisteredWorkflowGraceMs` like any run
7598
+ * whose workflow nobody registered. A {@link register} of the same name on this instance wins.
7599
+ */
7600
+ registerStartOnly(name, version, opts) {
7601
+ const entry = {
7602
+ name,
7603
+ version,
7604
+ fn: /* @__PURE__ */ __name(() => {
7605
+ throw new Error(`workflow ${name} is start-only on this instance \u2014 it has no body here`);
7606
+ }, "fn"),
7607
+ tags: opts?.tags,
7608
+ validateInput: opts?.validateInput,
7609
+ origin: opts?.origin
7610
+ };
7611
+ this.startOnly.set(versionKey(name, version), entry);
7612
+ const current = this.startOnlyLatest.get(name);
7613
+ if (!current || isNewerVersion(version, current.version)) this.startOnlyLatest.set(name, entry);
7614
+ }
7615
+ /** Whether `run` is of a workflow this instance only starts (see {@link registerStartOnly}). */
7616
+ isStartOnlyHere(run) {
7617
+ return !this.isRegisteredHere(run) && this.startOnly.has(versionKey(run.workflow, run.workflowVersion));
7618
+ }
7619
+ /**
7395
7620
  * The retained in-process body for `name@version`, for an IN-APP worker that consumes this engine's
7396
7621
  * own group to SERVE a group-served `register(..., { group, executor })` workflow (uniform dispatch):
7397
7622
  * the worker fetches the body by name when it picks up the dispatched {@link WorkflowTask}, replays
@@ -7495,15 +7720,19 @@ var WorkflowEngine = class _WorkflowEngine {
7495
7720
  * time from {@link context} — the SAME reader stamped on dispatched remote tasks — so a local step
7496
7721
  * sees the live tenant / user / trace ids ambiently (via the {@link rehydrate} bridge). Default
7497
7722
  * `rehydrate` is a passthrough, so this is byte-identical to a bare body call when unwired.
7723
+ *
7724
+ * The run row's tenant is re-applied INSIDE the rehydrated context: an app carrier (a custom
7725
+ * `serialize`/`deserialize`) may not carry the tenant, and its deserializer would otherwise replace
7726
+ * the tenant the turn was started with. Local steps always see the row's tenant.
7498
7727
  */
7499
- interceptStep(invocation, body) {
7728
+ interceptStep(invocation, body, tenant) {
7500
7729
  const carrier = this.context?.();
7501
7730
  const run = /* @__PURE__ */ __name(() => {
7502
7731
  if (this.interceptors.length === 0) return body();
7503
7732
  const chain = this.interceptors.reduceRight((next, interceptor) => () => interceptor(invocation, next), body);
7504
7733
  return chain();
7505
7734
  }, "run");
7506
- return this.rehydrate(carrier, run);
7735
+ return this.rehydrate(carrier, () => tenant ? this.inRunTenant(tenant, run) : run());
7507
7736
  }
7508
7737
  /**
7509
7738
  * Be notified when a run is cancelled — on ANY instance, via the transport control plane. A
@@ -7694,9 +7923,12 @@ var WorkflowEngine = class _WorkflowEngine {
7694
7923
  * an announcement carries no `where` or `input`. `routeIdOf` names the event for a subscriber's
7695
7924
  * debounce/batch accumulator, which counts an id once. Returns the subscribers reached, with the
7696
7925
  * run each started (none when the payload went into its debounce/batch accumulator), and the ones
7697
- * that could not be started, with why.
7926
+ * that could not be started, with why. `batchTenant` is the tenant whose debounce/batch accumulator
7927
+ * the payload goes into (see {@link EventAccumulators.route}). `runTenant`, when set, is the tenant
7928
+ * every directly started subscriber run gets (a lifecycle event: the settled run's), instead of the
7929
+ * context's at publish time (which may be none, e.g. the background retry pass).
7698
7930
  */
7699
- async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf) {
7931
+ async startSubscribers(name, payload, runIdOf, only, remote = [], routeIdOf, batchTenant, runTenant) {
7700
7932
  const reached = [];
7701
7933
  const failed = [];
7702
7934
  for (const [workflow, subscriptions] of this.eventTriggers.get(name) ?? []) {
@@ -7713,13 +7945,13 @@ var WorkflowEngine = class _WorkflowEngine {
7713
7945
  const input = accepted.input ? accepted.input(payload) : payload;
7714
7946
  const batch = this.latest.get(workflow)?.eventBatch;
7715
7947
  if (batch) {
7716
- await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow));
7948
+ await this.accumulators.route(workflow, batch, input, routeIdOf?.(workflow), batchTenant);
7717
7949
  reached.push({
7718
7950
  workflow
7719
7951
  });
7720
7952
  } else {
7721
7953
  const runId = runIdOf(workflow);
7722
- await this.start(workflow, input, runId);
7954
+ await this.start(workflow, input, runId, runTenant);
7723
7955
  reached.push({
7724
7956
  workflow,
7725
7957
  runId
@@ -7737,7 +7969,7 @@ var WorkflowEngine = class _WorkflowEngine {
7737
7969
  if (local?.has(workflow) || only && !only.has(workflow)) continue;
7738
7970
  try {
7739
7971
  const runId = runIdOf(workflow);
7740
- await this.start(workflow, payload, runId);
7972
+ await this.start(workflow, payload, runId, runTenant);
7741
7973
  reached.push({
7742
7974
  workflow,
7743
7975
  runId
@@ -8094,11 +8326,12 @@ var WorkflowEngine = class _WorkflowEngine {
8094
8326
  const triggers = this.eventTriggers.get(lifecycleEventName(run.workflow, kind));
8095
8327
  if (!triggers || !this.servesNamespace(run.namespace)) return out;
8096
8328
  let payload;
8329
+ const tenant = this.lifecycleBatchTenant(run)?.id;
8097
8330
  for (const [workflow, subscriptions] of triggers) {
8098
8331
  const batch = this.latest.get(workflow)?.eventBatch;
8099
8332
  if (!batch) continue;
8100
8333
  if (!batch.key && subscriptions.every((sub2) => !sub2.where)) {
8101
- out.set(workflow, accumulatorRunId(workflow));
8334
+ out.set(workflow, accumulatorRunId(workflow, void 0, tenant));
8102
8335
  continue;
8103
8336
  }
8104
8337
  try {
@@ -8106,7 +8339,7 @@ var WorkflowEngine = class _WorkflowEngine {
8106
8339
  const { accepted } = acceptingSubscription(subscriptions, payload);
8107
8340
  if (!accepted) continue;
8108
8341
  const input = accepted.input ? accepted.input(payload) : payload;
8109
- out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0));
8342
+ out.set(workflow, accumulatorRunId(workflow, batch.key ? String(batch.key(input)) : void 0, tenant));
8110
8343
  } catch {
8111
8344
  out.set(workflow, void 0);
8112
8345
  }
@@ -8285,7 +8518,9 @@ var WorkflowEngine = class _WorkflowEngine {
8285
8518
  */
8286
8519
  async triggeredRuns(source) {
8287
8520
  const run = typeof source === "string" ? await this.store.getRun(source) : source;
8288
- return run ? triggeredRunsOf(run) : [];
8521
+ if (!run) return [];
8522
+ const filter = this.restrictiveFilter();
8523
+ return filter && !tenantVisible(run, filter) ? [] : triggeredRunsOf(run);
8289
8524
  }
8290
8525
  /** The live path of {@link publishSettled}: right after this instance settled the run. */
8291
8526
  publishLifecycle(event) {
@@ -8418,7 +8653,18 @@ var WorkflowEngine = class _WorkflowEngine {
8418
8653
  }
8419
8654
  if (targets.length === 0 && owe.size === 0 && !resolved) return void 0;
8420
8655
  const runIdOf = /* @__PURE__ */ __name((sub2) => lifecycleRunId(run.id, kind, sub2), "runIdOf");
8421
- const { reached, failed } = targets.length > 0 ? await this.startSubscribers(name, lifecycleEventOf(run), runIdOf, new Set(targets), remote, runIdOf) : {
8656
+ const { reached, failed } = targets.length > 0 ? await this.startSubscribers(
8657
+ name,
8658
+ lifecycleEventOf(run),
8659
+ runIdOf,
8660
+ new Set(targets),
8661
+ remote,
8662
+ runIdOf,
8663
+ this.lifecycleBatchTenant(run),
8664
+ // The downstream run belongs to the settled run's customer, whoever publishes it (the
8665
+ // turn that settled it, or the background retry pass outside any request).
8666
+ inheritTenant(run)
8667
+ ) : {
8422
8668
  reached: [],
8423
8669
  failed: []
8424
8670
  };
@@ -8931,7 +9177,8 @@ var WorkflowEngine = class _WorkflowEngine {
8931
9177
  async start(workflow, input, runId, opts) {
8932
9178
  const name = workflowName(workflow);
8933
9179
  const pinned = opts?.version;
8934
- let registered = pinned === void 0 ? this.latest.get(name) : this.workflows.get(versionKey(name, pinned));
9180
+ const startOnly = pinned === void 0 ? this.startOnlyLatest.get(name) : this.startOnly.get(versionKey(name, pinned));
9181
+ let registered = pinned === void 0 ? this.latest.get(name) ?? startOnly : this.workflows.get(versionKey(name, pinned)) ?? startOnly;
8935
9182
  if (!registered && pinned === void 0) {
8936
9183
  const ancestor = await this.findRemoteAncestor(runId);
8937
9184
  if (ancestor) registered = this.synthesizeRemoteChild(name, ancestor.version, ancestor);
@@ -8960,14 +9207,7 @@ var WorkflowEngine = class _WorkflowEngine {
8960
9207
  }
8961
9208
  await registered.validateInput?.(input);
8962
9209
  const prior = await this.store.getRun(runId);
8963
- if (prior) {
8964
- return {
8965
- runId,
8966
- status: prior.status,
8967
- output: prior.output,
8968
- error: prior.error
8969
- };
8970
- }
9210
+ if (prior) return this.existingStartResult(prior);
8971
9211
  const quota = await resolveConcurrency(opts?.concurrency, registered.concurrency, input);
8972
9212
  if (quota) await assertConcurrency(this.store, name, quota);
8973
9213
  const now = /* @__PURE__ */ new Date();
@@ -9007,6 +9247,7 @@ var WorkflowEngine = class _WorkflowEngine {
9007
9247
  tags,
9008
9248
  searchAttributes: opts?.searchAttributes,
9009
9249
  priority: opts?.priority,
9250
+ ...this.startTenant(opts),
9010
9251
  createdAt: now,
9011
9252
  updatedAt: now
9012
9253
  };
@@ -9015,12 +9256,7 @@ var WorkflowEngine = class _WorkflowEngine {
9015
9256
  } catch (err) {
9016
9257
  const winner = await this.store.getRun(runId).catch(() => null);
9017
9258
  if (!winner) throw err;
9018
- return {
9019
- runId,
9020
- status: winner.status,
9021
- output: winner.output,
9022
- error: winner.error
9023
- };
9259
+ return this.existingStartResult(winner);
9024
9260
  }
9025
9261
  if (delayed) {
9026
9262
  this.emit({
@@ -9034,7 +9270,10 @@ var WorkflowEngine = class _WorkflowEngine {
9034
9270
  status: "suspended"
9035
9271
  };
9036
9272
  }
9037
- await this.dispatchRun(runId, run.priority, pendingStateKey(run.updatedAt));
9273
+ const runsLocally = this.customDispatcher === void 0 && !this.dispatchesOverTransport;
9274
+ if (!(runsLocally && registered === startOnly)) {
9275
+ await this.dispatchRun(runId, run.priority, pendingStateKey(run.updatedAt));
9276
+ }
9038
9277
  if (this.controlPlane && !this.queuesRunsOverTransport) {
9039
9278
  void this.controlPlane.publishControl({
9040
9279
  kind: "enqueued",
@@ -9047,13 +9286,125 @@ var WorkflowEngine = class _WorkflowEngine {
9047
9286
  status: "pending"
9048
9287
  };
9049
9288
  }
9050
- /** Read a run's current persisted state (or null if unknown). A thin pass-through to the store. */
9289
+ /**
9290
+ * The tenant columns a new run gets: an explicit `opts.tenantId` (`null` = none) wins, else the
9291
+ * context tenant when tenancy is on, else none (no keys at all, so a run row is unchanged when
9292
+ * tenancy is off).
9293
+ */
9294
+ startTenant(opts) {
9295
+ const tenant = opts?.tenantId !== void 0 ? opts.tenantId === null ? void 0 : {
9296
+ id: opts.tenantId,
9297
+ kind: opts.tenantKind
9298
+ } : this.tenancy?.current();
9299
+ if (!tenant) return {};
9300
+ return tenant.kind !== void 0 ? {
9301
+ tenantId: tenant.id,
9302
+ tenantKind: tenant.kind
9303
+ } : {
9304
+ tenantId: tenant.id
9305
+ };
9306
+ }
9307
+ /**
9308
+ * The context tenant a run started NOW would be stamped with (tenancy on), else undefined. For code
9309
+ * that records a start to replay it later outside the request, e.g. a transactional outbox.
9310
+ */
9311
+ contextTenant() {
9312
+ return this.tenancy?.current();
9313
+ }
9314
+ /**
9315
+ * The tenant whose debounce/batch accumulator a named event published now goes into: the
9316
+ * publisher's tenant, or `null` (the shared accumulator, no tenant) for a tenantless, `system` or
9317
+ * `all` publisher. Undefined when tenancy is off (the accumulator starts as it always did).
9318
+ */
9319
+ publishBatchTenant() {
9320
+ if (!this.tenancy) return void 0;
9321
+ const filter = this.tenantFilter();
9322
+ if (filter.mode !== "tenant") return null;
9323
+ const current = this.tenancy.current();
9324
+ return current?.id === filter.tenantId ? current : {
9325
+ id: filter.tenantId
9326
+ };
9327
+ }
9328
+ /**
9329
+ * The tenant whose debounce/batch accumulator `run`'s lifecycle event goes into: the run's own
9330
+ * (its publisher), or `null` for a run with no tenant. Undefined when tenancy is off.
9331
+ */
9332
+ lifecycleBatchTenant(run) {
9333
+ if (!this.tenancy) return void 0;
9334
+ return rowTenant(run) ?? null;
9335
+ }
9336
+ /** The matching filter for an app-facing call made now: `system` (sees all) when tenancy is off. */
9337
+ tenantFilter() {
9338
+ return this.tenancy?.filter() ?? {
9339
+ mode: "system"
9340
+ };
9341
+ }
9342
+ /**
9343
+ * The run `runId` if the caller may see it under the tenancy matching rule, else null — an
9344
+ * invisible run reads exactly like a missing one (not found, never forbidden).
9345
+ */
9346
+ visibleRun(runId) {
9347
+ const filter = this.restrictiveFilter();
9348
+ if (!filter) return this.store.getRun(runId);
9349
+ return this.store.getRun(runId).then((run) => run && tenantVisible(run, filter) ? run : null);
9350
+ }
9351
+ /**
9352
+ * What `start` returns for an id that already has a run. A run the caller may not see (tenancy)
9353
+ * returns its id and status only: never its output or error.
9354
+ */
9355
+ existingStartResult(run) {
9356
+ const filter = this.restrictiveFilter();
9357
+ if (filter && !tenantVisible(run, filter)) return {
9358
+ runId: run.id,
9359
+ status: run.status
9360
+ };
9361
+ return {
9362
+ runId: run.id,
9363
+ status: run.status,
9364
+ output: run.output,
9365
+ error: run.error
9366
+ };
9367
+ }
9368
+ /** The caller's filter when it can hide rows (`tenant` / `tenantless`), else undefined. */
9369
+ restrictiveFilter() {
9370
+ const filter = this.tenantFilter();
9371
+ return filter.mode === "system" || filter.mode === "all" ? void 0 : filter;
9372
+ }
9373
+ /**
9374
+ * True when the caller may NOT act on `runId` (it is missing or invisible to it). Callers guard
9375
+ * with `this.restrictiveFilter() && (await this.hidden(runId))`, so nothing is awaited when the
9376
+ * caller sees everything.
9377
+ */
9378
+ async hidden(runId) {
9379
+ return await this.visibleRun(runId) === null;
9380
+ }
9381
+ /**
9382
+ * Narrow `query` to the runs the caller may see (the tenancy matching rule). Use it before an
9383
+ * app-facing `store.listRuns`; a no-op when tenancy is off or the caller is `system`/`all`.
9384
+ */
9385
+ scopeRunQuery(query) {
9386
+ return scopeTenantQuery(query, this.tenantFilter());
9387
+ }
9388
+ /**
9389
+ * Run `fn` with `run`'s tenant restored as the context tenant (so a step body, a downstream lib and
9390
+ * every dispatched task's context carrier see it), whatever path drove the turn: a request, a
9391
+ * timer, a signal, recovery or a worker. A run with no tenant, or tenancy off, runs `fn` as is.
9392
+ */
9393
+ inRunTenant(run, fn) {
9394
+ const tenant = this.tenancy ? rowTenant(run) : void 0;
9395
+ return tenant && this.tenancy ? this.tenancy.run(tenant, fn) : fn();
9396
+ }
9397
+ /**
9398
+ * Read a run's current persisted state (or null if unknown). With tenancy on, a run of another
9399
+ * tenant reads as null (see {@link WorkflowEngineDeps.tenancy}).
9400
+ */
9051
9401
  getRun(runId) {
9052
- return this.store.getRun(runId);
9402
+ return this.visibleRun(runId);
9053
9403
  }
9054
- /** A run's full checkpoint timeline, ordered by seq. A thin pass-through to the store (it is what
9055
- * the testing kit's `captureHistory` reads, next to {@link getRun}). */
9056
- listCheckpoints(runId) {
9404
+ /** A run's full checkpoint timeline, ordered by seq (what the testing kit's `captureHistory`
9405
+ * reads, next to {@link getRun}). Empty for a run the caller may not see. */
9406
+ async listCheckpoints(runId) {
9407
+ if (this.restrictiveFilter() && await this.hidden(runId)) return [];
9057
9408
  return this.store.listCheckpoints(runId);
9058
9409
  }
9059
9410
  /**
@@ -9065,6 +9416,13 @@ var WorkflowEngine = class _WorkflowEngine {
9065
9416
  * terminal too.
9066
9417
  */
9067
9418
  resume(runId) {
9419
+ if (this.restrictiveFilter()) {
9420
+ return this.hidden(runId).then((hidden) => {
9421
+ if (hidden) throw new Error(`run ${runId} not found`);
9422
+ this.noteWakeReason(runId, void 0);
9423
+ return this.resumeRun(runId, true);
9424
+ });
9425
+ }
9068
9426
  this.noteWakeReason(runId, void 0);
9069
9427
  return this.resumeRun(runId, true);
9070
9428
  }
@@ -9691,7 +10049,7 @@ var WorkflowEngine = class _WorkflowEngine {
9691
10049
  result: settled2,
9692
10050
  dispatch: false
9693
10051
  };
9694
- if (settled2 === void 0) this.logUnregisteredSkip(run);
10052
+ if (settled2 === void 0 && !this.isStartOnlyHere(run)) this.logUnregisteredSkip(run);
9695
10053
  return void 0;
9696
10054
  }
9697
10055
  const settled = await this.countRecovery(run);
@@ -9943,10 +10301,12 @@ var WorkflowEngine = class _WorkflowEngine {
9943
10301
  await this.store.removeBufferedEvent(candidate.id);
9944
10302
  continue;
9945
10303
  }
9946
- if (!eventMatches(candidate.payload, match)) continue;
10304
+ const { payload, tenantIds } = readBufferedEvent(candidate.payload);
10305
+ if (!bufferedEventReaches(tenantIds, run.tenantId)) continue;
10306
+ if (!eventMatches(payload, match)) continue;
9947
10307
  if (!await this.store.removeBufferedEvent(candidate.id)) continue;
9948
10308
  await this.store.removeSignalWaiter(waiter);
9949
- const settled = await this.deliverSignal(waiter, candidate.payload, true);
10309
+ const settled = await this.deliverSignal(waiter, payload, true);
9950
10310
  return settled ?? {
9951
10311
  runId: run.id,
9952
10312
  status: run.status
@@ -9972,6 +10332,7 @@ var WorkflowEngine = class _WorkflowEngine {
9972
10332
  const run = await this.store.getRun(runId);
9973
10333
  const settled = run ? await this.settleUnregistered(run, nowMs) : null;
9974
10334
  if (settled !== void 0) return settled;
10335
+ if (run && this.isStartOnlyHere(run)) return null;
9975
10336
  }
9976
10337
  throw err;
9977
10338
  });
@@ -9984,6 +10345,7 @@ var WorkflowEngine = class _WorkflowEngine {
9984
10345
  * the HTTP request on workflow execution.
9985
10346
  */
9986
10347
  async requeue(runId, _seen) {
10348
+ if (_seen === void 0 && this.restrictiveFilter() && await this.hidden(runId)) return null;
9987
10349
  const seen = _seen ?? /* @__PURE__ */ new Set();
9988
10350
  if (seen.has(runId)) return null;
9989
10351
  seen.add(runId);
@@ -10091,7 +10453,7 @@ var WorkflowEngine = class _WorkflowEngine {
10091
10453
  * run's current status (with the count re-dispatched), or null if the run is unknown.
10092
10454
  */
10093
10455
  async redispatchPending(runId) {
10094
- const run = await this.store.getRun(runId);
10456
+ const run = await this.visibleRun(runId);
10095
10457
  if (!run) return null;
10096
10458
  const pending = (await this.store.listCheckpoints(runId)).filter((cp) => cp.kind === "remote" && cp.status === "pending");
10097
10459
  let redispatched = 0;
@@ -10106,7 +10468,7 @@ var WorkflowEngine = class _WorkflowEngine {
10106
10468
  startedAt: reEnqueuedAt,
10107
10469
  finishedAt: reEnqueuedAt
10108
10470
  });
10109
- await this.dispatchRemoteTask({
10471
+ await this.inRunTenant(run, () => this.dispatchRemoteTask({
10110
10472
  runId,
10111
10473
  seq: cp.seq,
10112
10474
  name: cp.name,
@@ -10114,7 +10476,7 @@ var WorkflowEngine = class _WorkflowEngine {
10114
10476
  group: cp.workerGroup ?? sanitizeQueueToken(cp.name),
10115
10477
  input: cp.input,
10116
10478
  attempt: reAttempt
10117
- });
10479
+ }));
10118
10480
  redispatched += 1;
10119
10481
  }
10120
10482
  return {
@@ -10129,12 +10491,13 @@ var WorkflowEngine = class _WorkflowEngine {
10129
10491
  * the original stays inspectable. Returns the new run's id, or null if `runId` is unknown.
10130
10492
  */
10131
10493
  async retryWithInput(runId, input, newRunId) {
10132
- const run = await this.store.getRun(runId);
10494
+ const run = await this.visibleRun(runId);
10133
10495
  if (!run) return null;
10134
10496
  const id = newRunId ?? `${runId}~retry~${globalThis.crypto.randomUUID().slice(0, 8)}`;
10135
10497
  await this.start(run.workflow, input, id, {
10136
10498
  tags: run.tags,
10137
- namespace: run.namespace
10499
+ namespace: run.namespace,
10500
+ ...inheritTenant(run)
10138
10501
  });
10139
10502
  return {
10140
10503
  runId: id
@@ -10183,6 +10546,7 @@ var WorkflowEngine = class _WorkflowEngine {
10183
10546
  output: run.output,
10184
10547
  error: run.error
10185
10548
  }), "toResult");
10549
+ const filter = this.restrictiveFilter();
10186
10550
  return new Promise((resolve, reject) => {
10187
10551
  let done = false;
10188
10552
  let off = /* @__PURE__ */ __name(() => {
@@ -10213,6 +10577,10 @@ var WorkflowEngine = class _WorkflowEngine {
10213
10577
  const check = /* @__PURE__ */ __name(() => {
10214
10578
  if (done) return;
10215
10579
  void this.store.getRun(runId).then((run) => {
10580
+ if (run && filter && !tenantVisible(run, filter)) {
10581
+ fail(new Error(`run ${runId} not found`));
10582
+ return;
10583
+ }
10216
10584
  if (run && isSettled(run)) finish(run);
10217
10585
  }, fail);
10218
10586
  }, "check");
@@ -10261,6 +10629,7 @@ var WorkflowEngine = class _WorkflowEngine {
10261
10629
  if (error2 instanceof WorkflowNotRegistered) {
10262
10630
  const settled = await this.settleUnregistered(run, this.clock()).catch(() => void 0);
10263
10631
  if (settled) return settled;
10632
+ if (this.isStartOnlyHere(run)) return void 0;
10264
10633
  }
10265
10634
  console.error(`[nestjs-durable] could not resume run ${run.id} (${run.workflow}@${run.workflowVersion}); leaving it for another instance:`, error2);
10266
10635
  return void 0;
@@ -10290,7 +10659,7 @@ var WorkflowEngine = class _WorkflowEngine {
10290
10659
  if (error2 instanceof WorkflowNotRegistered) {
10291
10660
  const settled = await this.settleUnregistered(run, nowMs).catch(() => void 0);
10292
10661
  if (settled) results.push(settled);
10293
- if (settled !== void 0) continue;
10662
+ if (settled !== void 0 || this.isStartOnlyHere(run)) continue;
10294
10663
  }
10295
10664
  console.error(`[nestjs-durable] could not resume run ${run.id} (${run.workflow}@${run.workflowVersion}); leaving it for another instance:`, error2);
10296
10665
  } finally {
@@ -10329,17 +10698,23 @@ var WorkflowEngine = class _WorkflowEngine {
10329
10698
  */
10330
10699
  async publishEvent(name, payload, opts) {
10331
10700
  let touched = 0;
10701
+ const filter = this.restrictiveFilter();
10702
+ const reaches = /* @__PURE__ */ __name(async (runId) => {
10703
+ if (!filter) return true;
10704
+ const run = await this.store.getRun(runId);
10705
+ return run !== null && tenantVisible(run, filter);
10706
+ }, "reaches");
10332
10707
  const waiters = await this.store.listSignalWaiters(eventPrefix(name));
10333
10708
  for (const w of waiters) {
10334
- if (eventMatches(payload, eventMatchOf(w.token))) {
10335
- await this.signal(w.token, payload);
10709
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10710
+ await this.signalUnchecked(w.token, payload);
10336
10711
  touched += 1;
10337
10712
  }
10338
10713
  }
10339
10714
  const remote = await this.announcedRemoteSubscribers(name, null);
10340
10715
  if (this.eventTriggers.get(name)?.size || remote.length > 0) {
10341
10716
  const eventId = opts?.id ?? globalThis.crypto.randomUUID();
10342
- const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote);
10717
+ const { reached, failed } = await this.startSubscribers(name, payload, (workflow) => `evt:${eventId}:${workflow}`, void 0, remote, void 0, this.publishBatchTenant());
10343
10718
  touched += reached.length;
10344
10719
  for (const { workflow, error: error2 } of failed) {
10345
10720
  console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error2);
@@ -10349,12 +10724,18 @@ var WorkflowEngine = class _WorkflowEngine {
10349
10724
  const bufferedId = globalThis.crypto.randomUUID();
10350
10725
  await this.store.bufferEvent({
10351
10726
  name,
10352
- payload,
10727
+ payload: scopeBufferedEvent(payload, filter ? tenantIdsFor(filter) : void 0),
10353
10728
  id: bufferedId,
10354
10729
  publishedAt: this.clock()
10355
10730
  });
10356
10731
  const lateWaiters = await this.store.listSignalWaiters(eventPrefix(name));
10357
- const lateWaiter = lateWaiters.find((w) => eventMatches(payload, eventMatchOf(w.token)));
10732
+ let lateWaiter;
10733
+ for (const w of lateWaiters) {
10734
+ if (eventMatches(payload, eventMatchOf(w.token)) && await reaches(w.runId)) {
10735
+ lateWaiter = w;
10736
+ break;
10737
+ }
10738
+ }
10358
10739
  if (!lateWaiter) return touched;
10359
10740
  if (!await this.store.removeBufferedEvent(bufferedId)) return touched;
10360
10741
  const waiter = await this.store.takeSignalWaiter(lateWaiter.token);
@@ -10661,7 +11042,23 @@ var WorkflowEngine = class _WorkflowEngine {
10661
11042
  * Either way, the destructive `take*` ops (on the waiter row, on the buffer) arbitrate: whichever
10662
11043
  * side actually removes the row is the one that delivers, so a signal is never delivered twice.
10663
11044
  */
10664
- async signal(token, payload, opts) {
11045
+ signal(token, payload, opts) {
11046
+ const filter = parseWebhookToken(token) ? void 0 : this.restrictiveFilter();
11047
+ if (!filter) return this.signalUnchecked(token, payload, opts);
11048
+ return this.signalTargetVisible(token, filter).then((visible) => visible ? this.signalUnchecked(token, payload, opts) : null);
11049
+ }
11050
+ /**
11051
+ * False when a run waits on `token` and `filter` may not see it (the tenancy matching rule). A
11052
+ * token nobody waits on yet is buffered as before (there is no run to check).
11053
+ */
11054
+ async signalTargetVisible(token, filter) {
11055
+ const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);
11056
+ if (!waiter) return true;
11057
+ const run = await this.store.getRun(waiter.runId);
11058
+ return !run || tenantVisible(run, filter);
11059
+ }
11060
+ /** {@link signal} without the tenancy check — the engine's own deliveries. */
11061
+ async signalUnchecked(token, payload, opts) {
10665
11062
  const id = opts?.id;
10666
11063
  if (id === void 0) return this.deliverOrBuffer(token, payload);
10667
11064
  if (!this.store.claimSignalId) {
@@ -10745,14 +11142,16 @@ var WorkflowEngine = class _WorkflowEngine {
10745
11142
  * null if no run is waiting on the task (e.g. a duplicate/late delivery) — a safe no-op.
10746
11143
  */
10747
11144
  async completeTask(runId, name, result) {
10748
- return this.signal(`task:${runId}:${name}`, {
11145
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
11146
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10749
11147
  ok: true,
10750
11148
  value: result
10751
11149
  });
10752
11150
  }
10753
11151
  /** Report that a `ctx.task` failed — the run resumes and throws a FatalError at the task. */
10754
11152
  async failTask(runId, name, error2) {
10755
- return this.signal(`task:${runId}:${name}`, {
11153
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
11154
+ return this.signalUnchecked(`task:${runId}:${name}`, {
10756
11155
  ok: false,
10757
11156
  error: error2
10758
11157
  });
@@ -10791,7 +11190,7 @@ var WorkflowEngine = class _WorkflowEngine {
10791
11190
  if (cancelled) return;
10792
11191
  const childId = token.slice(CHILD_TOKEN_PREFIX.length);
10793
11192
  if (!await childCompletionNeedsBuffer(this.store, childId, completion)) return;
10794
- await this.signal(token, completion);
11193
+ await this.signalUnchecked(token, completion);
10795
11194
  return;
10796
11195
  } catch (err) {
10797
11196
  if (err instanceof NamespaceMismatch) return;
@@ -10840,7 +11239,12 @@ var WorkflowEngine = class _WorkflowEngine {
10840
11239
  * steps' compensations run in reverse (visible as `compensate:<step>` events), then it's marked
10841
11240
  * cancelled. Without it, cancellation is immediate (no undo).
10842
11241
  */
10843
- async cancel(runId, opts) {
11242
+ cancel(runId, opts) {
11243
+ if (!this.restrictiveFilter()) return this.cancelUnchecked(runId, opts);
11244
+ return this.hidden(runId).then((hidden) => hidden ? null : this.cancelUnchecked(runId, opts));
11245
+ }
11246
+ /** {@link cancel} without the tenancy check — the engine's own cascades and bulk paths. */
11247
+ async cancelUnchecked(runId, opts) {
10844
11248
  const run = await this.store.getRun(runId);
10845
11249
  if (!run) return null;
10846
11250
  if (TERMINAL_RUN_STATUSES.includes(run.status)) {
@@ -10922,10 +11326,10 @@ var WorkflowEngine = class _WorkflowEngine {
10922
11326
  * their terminal status — `cancel` is a no-op on them, never clobbering a completed/dead run).
10923
11327
  */
10924
11328
  async cancelWhere(filter, opts) {
10925
- const runs = await this.store.listRuns(filter);
11329
+ const runs = await this.store.listRuns(this.scopeRunQuery(filter));
10926
11330
  const results = [];
10927
11331
  for (const run of runs) {
10928
- const r = await this.cancel(run.id, opts);
11332
+ const r = await this.cancelUnchecked(run.id, opts);
10929
11333
  if (r) results.push(r);
10930
11334
  }
10931
11335
  return results;
@@ -10941,11 +11345,16 @@ var WorkflowEngine = class _WorkflowEngine {
10941
11345
  * its worker (its next checkpoint write fails). Returns the number of runs deleted (0 if absent).
10942
11346
  */
10943
11347
  async deleteRun(runId) {
11348
+ if (this.restrictiveFilter() && await this.hidden(runId)) return 0;
11349
+ return await this.deleteRunUnchecked(runId);
11350
+ }
11351
+ /** {@link deleteRun} without the tenancy check (its own subtree recursion). */
11352
+ async deleteRunUnchecked(runId) {
10944
11353
  const run = await this.store.getRun(runId);
10945
11354
  if (!run) return 0;
10946
11355
  let deleted = 0;
10947
- for (const childId of await this.getRunChildren(runId)) {
10948
- deleted += await this.deleteRun(childId);
11356
+ for (const childId of await this.runChildrenUnchecked(runId)) {
11357
+ deleted += await this.deleteRunUnchecked(childId);
10949
11358
  }
10950
11359
  await this.store.deleteRun(runId);
10951
11360
  return deleted + 1;
@@ -10974,6 +11383,7 @@ var WorkflowEngine = class _WorkflowEngine {
10974
11383
  if (!isNonEmptyRunScope(scope)) {
10975
11384
  throw new Error("purgeRuns: refusing an empty scope (it would delete every run) \u2014 pass at least one predicate, e.g. { namespace }");
10976
11385
  }
11386
+ const scoped = this.scopeRunQuery(scope);
10977
11387
  const batchSize = Math.max(1, opts?.batchSize ?? 500);
10978
11388
  const cancelLive = opts?.cancelLive ?? true;
10979
11389
  const withChildren = opts?.children ?? true;
@@ -10984,7 +11394,7 @@ var WorkflowEngine = class _WorkflowEngine {
10984
11394
  let previous = "";
10985
11395
  for (; ; ) {
10986
11396
  const batch = await this.store.listRuns({
10987
- ...scope,
11397
+ ...scoped,
10988
11398
  statuses,
10989
11399
  limit: batchSize
10990
11400
  });
@@ -11005,7 +11415,7 @@ var WorkflowEngine = class _WorkflowEngine {
11005
11415
  if (status === void 0) continue;
11006
11416
  if (!TERMINAL_RUN_STATUSES.includes(status)) {
11007
11417
  if (!cancelLive) continue;
11008
- await this.cancel(id).catch(() => void 0);
11418
+ await this.cancelUnchecked(id).catch(() => void 0);
11009
11419
  }
11010
11420
  doomed.push(id);
11011
11421
  }
@@ -11066,10 +11476,10 @@ var WorkflowEngine = class _WorkflowEngine {
11066
11476
  * explicitly cancelled one's does, or the children are orphans nobody is holding a reference to.
11067
11477
  */
11068
11478
  async cancelChildren(parentRunId, opts) {
11069
- for (const id of await this.getRunChildren(parentRunId)) {
11479
+ for (const id of await this.runChildrenUnchecked(parentRunId)) {
11070
11480
  const child = await this.store.getRun(id).catch(() => null);
11071
11481
  if (child?.tags?.includes(`${PARENT_CLOSE_TAG_PREFIX}abandon`)) continue;
11072
- await this.cancel(id, opts).catch(() => void 0);
11482
+ await this.cancelUnchecked(id, opts).catch(() => void 0);
11073
11483
  }
11074
11484
  }
11075
11485
  /**
@@ -11087,7 +11497,7 @@ var WorkflowEngine = class _WorkflowEngine {
11087
11497
  if (event.type === "run.suspended") return;
11088
11498
  for (const [childId, policy] of intents) {
11089
11499
  if (policy === "abandon") continue;
11090
- queueMicrotask(() => void this.cancel(childId, {
11500
+ queueMicrotask(() => void this.cancelUnchecked(childId, {
11091
11501
  compensate: policy === "cancel"
11092
11502
  }).catch(() => void 0));
11093
11503
  }
@@ -11111,7 +11521,13 @@ var WorkflowEngine = class _WorkflowEngine {
11111
11521
  parentRunId
11112
11522
  ])).filter((w) => w.token.startsWith("child:") && !isAnyMember(w)).map((w) => w.token.slice("child:".length));
11113
11523
  }
11524
+ /** The child runs of `parentRunId`; empty for a parent the caller may not see. */
11114
11525
  async getRunChildren(parentRunId) {
11526
+ if (this.restrictiveFilter() && await this.hidden(parentRunId)) return [];
11527
+ return this.runChildrenUnchecked(parentRunId);
11528
+ }
11529
+ /** {@link getRunChildren} without the tenancy check (the engine's own subtree walks). */
11530
+ async runChildrenUnchecked(parentRunId) {
11115
11531
  const childIds = new Set(await this.awaitedChildIds(parentRunId));
11116
11532
  const prefixes = CHILD_EDGE_PREFIXES;
11117
11533
  const childCheckpoints = this.store.listCheckpointsByNamePrefix ? await this.store.listCheckpointsByNamePrefix(parentRunId, prefixes) : (await this.store.listCheckpoints(parentRunId)).filter((cp) => prefixes.some((p) => cp.name.startsWith(p)));
@@ -11472,7 +11888,7 @@ var WorkflowEngine = class _WorkflowEngine {
11472
11888
  const served = /* @__PURE__ */ new Set();
11473
11889
  this.turnServedWakes.set(run.id, served);
11474
11890
  if (registered?.remote) await this.noteServedWakes(run.id);
11475
- const result = registered?.remote ? await this.runRemoteExecution(run, registered) : await this.runExecution(run, fn, registered);
11891
+ const result = await this.inRunTenant(run, () => registered?.remote ? this.runRemoteExecution(run, registered) : this.runExecution(run, fn, registered));
11476
11892
  if (registered?.singleton && (result.status === "completed" || result.status === "failed" || result.status === "cancelled" || result.status === "dead")) {
11477
11893
  void this.singletons.wakeNext(run).catch(() => void 0);
11478
11894
  }
@@ -11788,7 +12204,8 @@ var WorkflowEngine = class _WorkflowEngine {
11788
12204
  error: error2
11789
12205
  });
11790
12206
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11791
- namespace: run.namespace
12207
+ namespace: run.namespace,
12208
+ ...inheritTenant(run)
11792
12209
  });
11793
12210
  return {
11794
12211
  kind: "suspended"
@@ -11835,7 +12252,8 @@ var WorkflowEngine = class _WorkflowEngine {
11835
12252
  if (!handlerRun) {
11836
12253
  const handler = handoff.input;
11837
12254
  this.startChildDeferred(handler.workflow, handler.input, handlerId, {
11838
- namespace: run.namespace
12255
+ namespace: run.namespace,
12256
+ ...inheritTenant(run)
11839
12257
  });
11840
12258
  }
11841
12259
  return {
@@ -12620,7 +13038,8 @@ ${run.workflowVersion}`;
12620
13038
  const existingChild = await this.store.getRun(childId);
12621
13039
  if (!existingChild) {
12622
13040
  this.startChildDeferred(cmd.workflow, cmd.input, childId, {
12623
- namespace: run.namespace
13041
+ namespace: run.namespace,
13042
+ ...inheritTenant(run)
12624
13043
  });
12625
13044
  } else {
12626
13045
  this.redeliverFinishedChild(childId, existingChild);
@@ -12739,7 +13158,7 @@ ${run.workflowVersion}`;
12739
13158
  this.awaitedRemoteSteps.set(run.id, awaitedSteps);
12740
13159
  const awaitedFans = [];
12741
13160
  this.awaitedStepFans.set(run.id, awaitedFans);
12742
- const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
13161
+ const ctx = warm ? void 0 : createWorkflowCtx(this.ctxHostFor(replay, run.namespace, cont, inheritTenant(run)), run.id, compensations, run.workflow, registered?.searchAttributesSchema);
12743
13162
  try {
12744
13163
  const handoff = liveHandoff(run.id, snapshot);
12745
13164
  if (handoff && !this.cancelRequested.has(run.id)) {
@@ -12797,7 +13216,7 @@ ${run.workflowVersion}`;
12797
13216
  value: void 0
12798
13217
  });
12799
13218
  const nextId = nextContinuationId(run.id);
12800
- queueMicrotask(() => void this.start(run.workflow, err.input, nextId).catch(() => void 0));
13219
+ queueMicrotask(() => void this.start(run.workflow, err.input, nextId, inheritTenant(run)).catch(() => void 0));
12801
13220
  return {
12802
13221
  runId: run.id,
12803
13222
  status: "completed"
@@ -13070,7 +13489,7 @@ ${run.workflowVersion}`;
13070
13489
  /** The seam handed to {@link createWorkflowCtx}: the authoring API reaches durability + lifecycle
13071
13490
  * (checkpointing, dispatch, child start) through this, so the ctx primitives live in their own
13072
13491
  * module and the engine stays the orchestrator. */
13073
- ctxHostFor(replay, parentNamespace, sticky) {
13492
+ ctxHostFor(replay, parentNamespace, sticky, parentTenant) {
13074
13493
  return {
13075
13494
  store: this.store,
13076
13495
  replay,
@@ -13117,6 +13536,8 @@ ${run.workflowVersion}`;
13117
13536
  this.startChildDeferred(workflow, input, id, {
13118
13537
  priority,
13119
13538
  namespace: parentNamespace,
13539
+ // The child belongs to the parent's customer, whichever instance or context drives it.
13540
+ ...parentTenant,
13120
13541
  // Absent unless the body pinned one (`ctx.child(ref, input, { version })`) — an omitted
13121
13542
  // pin must stay omitted, so the child keeps resolving `latest` exactly as before.
13122
13543
  version,
@@ -13140,7 +13561,7 @@ ${run.workflowVersion}`;
13140
13561
  // idempotent on a terminal/cancelled run (returns its existing status without side effects), so
13141
13562
  // no extra guard is needed here for the failFast replay case (re-issuing the same cancel calls).
13142
13563
  cancelChild: /* @__PURE__ */ __name((childId) => {
13143
- queueMicrotask(() => void this.cancel(childId).catch(() => void 0));
13564
+ queueMicrotask(() => void this.cancelUnchecked(childId).catch(() => void 0));
13144
13565
  }, "cancelChild"),
13145
13566
  // Shallow-merge into the run's searchAttributes (the ctx primitive makes this exactly-once).
13146
13567
  upsertSearchAttributes: /* @__PURE__ */ __name(async (runId, attrs) => {
@@ -13167,7 +13588,7 @@ ${run.workflowVersion}`;
13167
13588
  console.warn(`[nestjs-durable] waking entity "${name}" key "${key}" failed (its op stays buffered for the next wake):`, err);
13168
13589
  }));
13169
13590
  }, "kickEntity"),
13170
- interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body), "interceptStep")
13591
+ interceptStep: /* @__PURE__ */ __name((invocation, body) => this.interceptStep(invocation, body, parentTenant), "interceptStep")
13171
13592
  };
13172
13593
  }
13173
13594
  /**
@@ -13176,10 +13597,11 @@ ${run.workflowVersion}`;
13176
13597
  * paused at a breakpoint.
13177
13598
  */
13178
13599
  async continue(runId) {
13600
+ if (this.restrictiveFilter() && await this.hidden(runId)) return null;
13179
13601
  const checkpoints = await this.store.listCheckpoints(runId);
13180
13602
  const bp = checkpoints.find(isBreakpoint);
13181
13603
  if (!bp) return null;
13182
- return this.signal(breakpointToken(runId, bp.seq), void 0);
13604
+ return this.signalUnchecked(breakpointToken(runId, bp.seq), void 0);
13183
13605
  }
13184
13606
  /**
13185
13607
  * Read the latest value a run published for `key` via {@link WorkflowCtx.setEvent} — a
@@ -13187,6 +13609,7 @@ ${run.workflowVersion}`;
13187
13609
  * never published that key. The suspend-model counterpart of a Temporal query.
13188
13610
  */
13189
13611
  async getEvent(runId, key) {
13612
+ if (this.restrictiveFilter() && await this.hidden(runId)) return void 0;
13190
13613
  const name = `event:${key}`;
13191
13614
  if (this.store.getLatestCheckpointByName) {
13192
13615
  const latest2 = await this.store.getLatestCheckpointByName(runId, name);
@@ -13211,7 +13634,7 @@ ${run.workflowVersion}`;
13211
13634
  * if nothing was waiting — a too-early or duplicate update).
13212
13635
  */
13213
13636
  async update(runId, name, arg) {
13214
- const run = await this.store.getRun(runId);
13637
+ const run = await this.visibleRun(runId);
13215
13638
  if (!run) return {
13216
13639
  accepted: false,
13217
13640
  reason: `run ${runId} not found`
@@ -13231,7 +13654,7 @@ ${run.workflowVersion}`;
13231
13654
  };
13232
13655
  }
13233
13656
  }
13234
- const result = await this.signal(`update:${runId}:${name}`, arg);
13657
+ const result = await this.signalUnchecked(`update:${runId}:${name}`, arg);
13235
13658
  return {
13236
13659
  accepted: true,
13237
13660
  run: result
@@ -16416,6 +16839,9 @@ var InMemoryStateStore = class {
16416
16839
  if (query.origins) {
16417
16840
  runs = runs.filter((r) => query.origins?.includes(r.origin ?? null));
16418
16841
  }
16842
+ if (query.tenantId !== void 0 || query.tenantIds !== void 0) {
16843
+ runs = runs.filter((r) => matchesTenantPredicates(r, query));
16844
+ }
16419
16845
  if (query.attributes?.length) {
16420
16846
  let candidates = null;
16421
16847
  for (const f of query.attributes) {
@@ -16489,7 +16915,7 @@ var InMemoryStateStore = class {
16489
16915
  async listSchedules(query) {
16490
16916
  const rows = [
16491
16917
  ...this.schedules.values()
16492
- ].filter((s) => query.namespace === void 0 || s.namespace === query.namespace).filter((s) => query.workflow === void 0 || s.workflow === query.workflow).filter((s) => query.tag === void 0 || (s.tags ?? []).includes(query.tag)).filter((s) => query.paused === void 0 || s.paused === query.paused).filter((s) => query.dueBy === void 0 || !s.paused && s.nextFireAt !== null && s.nextFireAt <= query.dueBy).sort((a, b) => (a.nextFireAt ?? Number.POSITIVE_INFINITY) - (b.nextFireAt ?? Number.POSITIVE_INFINITY) || a.id.localeCompare(b.id));
16918
+ ].filter((s) => query.namespace === void 0 || s.namespace === query.namespace).filter((s) => query.workflow === void 0 || s.workflow === query.workflow).filter((s) => query.tag === void 0 || (s.tags ?? []).includes(query.tag)).filter((s) => query.paused === void 0 || s.paused === query.paused).filter((s) => matchesTenantPredicates(s, query)).filter((s) => query.dueBy === void 0 || !s.paused && s.nextFireAt !== null && s.nextFireAt <= query.dueBy).sort((a, b) => (a.nextFireAt ?? Number.POSITIVE_INFINITY) - (b.nextFireAt ?? Number.POSITIVE_INFINITY) || a.id.localeCompare(b.id));
16493
16919
  const offset = query.offset ?? 0;
16494
16920
  return rows.slice(offset, query.limit != null ? offset + query.limit : void 0).map((s) => structuredClone(s));
16495
16921
  }
@@ -16861,6 +17287,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16861
17287
  axisIsRunColumn,
16862
17288
  bindWorkflowClass,
16863
17289
  breakpointToken,
17290
+ bufferedEventReaches,
16864
17291
  buildWorkflowDirectory,
16865
17292
  canRoute,
16866
17293
  capableWorkers,
@@ -16908,6 +17335,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16908
17335
  hmacTenantVerifier,
16909
17336
  indexWaitersByRun,
16910
17337
  info,
17338
+ inheritTenant,
16911
17339
  isAnyCheckpoint,
16912
17340
  isAnyMember,
16913
17341
  isEngineMintedTag,
@@ -16934,6 +17362,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16934
17362
  log,
16935
17363
  markRemoteEvent,
16936
17364
  matchesAttributes,
17365
+ matchesTenantPredicates,
16937
17366
  mergeRunFacetRows,
16938
17367
  mergeRunValueFacetRows,
16939
17368
  missingCapabilities,
@@ -16958,6 +17387,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16958
17387
  prevCronFireMs,
16959
17388
  prevRRuleFireMs,
16960
17389
  queryCheckpointsOf,
17390
+ readBufferedEvent,
16961
17391
  readRunsByIds,
16962
17392
  readSearchAttributes,
16963
17393
  requiredCapabilities,
@@ -16969,6 +17399,7 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16969
17399
  retentionKeeps,
16970
17400
  retiredHandoffName,
16971
17401
  routeFor,
17402
+ rowTenant,
16972
17403
  runCompletedEvent,
16973
17404
  runDetailEtag,
16974
17405
  runDurableExecution,
@@ -16986,6 +17417,8 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
16986
17417
  sanitizeQueueToken,
16987
17418
  scheduleRunIdAt,
16988
17419
  scheduledRunId,
17420
+ scopeBufferedEvent,
17421
+ scopeTenantQuery,
16989
17422
  settleResultsWithPlainCalls,
16990
17423
  signTenantToken,
16991
17424
  singletonAdmissionDenialPatch,
@@ -17002,6 +17435,8 @@ __name(settleResultsWithPlainCalls, "settleResultsWithPlainCalls");
17002
17435
  summarizeRunFromStore,
17003
17436
  summarizeTimeline,
17004
17437
  tenantGroup,
17438
+ tenantIdsFor,
17439
+ tenantVisible,
17005
17440
  toEventSubscription,
17006
17441
  traceIdOfTraceparent,
17007
17442
  triggerFailedSubscribersOf,