@cadenza.io/service 2.20.1 → 2.21.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.
@@ -105,6 +105,30 @@ var LOCAL_ROUTINE_PERSISTENCE_KEYS = [
105
105
  "__routineCreatedAt",
106
106
  "__routineIsMeta"
107
107
  ];
108
+ var BULKY_EXECUTION_PERSISTENCE_KEYS = [
109
+ "rows",
110
+ "joinedContexts",
111
+ "serviceInstances",
112
+ "serviceInstanceLeases",
113
+ "serviceInstanceTransports",
114
+ "serviceManifests",
115
+ "tasks",
116
+ "helpers",
117
+ "globals",
118
+ "signals",
119
+ "intents",
120
+ "actors",
121
+ "routines",
122
+ "directionalTaskMaps",
123
+ "actorTaskMaps",
124
+ "taskToRoutineMaps",
125
+ "taskToHelperMaps",
126
+ "helperToHelperMaps",
127
+ "taskToGlobalMaps",
128
+ "helperToGlobalMaps",
129
+ "signalToTaskMaps",
130
+ "intentToTaskMaps"
131
+ ];
108
132
  function readHintValue(source, key) {
109
133
  if (!source || typeof source !== "object") {
110
134
  return void 0;
@@ -131,8 +155,80 @@ function stripLocalRoutinePersistenceHints(input) {
131
155
  }
132
156
  return context;
133
157
  }
158
+ function summarizeQueryData(queryData) {
159
+ if (!queryData || typeof queryData !== "object") {
160
+ return void 0;
161
+ }
162
+ const summary = {};
163
+ if (queryData.data && typeof queryData.data === "object") {
164
+ summary.dataKeys = Object.keys(queryData.data).sort();
165
+ }
166
+ if (queryData.filter && typeof queryData.filter === "object") {
167
+ summary.filterKeys = Object.keys(queryData.filter).sort();
168
+ }
169
+ if (queryData.onConflict && typeof queryData.onConflict === "object") {
170
+ const onConflict = queryData.onConflict;
171
+ summary.onConflictTarget = Array.isArray(onConflict.target) ? [...onConflict.target] : onConflict.target ?? null;
172
+ }
173
+ return Object.keys(summary).length > 0 ? summary : void 0;
174
+ }
175
+ function sanitizeExecutionPersistenceContext(input) {
176
+ const context = stripLocalRoutinePersistenceHints(input);
177
+ for (const key of BULKY_EXECUTION_PERSISTENCE_KEYS) {
178
+ const value = context[key];
179
+ if (value === void 0) {
180
+ continue;
181
+ }
182
+ const countKey = `${key}Count`;
183
+ if (context[countKey] === void 0) {
184
+ if (Array.isArray(value)) {
185
+ context[countKey] = value.length;
186
+ } else if (value && typeof value === "object") {
187
+ context[countKey] = Object.keys(value).length;
188
+ }
189
+ }
190
+ delete context[key];
191
+ }
192
+ if (context.queryData && typeof context.queryData === "object") {
193
+ const queryDataSummary = summarizeQueryData(context.queryData);
194
+ if (queryDataSummary) {
195
+ context.queryData = queryDataSummary;
196
+ } else {
197
+ delete context.queryData;
198
+ }
199
+ }
200
+ return context;
201
+ }
202
+ function sanitizeExecutionPersistenceResultPayload(input) {
203
+ const payload = input && typeof input === "object" ? { ...input } : {};
204
+ const resultContext = payload.resultContext && typeof payload.resultContext === "object" ? sanitizeExecutionPersistenceContext(
205
+ payload.resultContext
206
+ ) : payload.resultContext;
207
+ const metaResultContext = payload.metaResultContext && typeof payload.metaResultContext === "object" ? sanitizeExecutionPersistenceContext(
208
+ payload.metaResultContext
209
+ ) : payload.metaResultContext;
210
+ const snakeResultContext = payload.result_context && typeof payload.result_context === "object" ? sanitizeExecutionPersistenceContext(
211
+ payload.result_context
212
+ ) : payload.result_context;
213
+ const snakeMetaResultContext = payload.meta_result_context && typeof payload.meta_result_context === "object" ? sanitizeExecutionPersistenceContext(
214
+ payload.meta_result_context
215
+ ) : payload.meta_result_context;
216
+ if (resultContext !== void 0) {
217
+ payload.resultContext = resultContext;
218
+ }
219
+ if (metaResultContext !== void 0) {
220
+ payload.metaResultContext = metaResultContext;
221
+ }
222
+ if (snakeResultContext !== void 0) {
223
+ payload.result_context = snakeResultContext;
224
+ }
225
+ if (snakeMetaResultContext !== void 0) {
226
+ payload.meta_result_context = snakeMetaResultContext;
227
+ }
228
+ return payload;
229
+ }
134
230
  function splitRoutinePersistenceContext(input) {
135
- const sanitized = stripLocalRoutinePersistenceHints(input);
231
+ const sanitized = sanitizeExecutionPersistenceContext(input);
136
232
  return {
137
233
  context: Object.fromEntries(
138
234
  Object.entries(sanitized).filter(([key]) => !key.startsWith("__"))
@@ -321,6 +417,90 @@ function ensureDelegationContextMetadata(input) {
321
417
 
322
418
  // src/graph/definition/DeputyTask.ts
323
419
  var SERVICE_REGISTRY_TRACE_SERVICE = (process.env.CADENZA_SERVICE_REGISTRY_TRACE_SERVICE ?? "").trim();
420
+ function deputyTaskExecutor(context, emit2, inquire, _tools, progressCallback) {
421
+ const task = this;
422
+ return new Promise((resolve, reject) => {
423
+ if (context.__metadata.__blockRemoteExecution) {
424
+ reject(new Error("Blocked remote execution"));
425
+ return;
426
+ }
427
+ if (context.__metadata.__skipRemoteExecution) {
428
+ resolve(context);
429
+ return;
430
+ }
431
+ const processId = (0, import_uuid2.v4)();
432
+ context.__metadata.__deputyExecId = processId;
433
+ if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
434
+ console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
435
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
436
+ localTaskName: context.__localTaskName ?? null,
437
+ remoteRoutineName: context.__remoteRoutineName ?? null,
438
+ targetServiceName: context.__serviceName ?? null,
439
+ deputyExecId: processId,
440
+ dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
441
+ queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
442
+ queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
443
+ });
444
+ }
445
+ emit2("meta.deputy.delegation_requested", {
446
+ ...context
447
+ });
448
+ CadenzaService.createEphemeralMetaTask(
449
+ `On progress deputy ${task.remoteRoutineName}`,
450
+ (ctx) => {
451
+ if (typeof progressCallback === "function" && ctx.progress) {
452
+ progressCallback(ctx.progress * ctx.weight);
453
+ }
454
+ },
455
+ `Ephemeral task for deputy process ${processId}`,
456
+ {
457
+ once: false,
458
+ destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
459
+ register: false
460
+ }
461
+ ).doOn(
462
+ `meta.socket_client.delegation_progress:${processId}`,
463
+ `meta.socket_client.delegated:${processId}`,
464
+ `meta.fetch.delegated:${processId}`,
465
+ `meta.service_registry.load_balance_failed:${processId}`
466
+ );
467
+ CadenzaService.createEphemeralMetaTask(
468
+ `Resolve deputy ${task.remoteRoutineName}`,
469
+ (responseCtx) => {
470
+ const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
471
+ ...context,
472
+ ...responseCtx
473
+ } : responseCtx;
474
+ if (responseCtx?.errored) {
475
+ reject(new Error(responseCtx.__error));
476
+ } else {
477
+ if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
478
+ console.log(
479
+ "[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved",
480
+ {
481
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
482
+ targetServiceName: context.__serviceName ?? null,
483
+ resolverRequestId: context.__resolverRequestId ?? null,
484
+ serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
485
+ hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
486
+ }
487
+ );
488
+ }
489
+ if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
490
+ delete mergedResponseCtx.__isDeputy;
491
+ }
492
+ resolve(mergedResponseCtx);
493
+ }
494
+ },
495
+ `Ephemeral resolver for deputy process ${processId}`,
496
+ { register: false }
497
+ ).doOn(
498
+ `meta.socket_client.delegated:${processId}`,
499
+ `meta.fetch.delegated:${processId}`,
500
+ `meta.service_registry.load_balance_failed:${processId}`
501
+ );
502
+ });
503
+ }
324
504
  var DeputyTask = class extends import_core.Task {
325
505
  /**
326
506
  * Constructs a new instance of the class with the specified parameters.
@@ -348,87 +528,9 @@ var DeputyTask = class extends import_core.Task {
348
528
  * @return {void} This constructor does not return a value.
349
529
  */
350
530
  constructor(name, remoteRoutineName, serviceName = void 0, description = "", concurrency = 0, timeout = 0, register = true, isUnique = false, isMeta = false, isSubMeta = false, isHidden = false, getTagCallback = void 0, inputSchema = void 0, validateInputContext = false, outputSchema = void 0, validateOutputContext = false, retryCount = 0, retryDelay = 0, retryDelayMax = 0, retryDelayFactor = 1) {
351
- const taskFunction = (context, emit2, inquire, progressCallback) => {
352
- return new Promise((resolve, reject) => {
353
- if (context.__metadata.__blockRemoteExecution) {
354
- reject(new Error("Blocked remote execution"));
355
- return;
356
- }
357
- if (context.__metadata.__skipRemoteExecution) {
358
- resolve(context);
359
- return;
360
- }
361
- const processId = (0, import_uuid2.v4)();
362
- context.__metadata.__deputyExecId = processId;
363
- if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
364
- console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
365
- localServiceName: CadenzaService.serviceRegistry.serviceName,
366
- localTaskName: context.__localTaskName ?? null,
367
- remoteRoutineName: context.__remoteRoutineName ?? null,
368
- targetServiceName: context.__serviceName ?? null,
369
- deputyExecId: processId,
370
- dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
371
- queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
372
- queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
373
- });
374
- }
375
- emit2("meta.deputy.delegation_requested", {
376
- ...context
377
- });
378
- CadenzaService.createEphemeralMetaTask(
379
- `On progress deputy ${this.remoteRoutineName}`,
380
- (ctx) => {
381
- if (ctx.progress) progressCallback(ctx.progress * ctx.weight);
382
- },
383
- `Ephemeral task for deputy process ${processId}`,
384
- {
385
- once: false,
386
- destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
387
- register: false
388
- }
389
- ).doOn(
390
- `meta.socket_client.delegation_progress:${processId}`,
391
- `meta.socket_client.delegated:${processId}`,
392
- `meta.fetch.delegated:${processId}`,
393
- `meta.service_registry.load_balance_failed:${processId}`
394
- );
395
- CadenzaService.createEphemeralMetaTask(
396
- `Resolve deputy ${this.remoteRoutineName}`,
397
- (responseCtx) => {
398
- const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
399
- ...context,
400
- ...responseCtx
401
- } : responseCtx;
402
- if (responseCtx?.errored) {
403
- reject(new Error(responseCtx.__error));
404
- } else {
405
- if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
406
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved", {
407
- localServiceName: CadenzaService.serviceRegistry.serviceName,
408
- targetServiceName: context.__serviceName ?? null,
409
- resolverRequestId: context.__resolverRequestId ?? null,
410
- serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
411
- hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
412
- });
413
- }
414
- if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
415
- delete mergedResponseCtx.__isDeputy;
416
- }
417
- resolve(mergedResponseCtx);
418
- }
419
- },
420
- `Ephemeral resolver for deputy process ${processId}`,
421
- { register: false }
422
- ).doOn(
423
- `meta.socket_client.delegated:${processId}`,
424
- `meta.fetch.delegated:${processId}`,
425
- `meta.service_registry.load_balance_failed:${processId}`
426
- );
427
- });
428
- };
429
531
  super(
430
532
  name,
431
- taskFunction,
533
+ deputyTaskExecutor,
432
534
  description,
433
535
  concurrency,
434
536
  timeout,
@@ -460,6 +562,11 @@ var DeputyTask = class extends import_core.Task {
460
562
  communicationType: "delegation"
461
563
  });
462
564
  }
565
+ clone() {
566
+ throw new Error(
567
+ `DeputyTask '${this.name}' does not support clone(). Create a new named deputy task or use a flow-specific meta task that performs an inquiry instead.`
568
+ );
569
+ }
463
570
  /**
464
571
  * Executes the specified task function within the provided execution context.
465
572
  *
@@ -503,7 +610,25 @@ var DeputyTask = class extends import_core.Task {
503
610
  })
504
611
  )
505
612
  );
506
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
613
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
614
+ this,
615
+ deputyContext,
616
+ emit2,
617
+ inquire,
618
+ progressCallback
619
+ ) : {
620
+ helpers: {},
621
+ globals: {}
622
+ };
623
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
624
+ };
625
+ return this.taskFunction(
626
+ deputyContext,
627
+ emit2,
628
+ inquire,
629
+ resolvedTools,
630
+ resolvedProgressCallback
631
+ );
507
632
  }
508
633
  };
509
634
 
@@ -572,6 +697,11 @@ var DatabaseTask = class extends DeputyTask {
572
697
  );
573
698
  this.queryData = queryData;
574
699
  }
700
+ clone() {
701
+ throw new Error(
702
+ `DatabaseTask '${this.name}' does not support clone(). Create a new named database task or use a flow-specific meta task that performs the default database inquiry instead.`
703
+ );
704
+ }
575
705
  /**
576
706
  * Executes the specified task within the given context.
577
707
  *
@@ -697,7 +827,25 @@ var DatabaseTask = class extends DeputyTask {
697
827
  sourceTaskName: rawContext.__localTaskName ?? rawContext.__metadata?.__localTaskName ?? null
698
828
  });
699
829
  }
700
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
830
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
831
+ this,
832
+ deputyContext,
833
+ emit2,
834
+ inquire,
835
+ progressCallback
836
+ ) : {
837
+ helpers: {},
838
+ globals: {}
839
+ };
840
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
841
+ };
842
+ return this.taskFunction(
843
+ deputyContext,
844
+ emit2,
845
+ inquire,
846
+ resolvedTools,
847
+ resolvedProgressCallback
848
+ );
701
849
  }
702
850
  };
703
851
 
@@ -987,6 +1135,10 @@ function normalizeServiceInstanceDescriptor(value) {
987
1135
  return null;
988
1136
  }
989
1137
  const transports = normalizeTransportArray(raw.transports, uuid9);
1138
+ const leaseStatusRaw = normalizeString2(raw.leaseStatus ?? raw.lease_status);
1139
+ const leaseStatus = leaseStatusRaw === "active" || leaseStatusRaw === "non_responsive" || leaseStatusRaw === "inactive" || leaseStatusRaw === "deleted" ? leaseStatusRaw : void 0;
1140
+ const isActive = leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isActive ?? raw.is_active ?? true);
1141
+ const isNonResponsive = leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isNonResponsive ?? raw.is_non_responsive ?? false);
990
1142
  return {
991
1143
  uuid: uuid9,
992
1144
  serviceName,
@@ -997,10 +1149,16 @@ function normalizeServiceInstanceDescriptor(value) {
997
1149
  )
998
1150
  ),
999
1151
  isPrimary: Boolean(raw.isPrimary ?? raw.is_primary ?? false),
1000
- isActive: Boolean(raw.isActive ?? raw.is_active ?? true),
1001
- isNonResponsive: Boolean(
1002
- raw.isNonResponsive ?? raw.is_non_responsive ?? false
1003
- ),
1152
+ leaseStatus,
1153
+ leaseExpiresAt: typeof raw.leaseExpiresAt === "string" ? raw.leaseExpiresAt : typeof raw.lease_expires_at === "string" ? raw.lease_expires_at : void 0,
1154
+ lastLeaseRenewedAt: typeof raw.lastLeaseRenewedAt === "string" ? raw.lastLeaseRenewedAt : typeof raw.last_lease_renewed_at === "string" ? raw.last_lease_renewed_at : void 0,
1155
+ isReady: typeof raw.isReady === "boolean" ? raw.isReady : typeof raw.is_ready === "boolean" ? raw.is_ready : void 0,
1156
+ readinessReason: typeof raw.readinessReason === "string" ? raw.readinessReason : typeof raw.readiness_reason === "string" ? raw.readiness_reason : null,
1157
+ lastReadyAt: typeof raw.lastReadyAt === "string" ? raw.lastReadyAt : typeof raw.last_ready_at === "string" ? raw.last_ready_at : null,
1158
+ lastObservedTransportAt: typeof raw.lastObservedTransportAt === "string" ? raw.lastObservedTransportAt : typeof raw.last_observed_transport_at === "string" ? raw.last_observed_transport_at : null,
1159
+ shutdownRequestedAt: typeof raw.shutdownRequestedAt === "string" ? raw.shutdownRequestedAt : typeof raw.shutdown_requested_at === "string" ? raw.shutdown_requested_at : null,
1160
+ isActive,
1161
+ isNonResponsive,
1004
1162
  isBlocked: Boolean(raw.isBlocked ?? raw.is_blocked ?? false),
1005
1163
  runtimeState: raw.runtimeState === "healthy" || raw.runtimeState === "degraded" || raw.runtimeState === "overloaded" || raw.runtimeState === "unavailable" ? raw.runtimeState : void 0,
1006
1164
  acceptingWork: typeof raw.acceptingWork === "boolean" ? raw.acceptingWork : void 0,
@@ -1453,6 +1611,61 @@ function resolveHealthMetric(input, keys) {
1453
1611
  }
1454
1612
  return void 0;
1455
1613
  }
1614
+ function sanitizeRuntimeMetricsHealthDetail(value) {
1615
+ if (!value || typeof value !== "object") {
1616
+ return void 0;
1617
+ }
1618
+ const input = value;
1619
+ const sampledAt = typeof input.sampledAt === "string" && input.sampledAt.trim().length > 0 ? input.sampledAt : void 0;
1620
+ const cpuUsage = normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
1621
+ const memoryUsage = normalizeOptionalMetric(
1622
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
1623
+ );
1624
+ const eventLoopLag = normalizeOptionalMetric(
1625
+ input.eventLoopLag ?? input.eventLoopLagMs
1626
+ );
1627
+ const rssBytes = normalizeOptionalMetric(input.rssBytes);
1628
+ const heapUsedBytes = normalizeOptionalMetric(input.heapUsedBytes);
1629
+ const heapTotalBytes = normalizeOptionalMetric(input.heapTotalBytes);
1630
+ const memoryLimitBytes = normalizeOptionalMetric(input.memoryLimitBytes);
1631
+ if (sampledAt === void 0 && cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && rssBytes === void 0 && heapUsedBytes === void 0 && heapTotalBytes === void 0 && memoryLimitBytes === void 0) {
1632
+ return void 0;
1633
+ }
1634
+ return {
1635
+ ...sampledAt !== void 0 ? { sampledAt } : {},
1636
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
1637
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
1638
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
1639
+ ...rssBytes !== void 0 ? { rssBytes } : {},
1640
+ ...heapUsedBytes !== void 0 ? { heapUsedBytes } : {},
1641
+ ...heapTotalBytes !== void 0 ? { heapTotalBytes } : {},
1642
+ ...memoryLimitBytes !== void 0 ? { memoryLimitBytes } : {}
1643
+ };
1644
+ }
1645
+ function sanitizeAuthorityRuntimeStatusHealth(health, options) {
1646
+ const input = health && typeof health === "object" ? health : {};
1647
+ const cpuUsage = options?.cpuUsage !== void 0 ? options.cpuUsage : normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
1648
+ const memoryUsage = options?.memoryUsage !== void 0 ? options.memoryUsage : normalizeOptionalMetric(
1649
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
1650
+ );
1651
+ const eventLoopLag = options?.eventLoopLag !== void 0 ? options.eventLoopLag : normalizeOptionalMetric(input.eventLoopLag ?? input.eventLoopLagMs);
1652
+ const runtimeMetrics = sanitizeRuntimeMetricsHealthDetail(input.runtimeMetrics);
1653
+ const runtimeStatus = options?.state || options?.reportedAt || typeof options?.acceptingWork === "boolean" ? {
1654
+ ...options?.state ? { state: options.state } : {},
1655
+ ...typeof options?.acceptingWork === "boolean" ? { acceptingWork: options.acceptingWork } : {},
1656
+ ...options?.reportedAt ? { reportedAt: options.reportedAt } : {}
1657
+ } : void 0;
1658
+ if (cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && !runtimeMetrics && !runtimeStatus) {
1659
+ return void 0;
1660
+ }
1661
+ return {
1662
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
1663
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
1664
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
1665
+ ...runtimeMetrics ? { runtimeMetrics } : {},
1666
+ ...runtimeStatus ? { runtimeStatus } : {}
1667
+ };
1668
+ }
1456
1669
  function normalizeAuthorityRuntimeStatusReport(input) {
1457
1670
  if (!input || typeof input !== "object") {
1458
1671
  return null;
@@ -1481,6 +1694,17 @@ function normalizeAuthorityRuntimeStatusReport(input) {
1481
1694
  (protocol) => protocol === "rest" || protocol === "socket"
1482
1695
  ) : [];
1483
1696
  const transportProtocols = transportProtocolList.length > 0 ? Array.from(new Set(transportProtocolList)) : void 0;
1697
+ const acceptingWork = Boolean(input.acceptingWork ?? input.accepting_work);
1698
+ const cpuUsage = resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]);
1699
+ const memoryUsage = resolveHealthMetric(input, [
1700
+ "memoryUsage",
1701
+ "memory",
1702
+ "memoryPressure"
1703
+ ]);
1704
+ const eventLoopLag = resolveHealthMetric(input, [
1705
+ "eventLoopLag",
1706
+ "eventLoopLagMs"
1707
+ ]);
1484
1708
  return {
1485
1709
  serviceName,
1486
1710
  serviceInstanceId,
@@ -1491,7 +1715,7 @@ function normalizeAuthorityRuntimeStatusReport(input) {
1491
1715
  isFrontend: typeof input.isFrontend === "boolean" ? input.isFrontend : typeof input.is_frontend === "boolean" ? input.is_frontend : void 0,
1492
1716
  reportedAt,
1493
1717
  state,
1494
- acceptingWork: Boolean(input.acceptingWork ?? input.accepting_work),
1718
+ acceptingWork,
1495
1719
  numberOfRunningGraphs: Math.max(
1496
1720
  0,
1497
1721
  Math.trunc(
@@ -1500,22 +1724,22 @@ function normalizeAuthorityRuntimeStatusReport(input) {
1500
1724
  ) || 0
1501
1725
  )
1502
1726
  ),
1503
- cpuUsage: resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]),
1504
- memoryUsage: resolveHealthMetric(input, [
1505
- "memoryUsage",
1506
- "memory",
1507
- "memoryPressure"
1508
- ]),
1509
- eventLoopLag: resolveHealthMetric(input, [
1510
- "eventLoopLag",
1511
- "eventLoopLagMs"
1512
- ]),
1727
+ cpuUsage,
1728
+ memoryUsage,
1729
+ eventLoopLag,
1513
1730
  isActive: Boolean(input.isActive ?? input.is_active ?? true),
1514
1731
  isNonResponsive: Boolean(
1515
1732
  input.isNonResponsive ?? input.is_non_responsive ?? false
1516
1733
  ),
1517
1734
  isBlocked: Boolean(input.isBlocked ?? input.is_blocked ?? false),
1518
- health: input.health && typeof input.health === "object" ? input.health : void 0
1735
+ health: sanitizeAuthorityRuntimeStatusHealth(input.health, {
1736
+ state,
1737
+ acceptingWork,
1738
+ reportedAt,
1739
+ cpuUsage,
1740
+ memoryUsage,
1741
+ eventLoopLag
1742
+ })
1519
1743
  };
1520
1744
  }
1521
1745
  function buildAuthorityRuntimeStatusSignature(report) {
@@ -1528,18 +1752,53 @@ function buildAuthorityRuntimeStatusSignature(report) {
1528
1752
  transportProtocols: report.transportProtocols ?? [],
1529
1753
  state: report.state,
1530
1754
  acceptingWork: report.acceptingWork,
1531
- numberOfRunningGraphs: report.numberOfRunningGraphs,
1532
- cpuUsage: report.cpuUsage ?? null,
1533
- memoryUsage: report.memoryUsage ?? null,
1534
- eventLoopLag: report.eventLoopLag ?? null,
1535
1755
  isActive: report.isActive,
1536
1756
  isNonResponsive: report.isNonResponsive,
1537
1757
  isBlocked: report.isBlocked,
1538
- isFrontend: report.isFrontend ?? null,
1539
- health: report.health ?? {}
1758
+ isFrontend: report.isFrontend ?? null
1540
1759
  });
1541
1760
  }
1542
1761
 
1762
+ // src/registry/runtimeJitter.ts
1763
+ function normalizeKey(key) {
1764
+ return key.trim() || "default";
1765
+ }
1766
+ function hashKeyToUnitInterval(key) {
1767
+ const normalizedKey = normalizeKey(key);
1768
+ let hash = 2166136261;
1769
+ for (let index = 0; index < normalizedKey.length; index += 1) {
1770
+ hash ^= normalizedKey.charCodeAt(index);
1771
+ hash = Math.imul(hash, 16777619);
1772
+ }
1773
+ return (hash >>> 0) / 4294967295;
1774
+ }
1775
+ function normalizeJitterRatio(value) {
1776
+ if (!Number.isFinite(value) || value <= 0) {
1777
+ return 0;
1778
+ }
1779
+ return Math.min(value, 1);
1780
+ }
1781
+ function buildDeterministicJitterOffsetMs(baseMs, ratio, key) {
1782
+ if (!Number.isFinite(baseMs) || baseMs <= 0) {
1783
+ return 0;
1784
+ }
1785
+ const normalizedRatio = normalizeJitterRatio(ratio);
1786
+ if (normalizedRatio <= 0) {
1787
+ return 0;
1788
+ }
1789
+ const maxOffsetMs = Math.round(baseMs * normalizedRatio);
1790
+ if (maxOffsetMs <= 0) {
1791
+ return 0;
1792
+ }
1793
+ return Math.round(hashKeyToUnitInterval(key) * maxOffsetMs);
1794
+ }
1795
+ function buildDeterministicJitteredDelayMs(baseMs, ratio, key) {
1796
+ return Math.max(
1797
+ 0,
1798
+ Math.round(baseMs) + buildDeterministicJitterOffsetMs(baseMs, ratio, key)
1799
+ );
1800
+ }
1801
+
1543
1802
  // src/registry/serviceManifestContract.ts
1544
1803
  var AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT = "meta-service-registry-authority-service-manifest-report";
1545
1804
  var AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL = "global.meta.cadenza_db.service_manifest_updated";
@@ -1571,11 +1830,17 @@ function normalizeServiceManifestSnapshot(input) {
1571
1830
  intents: normalizeArray(record.intents),
1572
1831
  actors: normalizeArray(record.actors),
1573
1832
  routines: normalizeArray(record.routines),
1833
+ helpers: normalizeArray(record.helpers),
1834
+ globals: normalizeArray(record.globals),
1574
1835
  directionalTaskMaps: normalizeArray(record.directionalTaskMaps),
1575
1836
  signalToTaskMaps: normalizeArray(record.signalToTaskMaps),
1576
1837
  intentToTaskMaps: normalizeArray(record.intentToTaskMaps),
1577
1838
  actorTaskMaps: normalizeArray(record.actorTaskMaps),
1578
- taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps)
1839
+ taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps),
1840
+ taskToHelperMaps: normalizeArray(record.taskToHelperMaps),
1841
+ helperToHelperMaps: normalizeArray(record.helperToHelperMaps),
1842
+ taskToGlobalMaps: normalizeArray(record.taskToGlobalMaps),
1843
+ helperToGlobalMaps: normalizeArray(record.helperToGlobalMaps)
1579
1844
  };
1580
1845
  }
1581
1846
  function selectLatestServiceManifestSnapshots(snapshots) {
@@ -1839,6 +2104,27 @@ function buildRoutineDefinition(routine, serviceName) {
1839
2104
  is_meta: routine.isMeta === true
1840
2105
  };
1841
2106
  }
2107
+ function buildHelperDefinition(helper, serviceName) {
2108
+ return {
2109
+ name: helper.name,
2110
+ version: helper.version,
2111
+ description: helper.description,
2112
+ service_name: serviceName,
2113
+ is_meta: helper.isMeta === true,
2114
+ handler_source: helper.helperFunction.toString(),
2115
+ language: "js"
2116
+ };
2117
+ }
2118
+ function buildGlobalDefinition(globalDefinition, serviceName) {
2119
+ return {
2120
+ name: globalDefinition.name,
2121
+ version: globalDefinition.version,
2122
+ description: globalDefinition.description,
2123
+ service_name: serviceName,
2124
+ is_meta: globalDefinition.isMeta === true,
2125
+ value: sanitizeManifestValue(globalDefinition.value)
2126
+ };
2127
+ }
1842
2128
  function shouldExportTask(task) {
1843
2129
  return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
1844
2130
  }
@@ -1854,6 +2140,12 @@ function buildActorKey(actor) {
1854
2140
  function buildRoutineKey(routine) {
1855
2141
  return `${routine.service_name}|${routine.name}|${routine.version}`;
1856
2142
  }
2143
+ function buildHelperKey(helper) {
2144
+ return `${helper.service_name}|${helper.name}|${helper.version}`;
2145
+ }
2146
+ function buildGlobalKey(globalDefinition) {
2147
+ return `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`;
2148
+ }
1857
2149
  function listManifestTasks() {
1858
2150
  const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
1859
2151
  (task) => Boolean(task)
@@ -1867,6 +2159,18 @@ function listManifestTasks() {
1867
2159
  ).values()
1868
2160
  );
1869
2161
  }
2162
+ function listManifestHelpers() {
2163
+ const toolRuntime = CadenzaService;
2164
+ return (toolRuntime.getAllHelpers?.() ?? []).filter(
2165
+ (helper) => Boolean(helper && !helper.destroyed)
2166
+ );
2167
+ }
2168
+ function listManifestGlobals() {
2169
+ const toolRuntime = CadenzaService;
2170
+ return (toolRuntime.getAllGlobals?.() ?? []).filter(
2171
+ (globalDefinition) => Boolean(globalDefinition && !globalDefinition.destroyed)
2172
+ );
2173
+ }
1870
2174
  function isRoutingCriticalMetaSignal(_signal) {
1871
2175
  return false;
1872
2176
  }
@@ -1882,6 +2186,8 @@ function buildServiceManifestSnapshot(params) {
1882
2186
  publicationLayer = "business_structural"
1883
2187
  } = params;
1884
2188
  const tasks = listManifestTasks().filter(shouldExportTask);
2189
+ const helpers = listManifestHelpers();
2190
+ const globals = listManifestGlobals();
1885
2191
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
1886
2192
  const actors = CadenzaService.getAllActors();
1887
2193
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -1893,6 +2199,10 @@ function buildServiceManifestSnapshot(params) {
1893
2199
  const directionalTaskMaps = /* @__PURE__ */ new Map();
1894
2200
  const actorTaskMaps = /* @__PURE__ */ new Map();
1895
2201
  const taskToRoutineMaps = /* @__PURE__ */ new Map();
2202
+ const helperTaskMaps = /* @__PURE__ */ new Map();
2203
+ const helperHelperMaps = /* @__PURE__ */ new Map();
2204
+ const taskGlobalMaps = /* @__PURE__ */ new Map();
2205
+ const helperGlobalMaps = /* @__PURE__ */ new Map();
1896
2206
  const registerSignal = (signalName) => {
1897
2207
  const normalizedSignalName = canonicalizeSignalName(signalName);
1898
2208
  if (!normalizedSignalName || signalDefinitions.has(normalizedSignalName)) {
@@ -1976,6 +2286,37 @@ function buildServiceManifestSnapshot(params) {
1976
2286
  is_meta: actorTaskMetadata.actorKind === "meta" || task.isMeta === true
1977
2287
  });
1978
2288
  }
2289
+ const taskTools = task;
2290
+ for (const [alias, helperName] of taskTools.helperAliases?.entries?.() ?? []) {
2291
+ const helper = CadenzaService.getHelper?.(helperName);
2292
+ if (!helper) {
2293
+ continue;
2294
+ }
2295
+ const key = `${task.name}|${task.version}|${alias}|${helper.name}|${helper.version}|${serviceName}`;
2296
+ helperTaskMaps.set(key, {
2297
+ task_name: task.name,
2298
+ task_version: task.version,
2299
+ service_name: serviceName,
2300
+ alias,
2301
+ helper_name: helper.name,
2302
+ helper_version: helper.version
2303
+ });
2304
+ }
2305
+ for (const [alias, globalName] of taskTools.globalAliases?.entries?.() ?? []) {
2306
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
2307
+ if (!globalDefinition) {
2308
+ continue;
2309
+ }
2310
+ const key = `${task.name}|${task.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
2311
+ taskGlobalMaps.set(key, {
2312
+ task_name: task.name,
2313
+ task_version: task.version,
2314
+ service_name: serviceName,
2315
+ alias,
2316
+ global_name: globalDefinition.name,
2317
+ global_version: globalDefinition.version
2318
+ });
2319
+ }
1979
2320
  }
1980
2321
  const intentDefinitions = Array.from(CadenzaService.inquiryBroker.intents.values()).map((intent) => {
1981
2322
  const intentRecord = intent;
@@ -2007,6 +2348,44 @@ function buildServiceManifestSnapshot(params) {
2007
2348
  ).sort(
2008
2349
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2009
2350
  );
2351
+ const helperDefinitions = helpers.map((helper) => buildHelperDefinition(helper, serviceName)).sort(
2352
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2353
+ );
2354
+ const globalDefinitions = globals.map((globalDefinition) => buildGlobalDefinition(globalDefinition, serviceName)).sort(
2355
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2356
+ );
2357
+ for (const helper of helpers) {
2358
+ for (const [alias, dependencyHelperName] of helper.helperAliases.entries()) {
2359
+ const dependencyHelper = CadenzaService.getHelper?.(dependencyHelperName);
2360
+ if (!dependencyHelper) {
2361
+ continue;
2362
+ }
2363
+ const key = `${helper.name}|${helper.version}|${alias}|${dependencyHelper.name}|${dependencyHelper.version}|${serviceName}`;
2364
+ helperHelperMaps.set(key, {
2365
+ helper_name: helper.name,
2366
+ helper_version: helper.version,
2367
+ service_name: serviceName,
2368
+ alias,
2369
+ dependency_helper_name: dependencyHelper.name,
2370
+ dependency_helper_version: dependencyHelper.version
2371
+ });
2372
+ }
2373
+ for (const [alias, globalName] of helper.globalAliases.entries()) {
2374
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
2375
+ if (!globalDefinition) {
2376
+ continue;
2377
+ }
2378
+ const key = `${helper.name}|${helper.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
2379
+ helperGlobalMaps.set(key, {
2380
+ helper_name: helper.name,
2381
+ helper_version: helper.version,
2382
+ service_name: serviceName,
2383
+ alias,
2384
+ global_name: globalDefinition.name,
2385
+ global_version: globalDefinition.version
2386
+ });
2387
+ }
2388
+ }
2010
2389
  for (const routine of routines) {
2011
2390
  for (const task of routine.tasks) {
2012
2391
  if (!task) {
@@ -2044,6 +2423,15 @@ function buildServiceManifestSnapshot(params) {
2044
2423
  const routineDefinitionsByKey = new Map(
2045
2424
  routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
2046
2425
  );
2426
+ const helperDefinitionsByKey = new Map(
2427
+ helperDefinitions.map((helper) => [buildHelperKey(helper), helper])
2428
+ );
2429
+ const globalDefinitionsByKey = new Map(
2430
+ globalDefinitions.map((globalDefinition) => [
2431
+ buildGlobalKey(globalDefinition),
2432
+ globalDefinition
2433
+ ])
2434
+ );
2047
2435
  const routingTaskKeys = /* @__PURE__ */ new Set();
2048
2436
  const routingSignalNames = /* @__PURE__ */ new Set();
2049
2437
  const routingIntentNames = /* @__PURE__ */ new Set();
@@ -2361,6 +2749,112 @@ function buildServiceManifestSnapshot(params) {
2361
2749
  ).sort(
2362
2750
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2363
2751
  );
2752
+ const businessHelpers = helperDefinitions.filter((helper) => helper.is_meta !== true).sort(
2753
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2754
+ );
2755
+ const localMetaHelpers = helperDefinitions.filter((helper) => helper.is_meta === true).sort(
2756
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2757
+ );
2758
+ const businessGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta !== true).sort(
2759
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2760
+ );
2761
+ const localMetaGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta === true).sort(
2762
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
2763
+ );
2764
+ const businessTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => {
2765
+ const task = taskDefinitionsByKey.get(
2766
+ buildTaskKey({
2767
+ service_name: map.service_name,
2768
+ name: map.task_name,
2769
+ version: map.task_version
2770
+ })
2771
+ );
2772
+ const helper = helperDefinitionsByKey.get(
2773
+ buildHelperKey({
2774
+ service_name: map.service_name,
2775
+ name: map.helper_name,
2776
+ version: map.helper_version
2777
+ })
2778
+ );
2779
+ return task?.is_meta !== true && task?.is_sub_meta !== true && helper?.is_meta !== true;
2780
+ }).sort(
2781
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
2782
+ );
2783
+ const localMetaTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => !businessTaskToHelperMaps.includes(map)).sort(
2784
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
2785
+ );
2786
+ const businessHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => {
2787
+ const helper = helperDefinitionsByKey.get(
2788
+ buildHelperKey({
2789
+ service_name: map.service_name,
2790
+ name: map.helper_name,
2791
+ version: map.helper_version
2792
+ })
2793
+ );
2794
+ const dependencyHelper = helperDefinitionsByKey.get(
2795
+ buildHelperKey({
2796
+ service_name: map.service_name,
2797
+ name: map.dependency_helper_name,
2798
+ version: map.dependency_helper_version
2799
+ })
2800
+ );
2801
+ return helper?.is_meta !== true && dependencyHelper?.is_meta !== true;
2802
+ }).sort(
2803
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
2804
+ );
2805
+ const localMetaHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => !businessHelperToHelperMaps.includes(map)).sort(
2806
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
2807
+ );
2808
+ const businessTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => {
2809
+ const task = taskDefinitionsByKey.get(
2810
+ buildTaskKey({
2811
+ service_name: map.service_name,
2812
+ name: map.task_name,
2813
+ version: map.task_version
2814
+ })
2815
+ );
2816
+ const globalDefinition = globalDefinitionsByKey.get(
2817
+ buildGlobalKey({
2818
+ service_name: map.service_name,
2819
+ name: map.global_name,
2820
+ version: map.global_version
2821
+ })
2822
+ );
2823
+ return task?.is_meta !== true && task?.is_sub_meta !== true && globalDefinition?.is_meta !== true;
2824
+ }).sort(
2825
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
2826
+ );
2827
+ const localMetaTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => !businessTaskToGlobalMaps.includes(map)).sort(
2828
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
2829
+ );
2830
+ const businessHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => {
2831
+ const helper = helperDefinitionsByKey.get(
2832
+ buildHelperKey({
2833
+ service_name: map.service_name,
2834
+ name: map.helper_name,
2835
+ version: map.helper_version
2836
+ })
2837
+ );
2838
+ const globalDefinition = globalDefinitionsByKey.get(
2839
+ buildGlobalKey({
2840
+ service_name: map.service_name,
2841
+ name: map.global_name,
2842
+ version: map.global_version
2843
+ })
2844
+ );
2845
+ return helper?.is_meta !== true && globalDefinition?.is_meta !== true;
2846
+ }).sort(
2847
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
2848
+ );
2849
+ const localMetaHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => !businessHelperToGlobalMaps.includes(map)).sort(
2850
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
2851
+ );
2852
+ const cumulativeHelpers = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelpers : [...businessHelpers, ...localMetaHelpers];
2853
+ const cumulativeGlobals = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessGlobals : [...businessGlobals, ...localMetaGlobals];
2854
+ const cumulativeTaskToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToHelperMaps : [...businessTaskToHelperMaps, ...localMetaTaskToHelperMaps];
2855
+ const cumulativeHelperToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToHelperMaps : [...businessHelperToHelperMaps, ...localMetaHelperToHelperMaps];
2856
+ const cumulativeTaskToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToGlobalMaps : [...businessTaskToGlobalMaps, ...localMetaTaskToGlobalMaps];
2857
+ const cumulativeHelperToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToGlobalMaps : [...businessHelperToGlobalMaps, ...localMetaHelperToGlobalMaps];
2364
2858
  const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
2365
2859
  new Map(
2366
2860
  [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
@@ -2403,11 +2897,17 @@ function buildServiceManifestSnapshot(params) {
2403
2897
  intents: cumulativeIntents,
2404
2898
  actors: cumulativeActors,
2405
2899
  routines: cumulativeRoutines,
2900
+ helpers: cumulativeHelpers,
2901
+ globals: cumulativeGlobals,
2406
2902
  directionalTaskMaps: cumulativeDirectionalTaskMaps,
2407
2903
  signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
2408
2904
  intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
2409
2905
  actorTaskMaps: cumulativeActorTaskMaps,
2410
- taskToRoutineMaps: cumulativeTaskToRoutineMaps
2906
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps,
2907
+ taskToHelperMaps: cumulativeTaskToHelperMaps,
2908
+ helperToHelperMaps: cumulativeHelperToHelperMaps,
2909
+ taskToGlobalMaps: cumulativeTaskToGlobalMaps,
2910
+ helperToGlobalMaps: cumulativeHelperToGlobalMaps
2411
2911
  };
2412
2912
  return {
2413
2913
  ...manifestBody,
@@ -2451,6 +2951,20 @@ function explodeServiceManifestSnapshots(snapshots) {
2451
2951
  `${right.service_name}|${right.name}|${right.version}`
2452
2952
  )
2453
2953
  );
2954
+ const helpers = dedupe(
2955
+ snapshots.flatMap((snapshot) => snapshot.helpers),
2956
+ (helper) => `${helper.service_name}|${helper.name}|${helper.version}`,
2957
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
2958
+ `${right.service_name}|${right.name}|${right.version}`
2959
+ )
2960
+ );
2961
+ const globals = dedupe(
2962
+ snapshots.flatMap((snapshot) => snapshot.globals),
2963
+ (globalDefinition) => `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`,
2964
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
2965
+ `${right.service_name}|${right.name}|${right.version}`
2966
+ )
2967
+ );
2454
2968
  const directionalTaskMaps = dedupe(
2455
2969
  snapshots.flatMap((snapshot) => snapshot.directionalTaskMaps),
2456
2970
  (map) => `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
@@ -2486,17 +3000,51 @@ function explodeServiceManifestSnapshots(snapshots) {
2486
3000
  `${right.routine_name}|${right.routine_version}|${right.service_name}|${right.task_name}|${right.task_version}`
2487
3001
  )
2488
3002
  );
3003
+ const taskToHelperMaps = dedupe(
3004
+ snapshots.flatMap((snapshot) => snapshot.taskToHelperMaps),
3005
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.helper_name}|${map.helper_version}`,
3006
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.helper_name}`.localeCompare(
3007
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.helper_name}`
3008
+ )
3009
+ );
3010
+ const helperToHelperMaps = dedupe(
3011
+ snapshots.flatMap((snapshot) => snapshot.helperToHelperMaps),
3012
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.dependency_helper_name}|${map.dependency_helper_version}`,
3013
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.dependency_helper_name}`.localeCompare(
3014
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.dependency_helper_name}`
3015
+ )
3016
+ );
3017
+ const taskToGlobalMaps = dedupe(
3018
+ snapshots.flatMap((snapshot) => snapshot.taskToGlobalMaps),
3019
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.global_name}|${map.global_version}`,
3020
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.global_name}`.localeCompare(
3021
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.global_name}`
3022
+ )
3023
+ );
3024
+ const helperToGlobalMaps = dedupe(
3025
+ snapshots.flatMap((snapshot) => snapshot.helperToGlobalMaps),
3026
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.global_name}|${map.global_version}`,
3027
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.global_name}`.localeCompare(
3028
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.global_name}`
3029
+ )
3030
+ );
2489
3031
  return {
2490
3032
  tasks,
2491
3033
  signals,
2492
3034
  intents,
2493
3035
  actors,
2494
3036
  routines,
3037
+ helpers,
3038
+ globals,
2495
3039
  directionalTaskMaps,
2496
3040
  signalToTaskMaps,
2497
3041
  intentToTaskMaps,
2498
3042
  actorTaskMaps,
2499
- taskToRoutineMaps
3043
+ taskToRoutineMaps,
3044
+ taskToHelperMaps,
3045
+ helperToHelperMaps,
3046
+ taskToGlobalMaps,
3047
+ helperToGlobalMaps
2500
3048
  };
2501
3049
  }
2502
3050
 
@@ -2545,6 +3093,52 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
2545
3093
  function shouldTraceServiceRegistry(serviceName) {
2546
3094
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
2547
3095
  }
3096
+ function normalizeLeaseStatus(value) {
3097
+ const status = String(value ?? "").trim();
3098
+ if (status === "active" || status === "non_responsive" || status === "inactive" || status === "deleted") {
3099
+ return status;
3100
+ }
3101
+ return null;
3102
+ }
3103
+ function overlayServiceInstancesWithLeases(serviceInstances, serviceInstanceLeases) {
3104
+ if (serviceInstanceLeases.length === 0) {
3105
+ return serviceInstances;
3106
+ }
3107
+ const leasesByInstanceId = /* @__PURE__ */ new Map();
3108
+ for (const row of serviceInstanceLeases) {
3109
+ const serviceInstanceId = String(
3110
+ row.service_instance_id ?? row.serviceInstanceId ?? ""
3111
+ ).trim();
3112
+ if (!serviceInstanceId) {
3113
+ continue;
3114
+ }
3115
+ leasesByInstanceId.set(serviceInstanceId, row);
3116
+ }
3117
+ return serviceInstances.map((row) => {
3118
+ const serviceInstanceId = String(row.uuid ?? "").trim();
3119
+ const lease = serviceInstanceId ? leasesByInstanceId.get(serviceInstanceId) : void 0;
3120
+ if (!lease) {
3121
+ return row;
3122
+ }
3123
+ const leaseStatus = normalizeLeaseStatus(
3124
+ lease.status ?? lease.lease_status ?? lease.leaseStatus
3125
+ );
3126
+ return {
3127
+ ...row,
3128
+ lease_status: leaseStatus ?? void 0,
3129
+ is_ready: typeof lease.is_ready === "boolean" ? lease.is_ready : typeof lease.isReady === "boolean" ? lease.isReady : void 0,
3130
+ readiness_reason: typeof lease.readiness_reason === "string" ? lease.readiness_reason : typeof lease.readinessReason === "string" ? lease.readinessReason : null,
3131
+ lease_expires_at: typeof lease.lease_expires_at === "string" ? lease.lease_expires_at : typeof lease.leaseExpiresAt === "string" ? lease.leaseExpiresAt : null,
3132
+ last_lease_renewed_at: typeof lease.last_lease_renewed_at === "string" ? lease.last_lease_renewed_at : typeof lease.lastLeaseRenewedAt === "string" ? lease.lastLeaseRenewedAt : null,
3133
+ last_ready_at: typeof lease.last_ready_at === "string" ? lease.last_ready_at : typeof lease.lastReadyAt === "string" ? lease.lastReadyAt : null,
3134
+ last_observed_transport_at: typeof lease.last_observed_transport_at === "string" ? lease.last_observed_transport_at : typeof lease.lastObservedTransportAt === "string" ? lease.lastObservedTransportAt : null,
3135
+ shutdown_requested_at: typeof lease.shutdown_requested_at === "string" ? lease.shutdown_requested_at : typeof lease.shutdownRequestedAt === "string" ? lease.shutdownRequestedAt : null,
3136
+ is_active: leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_active,
3137
+ is_non_responsive: leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_non_responsive,
3138
+ deleted: leaseStatus === "deleted" ? true : Boolean(row.deleted ?? false)
3139
+ };
3140
+ });
3141
+ }
2548
3142
  function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
2549
3143
  const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
2550
3144
  const getJoinedValue = (key) => {
@@ -2622,6 +3216,43 @@ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
2622
3216
  }
2623
3217
  return sanitized;
2624
3218
  }
3219
+ var BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS = [
3220
+ "data",
3221
+ "batch",
3222
+ "transaction",
3223
+ "onConflict",
3224
+ "filter",
3225
+ "fields",
3226
+ "joins",
3227
+ "sort",
3228
+ "limit",
3229
+ "offset",
3230
+ "queryMode",
3231
+ "aggregates",
3232
+ "groupBy"
3233
+ ];
3234
+ function isBootstrapDbOperationRoutineName(value) {
3235
+ return /^(Insert|Update|Query|Delete)\s+/.test(String(value ?? "").trim());
3236
+ }
3237
+ function compactAuthorityBootstrapRequestBody(ctx) {
3238
+ if (!isBootstrapDbOperationRoutineName(ctx.__remoteRoutineName)) {
3239
+ return ctx;
3240
+ }
3241
+ const queryData = ctx.queryData && typeof ctx.queryData === "object" ? { ...ctx.queryData } : null;
3242
+ if (!queryData) {
3243
+ return ctx;
3244
+ }
3245
+ const compacted = {
3246
+ ...ctx,
3247
+ queryData
3248
+ };
3249
+ for (const key of BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS) {
3250
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
3251
+ delete compacted[key];
3252
+ }
3253
+ }
3254
+ return compacted;
3255
+ }
2625
3256
  function cloneServiceRegistryContextValue(value) {
2626
3257
  if (value instanceof Date) {
2627
3258
  return new Date(value.getTime());
@@ -2978,6 +3609,92 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
2978
3609
  `Resolve service registry insert for ${tableName}`,
2979
3610
  (ctx, emit2) => new Promise((resolve) => {
2980
3611
  const resolverRequestId = (0, import_uuid3.v4)();
3612
+ const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
3613
+ const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
3614
+ const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
3615
+ const selfBootstrapRetrySignal = CadenzaService.serviceRegistry.serviceName === "CadenzaDB" && resolvedTargetServiceName === "CadenzaDB" && !localInsertTask ? getSelfBootstrapRegistrationRetrySignal(tableName) : null;
3616
+ if (selfBootstrapRetrySignal) {
3617
+ CadenzaService.schedule(
3618
+ selfBootstrapRetrySignal,
3619
+ {
3620
+ ...ctx
3621
+ },
3622
+ 250
3623
+ );
3624
+ resolve(false);
3625
+ return;
3626
+ }
3627
+ if (bootstrapAuthorityInsertSpec) {
3628
+ const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
3629
+ const nextQueryData = buildServiceRegistryInsertQueryData(
3630
+ tableName,
3631
+ sanitizedContext,
3632
+ queryData
3633
+ );
3634
+ const inquiryContext = ensureDelegationContextMetadata({
3635
+ ...sanitizedContext,
3636
+ data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
3637
+ batch: nextQueryData.batch !== void 0 ? nextQueryData.batch : sanitizedContext.batch,
3638
+ onConflict: Object.prototype.hasOwnProperty.call(nextQueryData, "onConflict") ? nextQueryData.onConflict : void 0,
3639
+ transaction: nextQueryData.transaction !== void 0 ? nextQueryData.transaction : sanitizedContext.transaction,
3640
+ queryData: nextQueryData
3641
+ });
3642
+ inquiryContext.__metadata = {
3643
+ ...inquiryContext.__metadata ?? {},
3644
+ __skipRemoteExecution: inquiryContext.__metadata?.__skipRemoteExecution ?? inquiryContext.__skipRemoteExecution ?? false,
3645
+ __blockRemoteExecution: inquiryContext.__metadata?.__blockRemoteExecution ?? inquiryContext.__blockRemoteExecution ?? false
3646
+ };
3647
+ CadenzaService.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
3648
+ bootstrapAuthorityInsertSpec.intentName,
3649
+ inquiryContext
3650
+ );
3651
+ void CadenzaService.inquire(
3652
+ bootstrapAuthorityInsertSpec.intentName,
3653
+ inquiryContext,
3654
+ {
3655
+ requireComplete: true,
3656
+ timeout: bootstrapAuthorityInsertSpec.defaultTimeoutMs
3657
+ }
3658
+ ).then(
3659
+ (result) => resolve(
3660
+ resolveBootstrapAuthorityInsertResult(
3661
+ tableName,
3662
+ sanitizedContext,
3663
+ nextQueryData,
3664
+ result,
3665
+ emit2
3666
+ )
3667
+ )
3668
+ ).catch(
3669
+ (error) => resolve(
3670
+ resolveBootstrapAuthorityInsertResult(
3671
+ tableName,
3672
+ sanitizedContext,
3673
+ nextQueryData,
3674
+ error,
3675
+ emit2
3676
+ )
3677
+ )
3678
+ );
3679
+ return;
3680
+ }
3681
+ const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
3682
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
3683
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
3684
+ tableName,
3685
+ executionSignal,
3686
+ hasLocalInsertTask: !!localInsertTask,
3687
+ serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
3688
+ serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
3689
+ hasData: !!ctx.data,
3690
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
3691
+ registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
3692
+ });
3693
+ }
3694
+ if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
3695
+ wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
3696
+ wiredLocalTaskNames.add(localInsertTask.name);
3697
+ }
2981
3698
  CadenzaService.createEphemeralMetaTask(
2982
3699
  `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
2983
3700
  (resultCtx) => {
@@ -3077,95 +3794,11 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
3077
3794
  },
3078
3795
  `Resolves signal-driven ${tableName} service-registry insert execution.`,
3079
3796
  {
3080
- register: false
3797
+ register: false,
3798
+ once: false,
3799
+ destroyCondition: (result) => result !== false
3081
3800
  }
3082
3801
  ).doOn(executionResolvedSignal, executionFailedSignal);
3083
- const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
3084
- const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
3085
- const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
3086
- const selfBootstrapRetrySignal = CadenzaService.serviceRegistry.serviceName === "CadenzaDB" && resolvedTargetServiceName === "CadenzaDB" && !localInsertTask ? getSelfBootstrapRegistrationRetrySignal(tableName) : null;
3087
- if (selfBootstrapRetrySignal) {
3088
- CadenzaService.schedule(
3089
- selfBootstrapRetrySignal,
3090
- {
3091
- ...ctx
3092
- },
3093
- 250
3094
- );
3095
- resolve(false);
3096
- return;
3097
- }
3098
- if (bootstrapAuthorityInsertSpec) {
3099
- const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
3100
- const nextQueryData = buildServiceRegistryInsertQueryData(
3101
- tableName,
3102
- sanitizedContext,
3103
- queryData
3104
- );
3105
- const inquiryContext = ensureDelegationContextMetadata({
3106
- ...sanitizedContext,
3107
- data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
3108
- batch: nextQueryData.batch !== void 0 ? nextQueryData.batch : sanitizedContext.batch,
3109
- onConflict: Object.prototype.hasOwnProperty.call(nextQueryData, "onConflict") ? nextQueryData.onConflict : void 0,
3110
- transaction: nextQueryData.transaction !== void 0 ? nextQueryData.transaction : sanitizedContext.transaction,
3111
- queryData: nextQueryData
3112
- });
3113
- inquiryContext.__metadata = {
3114
- ...inquiryContext.__metadata ?? {},
3115
- __skipRemoteExecution: inquiryContext.__metadata?.__skipRemoteExecution ?? inquiryContext.__skipRemoteExecution ?? false,
3116
- __blockRemoteExecution: inquiryContext.__metadata?.__blockRemoteExecution ?? inquiryContext.__blockRemoteExecution ?? false
3117
- };
3118
- CadenzaService.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
3119
- bootstrapAuthorityInsertSpec.intentName,
3120
- inquiryContext
3121
- );
3122
- void CadenzaService.inquire(
3123
- bootstrapAuthorityInsertSpec.intentName,
3124
- inquiryContext,
3125
- {
3126
- requireComplete: true,
3127
- timeout: bootstrapAuthorityInsertSpec.defaultTimeoutMs
3128
- }
3129
- ).then(
3130
- (result) => resolve(
3131
- resolveBootstrapAuthorityInsertResult(
3132
- tableName,
3133
- sanitizedContext,
3134
- nextQueryData,
3135
- result,
3136
- emit2
3137
- )
3138
- )
3139
- ).catch(
3140
- (error) => resolve(
3141
- resolveBootstrapAuthorityInsertResult(
3142
- tableName,
3143
- sanitizedContext,
3144
- nextQueryData,
3145
- error,
3146
- emit2
3147
- )
3148
- )
3149
- );
3150
- return;
3151
- }
3152
- const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
3153
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
3154
- console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
3155
- tableName,
3156
- executionSignal,
3157
- hasLocalInsertTask: !!localInsertTask,
3158
- serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
3159
- serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
3160
- hasData: !!ctx.data,
3161
- dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
3162
- registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
3163
- });
3164
- }
3165
- if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
3166
- wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
3167
- wiredLocalTaskNames.add(localInsertTask.name);
3168
- }
3169
3802
  emit2(executionSignal, {
3170
3803
  ...ctx,
3171
3804
  __resolverRequestId: resolverRequestId
@@ -3190,6 +3823,17 @@ function readPositiveIntegerEnv(name, fallback) {
3190
3823
  }
3191
3824
  return normalized;
3192
3825
  }
3826
+ function readNonNegativeFloatEnv(name, fallback) {
3827
+ if (typeof process === "undefined") {
3828
+ return fallback;
3829
+ }
3830
+ const raw = process.env?.[name];
3831
+ const parsed = Number(raw);
3832
+ if (!Number.isFinite(parsed) || parsed < 0) {
3833
+ return fallback;
3834
+ }
3835
+ return parsed;
3836
+ }
3193
3837
  var ServiceRegistry = class _ServiceRegistry {
3194
3838
  /**
3195
3839
  * Initializes a private constructor for managing service instances, remote signals,
@@ -3239,6 +3883,9 @@ var ServiceRegistry = class _ServiceRegistry {
3239
3883
  "CADENZA_RUNTIME_STATUS_REST_REFRESH_MS",
3240
3884
  this.runtimeMetricsSampleIntervalMs
3241
3885
  );
3886
+ this.runtimeStatusLoopJitterRatio = normalizeJitterRatio(
3887
+ readNonNegativeFloatEnv("CADENZA_RUNTIME_STATUS_JITTER_RATIO", 0.2)
3888
+ );
3242
3889
  this.runtimeStatusMissThreshold = readPositiveIntegerEnv(
3243
3890
  "CADENZA_RUNTIME_STATUS_MISSED_HEARTBEATS",
3244
3891
  3
@@ -3287,6 +3934,18 @@ var ServiceRegistry = class _ServiceRegistry {
3287
3934
  "CADENZA_RUNTIME_STATUS_OVERLOADED_GRAPH_THRESHOLD",
3288
3935
  20
3289
3936
  );
3937
+ this.bootstrapFullSyncRetryJitterRatio = normalizeJitterRatio(
3938
+ readNonNegativeFloatEnv(
3939
+ "CADENZA_BOOTSTRAP_FULL_SYNC_RETRY_JITTER_RATIO",
3940
+ 0.2
3941
+ )
3942
+ );
3943
+ this.serviceCommunicationRetryJitterRatio = normalizeJitterRatio(
3944
+ readNonNegativeFloatEnv(
3945
+ "CADENZA_SERVICE_COMMUNICATION_RETRY_JITTER_RATIO",
3946
+ 0.2
3947
+ )
3948
+ );
3290
3949
  this.serviceName = null;
3291
3950
  this.serviceInstanceId = null;
3292
3951
  this.numberOfRunningGraphs = 0;
@@ -4265,6 +4924,12 @@ var ServiceRegistry = class _ServiceRegistry {
4265
4924
  const tasks = this.readArrayPayload(inquiryResult, [
4266
4925
  "tasks"
4267
4926
  ]);
4927
+ const helpers = this.readArrayPayload(inquiryResult, [
4928
+ "helpers"
4929
+ ]);
4930
+ const globals = this.readArrayPayload(inquiryResult, [
4931
+ "globals"
4932
+ ]);
4268
4933
  const signals = this.readArrayPayload(inquiryResult, [
4269
4934
  "signals"
4270
4935
  ]);
@@ -4289,6 +4954,22 @@ var ServiceRegistry = class _ServiceRegistry {
4289
4954
  inquiryResult,
4290
4955
  ["taskToRoutineMaps", "task_to_routine_maps"]
4291
4956
  );
4957
+ const taskToHelperMaps = this.readArrayPayload(
4958
+ inquiryResult,
4959
+ ["taskToHelperMaps", "task_to_helper_maps"]
4960
+ );
4961
+ const helperToHelperMaps = this.readArrayPayload(
4962
+ inquiryResult,
4963
+ ["helperToHelperMaps", "helper_to_helper_maps"]
4964
+ );
4965
+ const taskToGlobalMaps = this.readArrayPayload(
4966
+ inquiryResult,
4967
+ ["taskToGlobalMaps", "task_to_global_maps"]
4968
+ );
4969
+ const helperToGlobalMaps = this.readArrayPayload(
4970
+ inquiryResult,
4971
+ ["helperToGlobalMaps", "helper_to_global_maps"]
4972
+ );
4292
4973
  const serviceInstances = this.normalizeServiceInstancesFromSync(
4293
4974
  inquiryResult
4294
4975
  );
@@ -4322,6 +5003,8 @@ var ServiceRegistry = class _ServiceRegistry {
4322
5003
  serviceInstanceTransports: serviceInstanceTransports.length,
4323
5004
  serviceManifests: serviceManifests.length,
4324
5005
  tasks: tasks.length,
5006
+ helpers: helpers.length,
5007
+ globals: globals.length,
4325
5008
  signals: signals.length,
4326
5009
  intents: intents.length,
4327
5010
  actors: actors.length,
@@ -4347,6 +5030,8 @@ var ServiceRegistry = class _ServiceRegistry {
4347
5030
  serviceInstanceTransports,
4348
5031
  serviceManifests,
4349
5032
  tasks,
5033
+ helpers,
5034
+ globals,
4350
5035
  signals,
4351
5036
  intents,
4352
5037
  actors,
@@ -4354,6 +5039,10 @@ var ServiceRegistry = class _ServiceRegistry {
4354
5039
  directionalTaskMaps,
4355
5040
  actorTaskMaps,
4356
5041
  taskToRoutineMaps,
5042
+ taskToHelperMaps,
5043
+ helperToHelperMaps,
5044
+ taskToGlobalMaps,
5045
+ helperToGlobalMaps,
4357
5046
  __inquiryMeta: inquiryResult.__inquiryMeta
4358
5047
  };
4359
5048
  },
@@ -4973,29 +5662,51 @@ var ServiceRegistry = class _ServiceRegistry {
4973
5662
  this.runtimeStatusHeartbeatStarted = true;
4974
5663
  if (!this.runtimeMetricsSamplingStarted) {
4975
5664
  this.runtimeMetricsSamplingStarted = true;
5665
+ CadenzaService.emit(META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL, {});
4976
5666
  CadenzaService.interval(
4977
5667
  META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL,
4978
5668
  {},
4979
5669
  this.runtimeMetricsSampleIntervalMs,
4980
- true
5670
+ false,
5671
+ this.buildJitteredIntervalStartDate(
5672
+ this.runtimeMetricsSampleIntervalMs,
5673
+ "runtime-metrics-sample"
5674
+ )
4981
5675
  );
4982
5676
  }
5677
+ CadenzaService.emit(META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL, {
5678
+ reason: "heartbeat"
5679
+ });
4983
5680
  CadenzaService.interval(
4984
5681
  META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL,
4985
5682
  { reason: "heartbeat" },
4986
5683
  this.runtimeStatusHeartbeatIntervalMs,
4987
- true
5684
+ false,
5685
+ this.buildJitteredIntervalStartDate(
5686
+ this.runtimeStatusHeartbeatIntervalMs,
5687
+ "runtime-status-heartbeat"
5688
+ )
4988
5689
  );
4989
5690
  CadenzaService.interval(
4990
5691
  META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL,
4991
5692
  {},
4992
- this.runtimeStatusHeartbeatIntervalMs
5693
+ this.runtimeStatusHeartbeatIntervalMs,
5694
+ false,
5695
+ this.buildJitteredIntervalStartDate(
5696
+ this.runtimeStatusHeartbeatIntervalMs,
5697
+ "runtime-status-monitor"
5698
+ )
4993
5699
  );
5700
+ CadenzaService.emit(META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL, {});
4994
5701
  CadenzaService.interval(
4995
5702
  META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL,
4996
5703
  {},
4997
5704
  this.runtimeStatusRestRefreshIntervalMs,
4998
- true
5705
+ false,
5706
+ this.buildJitteredIntervalStartDate(
5707
+ this.runtimeStatusRestRefreshIntervalMs,
5708
+ "runtime-status-rest-refresh"
5709
+ )
4999
5710
  );
5000
5711
  return true;
5001
5712
  },
@@ -6000,11 +6711,14 @@ var ServiceRegistry = class _ServiceRegistry {
6000
6711
  }
6001
6712
  collectBootstrapFullSyncPayload(ctx) {
6002
6713
  const serviceInstances = [];
6714
+ const serviceInstanceLeases = [];
6003
6715
  const serviceInstanceTransports = [];
6004
6716
  const manifestSnapshots = [];
6005
6717
  const signalToTaskMaps = [];
6006
6718
  const intentToTaskMaps = [];
6007
6719
  const tasks = [];
6720
+ const helpers = [];
6721
+ const globals = [];
6008
6722
  const signals = [];
6009
6723
  const intents = [];
6010
6724
  const actors = [];
@@ -6012,11 +6726,18 @@ var ServiceRegistry = class _ServiceRegistry {
6012
6726
  const directionalTaskMaps = [];
6013
6727
  const actorTaskMaps = [];
6014
6728
  const taskToRoutineMaps = [];
6729
+ const taskToHelperMaps = [];
6730
+ const helperToHelperMaps = [];
6731
+ const taskToGlobalMaps = [];
6732
+ const helperToGlobalMaps = [];
6015
6733
  const seenServiceInstances = /* @__PURE__ */ new Set();
6734
+ const seenServiceInstanceLeases = /* @__PURE__ */ new Set();
6016
6735
  const seenServiceInstanceTransports = /* @__PURE__ */ new Set();
6017
6736
  const seenSignalMaps = /* @__PURE__ */ new Set();
6018
6737
  const seenIntentMaps = /* @__PURE__ */ new Set();
6019
6738
  const seenTasks = /* @__PURE__ */ new Set();
6739
+ const seenHelpers = /* @__PURE__ */ new Set();
6740
+ const seenGlobals = /* @__PURE__ */ new Set();
6020
6741
  const seenSignals = /* @__PURE__ */ new Set();
6021
6742
  const seenIntents = /* @__PURE__ */ new Set();
6022
6743
  const seenActors = /* @__PURE__ */ new Set();
@@ -6024,6 +6745,10 @@ var ServiceRegistry = class _ServiceRegistry {
6024
6745
  const seenDirectionalTaskMaps = /* @__PURE__ */ new Set();
6025
6746
  const seenActorTaskMaps = /* @__PURE__ */ new Set();
6026
6747
  const seenTaskToRoutineMaps = /* @__PURE__ */ new Set();
6748
+ const seenTaskToHelperMaps = /* @__PURE__ */ new Set();
6749
+ const seenHelperToHelperMaps = /* @__PURE__ */ new Set();
6750
+ const seenTaskToGlobalMaps = /* @__PURE__ */ new Set();
6751
+ const seenHelperToGlobalMaps = /* @__PURE__ */ new Set();
6027
6752
  const contexts = Array.isArray(ctx.joinedContexts) ? [ctx, ...ctx.joinedContexts] : [ctx];
6028
6753
  const pushUnique = (rows, target, seen, keyResolver) => {
6029
6754
  for (const row of rows) {
@@ -6054,6 +6779,12 @@ var ServiceRegistry = class _ServiceRegistry {
6054
6779
  "serviceInstance",
6055
6780
  "service_instance"
6056
6781
  ]);
6782
+ const serviceInstanceLeaseRows = readDirectArrayPayload(candidate, [
6783
+ "serviceInstanceLeases",
6784
+ "service_instance_leases",
6785
+ "serviceInstanceLease",
6786
+ "service_instance_lease"
6787
+ ]);
6057
6788
  const serviceInstanceTransportRows = readDirectArrayPayload(candidate, [
6058
6789
  "serviceInstanceTransports",
6059
6790
  "service_instance_transports",
@@ -6084,6 +6815,12 @@ var ServiceRegistry = class _ServiceRegistry {
6084
6815
  seenServiceInstances,
6085
6816
  (row) => String(row.uuid ?? "").trim()
6086
6817
  );
6818
+ pushUnique(
6819
+ serviceInstanceLeaseRows,
6820
+ serviceInstanceLeases,
6821
+ seenServiceInstanceLeases,
6822
+ (row) => String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
6823
+ );
6087
6824
  pushUnique(
6088
6825
  serviceInstanceTransportRows,
6089
6826
  serviceInstanceTransports,
@@ -6146,6 +6883,17 @@ var ServiceRegistry = class _ServiceRegistry {
6146
6883
  );
6147
6884
  continue;
6148
6885
  }
6886
+ if (row.status !== void 0 && (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0)) {
6887
+ pushUnique(
6888
+ [row],
6889
+ serviceInstanceLeases,
6890
+ seenServiceInstanceLeases,
6891
+ (entry) => String(
6892
+ entry.service_instance_id ?? entry.serviceInstanceId ?? ""
6893
+ ).trim()
6894
+ );
6895
+ continue;
6896
+ }
6149
6897
  if (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0) {
6150
6898
  pushUnique(
6151
6899
  [row],
@@ -6174,12 +6922,16 @@ var ServiceRegistry = class _ServiceRegistry {
6174
6922
  }
6175
6923
  }
6176
6924
  }
6925
+ const mergedServiceInstances = overlayServiceInstancesWithLeases(
6926
+ serviceInstances,
6927
+ serviceInstanceLeases
6928
+ );
6177
6929
  const activeServiceInstanceIds = new Set(
6178
- serviceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid9) => uuid9.length > 0)
6930
+ mergedServiceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid9) => uuid9.length > 0)
6179
6931
  );
6180
- const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? serviceInstances.filter(
6932
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? mergedServiceInstances.filter(
6181
6933
  (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
6182
- ) : serviceInstances;
6934
+ ) : mergedServiceInstances;
6183
6935
  const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
6184
6936
  (row) => activeServiceInstanceIds.has(
6185
6937
  String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
@@ -6223,6 +6975,22 @@ var ServiceRegistry = class _ServiceRegistry {
6223
6975
  row.version ?? 1
6224
6976
  ).trim()}`
6225
6977
  );
6978
+ pushUnique(
6979
+ explodedManifest.helpers,
6980
+ helpers,
6981
+ seenHelpers,
6982
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
6983
+ row.version ?? 1
6984
+ ).trim()}`
6985
+ );
6986
+ pushUnique(
6987
+ explodedManifest.globals,
6988
+ globals,
6989
+ seenGlobals,
6990
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
6991
+ row.version ?? 1
6992
+ ).trim()}`
6993
+ );
6226
6994
  pushUnique(
6227
6995
  explodedManifest.signals,
6228
6996
  signals,
@@ -6283,6 +7051,50 @@ var ServiceRegistry = class _ServiceRegistry {
6283
7051
  row.task_version ?? 1
6284
7052
  ).trim()}`
6285
7053
  );
7054
+ pushUnique(
7055
+ explodedManifest.taskToHelperMaps,
7056
+ taskToHelperMaps,
7057
+ seenTaskToHelperMaps,
7058
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
7059
+ row.task_version ?? 1
7060
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
7061
+ row.helper_name ?? ""
7062
+ ).trim()}|${String(row.helper_version ?? 1).trim()}`
7063
+ );
7064
+ pushUnique(
7065
+ explodedManifest.helperToHelperMaps,
7066
+ helperToHelperMaps,
7067
+ seenHelperToHelperMaps,
7068
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
7069
+ row.helper_name ?? ""
7070
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
7071
+ row.alias ?? ""
7072
+ ).trim()}|${String(row.dependency_helper_name ?? "").trim()}|${String(
7073
+ row.dependency_helper_version ?? 1
7074
+ ).trim()}`
7075
+ );
7076
+ pushUnique(
7077
+ explodedManifest.taskToGlobalMaps,
7078
+ taskToGlobalMaps,
7079
+ seenTaskToGlobalMaps,
7080
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
7081
+ row.task_version ?? 1
7082
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
7083
+ row.global_name ?? ""
7084
+ ).trim()}|${String(row.global_version ?? 1).trim()}`
7085
+ );
7086
+ pushUnique(
7087
+ explodedManifest.helperToGlobalMaps,
7088
+ helperToGlobalMaps,
7089
+ seenHelperToGlobalMaps,
7090
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
7091
+ row.helper_name ?? ""
7092
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
7093
+ row.alias ?? ""
7094
+ ).trim()}|${String(row.global_name ?? "").trim()}|${String(
7095
+ row.global_version ?? 1
7096
+ ).trim()}`
7097
+ );
6286
7098
  if (!hasExplicitSignalRoutingRows) {
6287
7099
  pushUnique(
6288
7100
  explodedManifest.signalToTaskMaps,
@@ -6309,9 +7121,12 @@ var ServiceRegistry = class _ServiceRegistry {
6309
7121
  }
6310
7122
  return {
6311
7123
  serviceInstances: filteredServiceInstances,
7124
+ serviceInstanceLeases,
6312
7125
  serviceInstanceTransports: filteredServiceInstanceTransports,
6313
7126
  serviceManifests,
6314
7127
  tasks,
7128
+ helpers,
7129
+ globals,
6315
7130
  signals,
6316
7131
  intents,
6317
7132
  actors,
@@ -6319,6 +7134,10 @@ var ServiceRegistry = class _ServiceRegistry {
6319
7134
  directionalTaskMaps,
6320
7135
  actorTaskMaps,
6321
7136
  taskToRoutineMaps,
7137
+ taskToHelperMaps,
7138
+ helperToHelperMaps,
7139
+ taskToGlobalMaps,
7140
+ helperToGlobalMaps,
6322
7141
  signalToTaskMaps: filteredSignalToTaskMaps,
6323
7142
  intentToTaskMaps: filteredIntentToTaskMaps
6324
7143
  };
@@ -6750,29 +7569,31 @@ var ServiceRegistry = class _ServiceRegistry {
6750
7569
  const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
6751
7570
  try {
6752
7571
  const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
6753
- const requestBody = stripDelegationRequestSnapshot(
6754
- ensureDelegationContextMetadata(
6755
- attachDelegationRequestSnapshot({
6756
- ...sanitizedContext,
6757
- __remoteRoutineName: remoteRoutineName,
6758
- __serviceName: "CadenzaDB",
6759
- __localServiceName: this.serviceName,
6760
- __timeout: timeoutMs,
6761
- __syncing: true,
6762
- __transportOrigin: target.origin,
6763
- __transportProtocol: "rest",
6764
- __transportProtocols: ["rest"],
6765
- __routeKey: target.routeKey,
6766
- routeKey: target.routeKey,
6767
- __fetchId: target.fetchId,
6768
- fetchId: target.fetchId,
6769
- __metadata: {
6770
- ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
7572
+ const requestBody = compactAuthorityBootstrapRequestBody(
7573
+ stripDelegationRequestSnapshot(
7574
+ ensureDelegationContextMetadata(
7575
+ attachDelegationRequestSnapshot({
7576
+ ...sanitizedContext,
7577
+ __remoteRoutineName: remoteRoutineName,
7578
+ __serviceName: "CadenzaDB",
7579
+ __localServiceName: this.serviceName,
6771
7580
  __timeout: timeoutMs,
6772
7581
  __syncing: true,
6773
- __authorityBootstrapChannel: true
6774
- }
6775
- })
7582
+ __transportOrigin: target.origin,
7583
+ __transportProtocol: "rest",
7584
+ __transportProtocols: ["rest"],
7585
+ __routeKey: target.routeKey,
7586
+ routeKey: target.routeKey,
7587
+ __fetchId: target.fetchId,
7588
+ fetchId: target.fetchId,
7589
+ __metadata: {
7590
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
7591
+ __timeout: timeoutMs,
7592
+ __syncing: true,
7593
+ __authorityBootstrapChannel: true
7594
+ }
7595
+ })
7596
+ )
6776
7597
  )
6777
7598
  );
6778
7599
  const response = await globalThis.fetch(`${target.origin}/delegation`, {
@@ -6927,12 +7748,14 @@ var ServiceRegistry = class _ServiceRegistry {
6927
7748
  };
6928
7749
  const [
6929
7750
  serviceInstances,
7751
+ serviceInstanceLeases,
6930
7752
  serviceInstanceTransports,
6931
7753
  serviceManifests,
6932
7754
  signalToTaskMaps,
6933
7755
  intentToTaskMaps
6934
7756
  ] = await Promise.all([
6935
7757
  DatabaseController.instance.queryAuthorityTableRows("service_instance"),
7758
+ queryOptionalAuthorityRoutingRows("service_instance_lease"),
6936
7759
  DatabaseController.instance.queryAuthorityTableRows(
6937
7760
  "service_instance_transport"
6938
7761
  ),
@@ -6945,6 +7768,7 @@ var ServiceRegistry = class _ServiceRegistry {
6945
7768
  __syncing: true,
6946
7769
  ...this.collectBootstrapFullSyncPayload({
6947
7770
  serviceInstances,
7771
+ serviceInstanceLeases,
6948
7772
  serviceInstanceTransports,
6949
7773
  serviceManifests,
6950
7774
  signalToTaskMaps,
@@ -6977,9 +7801,14 @@ var ServiceRegistry = class _ServiceRegistry {
6977
7801
  return false;
6978
7802
  }
6979
7803
  const scheduleRetry = (reason, error) => {
6980
- const delayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
7804
+ const baseDelayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
6981
7805
  const nextAttempt = descriptor.retryAttempt + 1;
6982
- if (delayMs !== void 0) {
7806
+ if (baseDelayMs !== void 0) {
7807
+ const delayMs = buildDeterministicJitteredDelayMs(
7808
+ baseDelayMs,
7809
+ this.serviceCommunicationRetryJitterRatio,
7810
+ `${descriptor.serviceInstanceId}:${descriptor.communicationType}:${descriptor.retryAttempt}`
7811
+ );
6983
7812
  CadenzaService.schedule(
6984
7813
  retrySignal,
6985
7814
  buildServiceCommunicationRetryContext({
@@ -7127,6 +7956,31 @@ var ServiceRegistry = class _ServiceRegistry {
7127
7956
  })
7128
7957
  );
7129
7958
  }
7959
+ buildDeterministicInstanceJitterKey(scope) {
7960
+ const serviceName = String(this.serviceName ?? "").trim() || "unknown-service";
7961
+ const serviceInstanceId = String(this.serviceInstanceId ?? "").trim() || "pending-instance";
7962
+ return `${serviceName}:${serviceInstanceId}:${scope}`;
7963
+ }
7964
+ buildJitteredIntervalStartDate(intervalMs, scope) {
7965
+ const jitterOffsetMs = buildDeterministicJitterOffsetMs(
7966
+ intervalMs,
7967
+ this.runtimeStatusLoopJitterRatio,
7968
+ this.buildDeterministicInstanceJitterKey(scope)
7969
+ );
7970
+ if (jitterOffsetMs <= 0) {
7971
+ return void 0;
7972
+ }
7973
+ return new Date(Date.now() + intervalMs + jitterOffsetMs);
7974
+ }
7975
+ buildJitteredBootstrapRetryDelayMs(baseDelayMs, attempt) {
7976
+ return buildDeterministicJitteredDelayMs(
7977
+ baseDelayMs,
7978
+ this.bootstrapFullSyncRetryJitterRatio,
7979
+ this.buildDeterministicInstanceJitterKey(
7980
+ `bootstrap-full-sync-retry-${attempt}`
7981
+ )
7982
+ );
7983
+ }
7130
7984
  ensureAuthorityBootstrapSignalTransmissions() {
7131
7985
  if (this.serviceName !== "CadenzaDB") {
7132
7986
  return false;
@@ -7204,8 +8058,11 @@ var ServiceRegistry = class _ServiceRegistry {
7204
8058
  }
7205
8059
  const retryGeneration = this.bootstrapFullSyncRetryGeneration;
7206
8060
  const retryReason = this.bootstrapFullSyncRetryReason ?? "service_registry_bootstrap_retry";
7207
- const delayMs = EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex];
7208
8061
  const attempt = this.bootstrapFullSyncRetryIndex + 1;
8062
+ const delayMs = this.buildJitteredBootstrapRetryDelayMs(
8063
+ EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex],
8064
+ attempt
8065
+ );
7209
8066
  this.bootstrapFullSyncRetryIndex += 1;
7210
8067
  this.bootstrapFullSyncRetryTimer = setTimeout(() => {
7211
8068
  this.bootstrapFullSyncRetryTimer = null;
@@ -9108,6 +9965,18 @@ var ServiceRegistry = class _ServiceRegistry {
9108
9965
  isNonResponsive,
9109
9966
  isBlocked
9110
9967
  );
9968
+ const cpuUsage = this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad");
9969
+ const memoryUsage = this.readRuntimeStatusMetric(
9970
+ ctx,
9971
+ "memoryUsage",
9972
+ "memory",
9973
+ "memoryPressure"
9974
+ );
9975
+ const eventLoopLag = this.readRuntimeStatusMetric(
9976
+ ctx,
9977
+ "eventLoopLag",
9978
+ "eventLoopLagMs"
9979
+ );
9111
9980
  return {
9112
9981
  serviceName,
9113
9982
  serviceInstanceId,
@@ -9120,22 +9989,20 @@ var ServiceRegistry = class _ServiceRegistry {
9120
9989
  state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
9121
9990
  acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
9122
9991
  numberOfRunningGraphs,
9123
- cpuUsage: this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad"),
9124
- memoryUsage: this.readRuntimeStatusMetric(
9125
- ctx,
9126
- "memoryUsage",
9127
- "memory",
9128
- "memoryPressure"
9129
- ),
9130
- eventLoopLag: this.readRuntimeStatusMetric(
9131
- ctx,
9132
- "eventLoopLag",
9133
- "eventLoopLagMs"
9134
- ),
9992
+ cpuUsage,
9993
+ memoryUsage,
9994
+ eventLoopLag,
9135
9995
  isActive,
9136
9996
  isNonResponsive,
9137
9997
  isBlocked,
9138
- health: ctx.health ?? ctx.__health ?? {}
9998
+ health: sanitizeAuthorityRuntimeStatusHealth(ctx.health ?? ctx.__health, {
9999
+ state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
10000
+ acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
10001
+ reportedAt: ctx.reportedAt ?? (typeof ctx.__reportedAt === "string" ? ctx.__reportedAt : void 0) ?? (/* @__PURE__ */ new Date()).toISOString(),
10002
+ cpuUsage,
10003
+ memoryUsage,
10004
+ eventLoopLag
10005
+ })
9139
10006
  };
9140
10007
  }
9141
10008
  applyRuntimeStatusReport(report) {
@@ -9176,12 +10043,14 @@ var ServiceRegistry = class _ServiceRegistry {
9176
10043
  instance.isFrontend = report.isFrontend;
9177
10044
  }
9178
10045
  instance.numberOfRunningGraphs = report.numberOfRunningGraphs;
9179
- const runtimeMetricsHealth = {
10046
+ const runtimeStatusHealth = sanitizeAuthorityRuntimeStatusHealth(report.health, {
10047
+ state: report.state,
10048
+ acceptingWork: report.acceptingWork,
10049
+ reportedAt: report.reportedAt,
9180
10050
  cpuUsage: report.cpuUsage ?? null,
9181
10051
  memoryUsage: report.memoryUsage ?? null,
9182
- eventLoopLag: report.eventLoopLag ?? null,
9183
- runtimeMetrics: report.health?.runtimeMetrics && typeof report.health.runtimeMetrics === "object" ? report.health.runtimeMetrics : void 0
9184
- };
10052
+ eventLoopLag: report.eventLoopLag ?? null
10053
+ });
9185
10054
  instance.isActive = report.isActive;
9186
10055
  instance.isNonResponsive = report.isNonResponsive;
9187
10056
  instance.isBlocked = report.isBlocked;
@@ -9190,13 +10059,7 @@ var ServiceRegistry = class _ServiceRegistry {
9190
10059
  instance.reportedAt = report.reportedAt;
9191
10060
  instance.health = {
9192
10061
  ...instance.health ?? {},
9193
- ...report.health ?? {},
9194
- ...runtimeMetricsHealth,
9195
- runtimeStatus: {
9196
- state: report.state,
9197
- acceptingWork: report.acceptingWork,
9198
- reportedAt: report.reportedAt
9199
- }
10062
+ ...runtimeStatusHealth ?? {}
9200
10063
  };
9201
10064
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
9202
10065
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -9368,15 +10231,20 @@ var ServiceRegistry = class _ServiceRegistry {
9368
10231
  isActive: snapshot.isActive,
9369
10232
  isNonResponsive: snapshot.isNonResponsive,
9370
10233
  isBlocked: snapshot.isBlocked,
9371
- health: {
9372
- ...localInstance.health ?? {},
9373
- ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {},
9374
- runtimeStatus: {
10234
+ health: sanitizeAuthorityRuntimeStatusHealth(
10235
+ {
10236
+ ...localInstance.health ?? {},
10237
+ ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {}
10238
+ },
10239
+ {
9375
10240
  state: snapshot.state,
9376
10241
  acceptingWork: snapshot.acceptingWork,
9377
- reportedAt
10242
+ reportedAt,
10243
+ cpuUsage: runtimeMetricsSnapshot?.cpuUsage ?? null,
10244
+ memoryUsage: runtimeMetricsSnapshot?.memoryUsage ?? null,
10245
+ eventLoopLag: runtimeMetricsSnapshot?.eventLoopLag ?? null
9378
10246
  }
9379
- }
10247
+ )
9380
10248
  };
9381
10249
  this.applyRuntimeStatusReport(report);
9382
10250
  return detailLevel === "full" ? report : this.stripRuntimeStatusReportForPeer(report);
@@ -9730,6 +10598,32 @@ var ServiceRegistry = class _ServiceRegistry {
9730
10598
  if (!instancePersisted) {
9731
10599
  return false;
9732
10600
  }
10601
+ await this.delegateAuthorityLifecycleUpdate(
10602
+ "Update service_instance_lease",
10603
+ {
10604
+ reason,
10605
+ graceful: true,
10606
+ data: {
10607
+ status: "inactive",
10608
+ is_ready: false,
10609
+ readiness_reason: "graceful_shutdown",
10610
+ lease_expires_at: reportedAt,
10611
+ last_lease_renewed_at: reportedAt,
10612
+ last_ready_at: null,
10613
+ last_observed_transport_at: reportedAt,
10614
+ shutdown_requested_at: reportedAt,
10615
+ deleted: false,
10616
+ modified: reportedAt
10617
+ },
10618
+ queryData: {
10619
+ filter: {
10620
+ service_instance_id: localInstance.uuid
10621
+ }
10622
+ },
10623
+ __serviceInstanceId: localInstance.uuid
10624
+ },
10625
+ Math.max(1e3, timeoutMs)
10626
+ );
9733
10627
  for (const transport of localInstance.transports) {
9734
10628
  if (!isPersistedUuid(transport.uuid)) {
9735
10629
  continue;
@@ -9881,6 +10775,7 @@ var ServiceRegistry = class _ServiceRegistry {
9881
10775
  };
9882
10776
  }
9883
10777
  reset() {
10778
+ this.clearBootstrapFullSyncRetryTimer();
9884
10779
  this.instances.clear();
9885
10780
  this.deputies.clear();
9886
10781
  this.remoteSignals.clear();
@@ -9904,6 +10799,23 @@ var ServiceRegistry = class _ServiceRegistry {
9904
10799
  this.lastRuntimeStatusSnapshot = null;
9905
10800
  this.isFrontend = false;
9906
10801
  this.localInstanceSeed = null;
10802
+ this.bootstrapFullSyncRetryIndex = 0;
10803
+ this.bootstrapFullSyncRetryGeneration = 0;
10804
+ this.bootstrapFullSyncSatisfied = false;
10805
+ this.bootstrapFullSyncRetryReason = null;
10806
+ this.knownGlobalSignalMaps.clear();
10807
+ this.authorityBootstrapRoute = {
10808
+ origin: null,
10809
+ role: "internal",
10810
+ routeKey: null,
10811
+ fetchId: null,
10812
+ serviceInstanceId: null,
10813
+ serviceTransportId: null,
10814
+ handshakeEstablished: false
10815
+ };
10816
+ this.authorityBootstrapHandshakeInFlight = false;
10817
+ this.authorityFullSyncResponderTask = null;
10818
+ this.authorityServiceCommunicationPersistenceTask = null;
9907
10819
  }
9908
10820
  };
9909
10821
 
@@ -10012,7 +10924,25 @@ var SignalTransmissionTask = class extends import_core3.Task {
10012
10924
  ...ctx
10013
10925
  })
10014
10926
  );
10015
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
10927
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
10928
+ this,
10929
+ deputyContext,
10930
+ emit2,
10931
+ inquire,
10932
+ progressCallback
10933
+ ) : {
10934
+ helpers: {},
10935
+ globals: {}
10936
+ };
10937
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
10938
+ };
10939
+ return this.taskFunction(
10940
+ deputyContext,
10941
+ emit2,
10942
+ inquire,
10943
+ resolvedTools,
10944
+ resolvedProgressCallback
10945
+ );
10016
10946
  }
10017
10947
  };
10018
10948
 
@@ -12583,7 +13513,7 @@ var SignalController = class _SignalController {
12583
13513
  }
12584
13514
  const traceContext = { ...ctx };
12585
13515
  delete traceContext.__traceCreatedBySignalBroker;
12586
- const sanitizedTraceContext = stripLocalRoutinePersistenceHints(traceContext);
13516
+ const sanitizedTraceContext = sanitizeExecutionPersistenceContext(traceContext);
12587
13517
  const routineMetadata = resolveRoutinePersistenceMetadata(traceContext);
12588
13518
  const { context: routineContext, metaContext: routineMetaContext } = splitRoutinePersistenceContext(traceContext);
12589
13519
  const traceCreatedBySignalBroker = ctx.__traceCreatedBySignalBroker === true || signalEmission.__traceCreatedBySignalBroker === true;
@@ -13265,6 +14195,16 @@ function buildActorRegistrationData(actor) {
13265
14195
  version: 1
13266
14196
  };
13267
14197
  }
14198
+ function sanitizePersistedTaskSourceFields(task, data) {
14199
+ if (!task.isMeta && !task.isDeputy) {
14200
+ return data;
14201
+ }
14202
+ return {
14203
+ ...data,
14204
+ function_string: "",
14205
+ tag_id_getter: null
14206
+ };
14207
+ }
13268
14208
  function resolveSyncServiceName(task) {
13269
14209
  const ownerServiceName = typeof task?.ownerServiceName === "string" ? task.ownerServiceName.trim() : "";
13270
14210
  const taskServiceName = typeof task?.serviceName === "string" ? task.serviceName.trim() : "";
@@ -14382,40 +15322,41 @@ var GraphSyncController = class _GraphSyncController {
14382
15322
  if (task.registered) continue;
14383
15323
  const { __functionString, __getTagCallback } = task.export();
14384
15324
  this.tasksSynced = false;
15325
+ const taskRegistrationData = sanitizePersistedTaskSourceFields(task, {
15326
+ name: task.name,
15327
+ version: task.version,
15328
+ description: task.description,
15329
+ function_string: __functionString,
15330
+ tag_id_getter: __getTagCallback,
15331
+ layer_index: task.layerIndex,
15332
+ concurrency: task.concurrency,
15333
+ timeout: task.timeout,
15334
+ is_unique: task.isUnique,
15335
+ is_signal: task.isSignal,
15336
+ is_throttled: task.isThrottled,
15337
+ is_debounce: task.isDebounce,
15338
+ is_ephemeral: task.isEphemeral,
15339
+ is_meta: task.isMeta,
15340
+ is_sub_meta: task.isSubMeta,
15341
+ is_hidden: task.isHidden,
15342
+ validate_input_context: task.validateInputContext,
15343
+ validate_output_context: task.validateOutputContext,
15344
+ retry_count: task.retryCount,
15345
+ retry_delay: task.retryDelay,
15346
+ retry_delay_max: task.retryDelayMax,
15347
+ retry_delay_factor: task.retryDelayFactor,
15348
+ service_name: serviceName2,
15349
+ signals: {
15350
+ emits: Array.from(task.emitsSignals),
15351
+ signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
15352
+ signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
15353
+ observed: Array.from(task.observedSignals)
15354
+ },
15355
+ intents: Array.from(task.handlesIntents)
15356
+ });
14385
15357
  yield {
14386
15358
  __syncing: ctx.__syncing,
14387
- data: {
14388
- name: task.name,
14389
- version: task.version,
14390
- description: task.description,
14391
- function_string: __functionString,
14392
- tag_id_getter: __getTagCallback,
14393
- layer_index: task.layerIndex,
14394
- concurrency: task.concurrency,
14395
- timeout: task.timeout,
14396
- is_unique: task.isUnique,
14397
- is_signal: task.isSignal,
14398
- is_throttled: task.isThrottled,
14399
- is_debounce: task.isDebounce,
14400
- is_ephemeral: task.isEphemeral,
14401
- is_meta: task.isMeta,
14402
- is_sub_meta: task.isSubMeta,
14403
- is_hidden: task.isHidden,
14404
- validate_input_context: task.validateInputContext,
14405
- validate_output_context: task.validateOutputContext,
14406
- retry_count: task.retryCount,
14407
- retry_delay: task.retryDelay,
14408
- retry_delay_max: task.retryDelayMax,
14409
- retry_delay_factor: task.retryDelayFactor,
14410
- service_name: serviceName2,
14411
- signals: {
14412
- emits: Array.from(task.emitsSignals),
14413
- signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
14414
- signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
14415
- observed: Array.from(task.observedSignals)
14416
- },
14417
- intents: Array.from(task.handlesIntents)
14418
- },
15359
+ data: taskRegistrationData,
14419
15360
  __taskName: task.name
14420
15361
  };
14421
15362
  }
@@ -15574,13 +16515,50 @@ var GraphSyncController = class _GraphSyncController {
15574
16515
  startActorPrimitiveSyncTask,
15575
16516
  startRoutinePrimitiveSyncTask
15576
16517
  );
15577
- const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
16518
+ const getAllTasksForSyncTask = CadenzaService.createMetaTask(
16519
+ "Get all tasks for sync",
16520
+ (ctx) => ({
16521
+ ...ctx,
16522
+ tasks: Array.from(CadenzaService.registry.tasks.values())
16523
+ }),
16524
+ "Collects local tasks for the primitive sync phase.",
16525
+ {
16526
+ register: false,
16527
+ isHidden: true
16528
+ }
16529
+ );
15578
16530
  startTaskPrimitiveSyncTask.then(
15579
16531
  getAllTasksForSyncTask,
15580
16532
  gatherTaskRegistrationTask
15581
16533
  );
15582
16534
  getAllTasksForSyncTask.then(this.splitTasksForRegistration);
15583
- const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
16535
+ const getSignalsForSyncTask = CadenzaService.createMetaTask(
16536
+ "Get signals for sync",
16537
+ (ctx) => {
16538
+ const uniqueSignals = Array.from(
16539
+ /* @__PURE__ */ new Set([
16540
+ ...CadenzaService.signalBroker.signalObservers.keys(),
16541
+ ...CadenzaService.signalBroker.emittedSignalsRegistry
16542
+ ])
16543
+ ).filter((signal) => !signal.includes(":"));
16544
+ const processedSignals = uniqueSignals.map((signal) => ({
16545
+ signal,
16546
+ data: {
16547
+ registered: CadenzaService.signalBroker.signalObservers.get(signal)?.registered ?? false,
16548
+ metadata: CadenzaService.signalBroker.getSignalMetadata(signal) ?? null
16549
+ }
16550
+ }));
16551
+ return {
16552
+ ...ctx,
16553
+ signals: processedSignals
16554
+ };
16555
+ },
16556
+ "Collects local signals for the primitive sync phase.",
16557
+ {
16558
+ register: false,
16559
+ isHidden: true
16560
+ }
16561
+ );
15584
16562
  startSignalPrimitiveSyncTask.then(
15585
16563
  getSignalsForSyncTask,
15586
16564
  gatherSignalRegistrationTask
@@ -15622,40 +16600,110 @@ var GraphSyncController = class _GraphSyncController {
15622
16600
  gatherActorRegistrationTask
15623
16601
  );
15624
16602
  getAllActorsForSyncTask.then(this.splitActorsForRegistration);
15625
- const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
16603
+ const getAllRoutinesForSyncTask = CadenzaService.createMetaTask(
16604
+ "Get all routines for sync",
16605
+ (ctx) => ({
16606
+ ...ctx,
16607
+ routines: Array.from(CadenzaService.registry.routines.values())
16608
+ }),
16609
+ "Collects local routines for the primitive sync phase.",
16610
+ {
16611
+ register: false,
16612
+ isHidden: true
16613
+ }
16614
+ );
15626
16615
  startRoutinePrimitiveSyncTask.then(
15627
16616
  getAllRoutinesForSyncTask,
15628
16617
  gatherRoutineRegistrationTask
15629
16618
  );
15630
16619
  getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
15631
- const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
16620
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
16621
+ "Iterate tasks for directional task map sync",
16622
+ function* (ctx) {
16623
+ for (const task of CadenzaService.registry.tasks.values()) {
16624
+ yield { ...ctx, task };
16625
+ }
16626
+ },
16627
+ "Iterates local tasks for directional task-map sync.",
16628
+ {
16629
+ register: false,
16630
+ isHidden: true
16631
+ }
16632
+ );
15632
16633
  startDirectionalTaskMapSyncTask.then(
15633
16634
  iterateTasksForDirectionalTaskMapSyncTask,
15634
16635
  gatherDirectionalTaskMapRegistrationTask
15635
16636
  );
15636
16637
  iterateTasksForDirectionalTaskMapSyncTask.then(this.registerTaskMapTask);
15637
16638
  recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
15638
- const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
16639
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.createMetaTask(
16640
+ "Iterate tasks for signal task map sync",
16641
+ function* (ctx) {
16642
+ for (const task of CadenzaService.registry.tasks.values()) {
16643
+ yield { ...ctx, task };
16644
+ }
16645
+ },
16646
+ "Iterates local tasks for signal-to-task map sync.",
16647
+ {
16648
+ register: false,
16649
+ isHidden: true
16650
+ }
16651
+ );
15639
16652
  startSignalTaskMapSyncTask.then(
15640
16653
  iterateTasksForSignalTaskMapSyncTask,
15641
16654
  gatherSignalTaskMapRegistrationTask
15642
16655
  );
15643
16656
  iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
15644
16657
  this.registerSignalToTaskMapTask.then(gatherSignalTaskMapRegistrationTask);
15645
- const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
16658
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.createMetaTask(
16659
+ "Iterate tasks for intent task map sync",
16660
+ function* (ctx) {
16661
+ for (const task of CadenzaService.registry.tasks.values()) {
16662
+ yield { ...ctx, task };
16663
+ }
16664
+ },
16665
+ "Iterates local tasks for intent-to-task map sync.",
16666
+ {
16667
+ register: false,
16668
+ isHidden: true
16669
+ }
16670
+ );
15646
16671
  startIntentTaskMapSyncTask.then(
15647
16672
  iterateTasksForIntentTaskMapSyncTask,
15648
16673
  gatherIntentTaskMapRegistrationTask
15649
16674
  );
15650
16675
  iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
15651
16676
  this.registerIntentToTaskMapTask.then(gatherIntentTaskMapRegistrationTask);
15652
- const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
16677
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.createMetaTask(
16678
+ "Iterate tasks for actor task map sync",
16679
+ function* (ctx) {
16680
+ for (const task of CadenzaService.registry.tasks.values()) {
16681
+ yield { ...ctx, task };
16682
+ }
16683
+ },
16684
+ "Iterates local tasks for actor-to-task map sync.",
16685
+ {
16686
+ register: false,
16687
+ isHidden: true
16688
+ }
16689
+ );
15653
16690
  startActorTaskMapSyncTask.then(
15654
16691
  iterateTasksForActorTaskMapSyncTask,
15655
16692
  gatherActorTaskMapRegistrationTask
15656
16693
  );
15657
16694
  iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
15658
- const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
16695
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.createMetaTask(
16696
+ "Get all routines for task map sync",
16697
+ (ctx) => ({
16698
+ ...ctx,
16699
+ routines: Array.from(CadenzaService.registry.routines.values())
16700
+ }),
16701
+ "Collects local routines for routine-to-task map sync.",
16702
+ {
16703
+ register: false,
16704
+ isHidden: true
16705
+ }
16706
+ );
15659
16707
  startRoutineTaskMapSyncTask.then(
15660
16708
  getAllRoutinesForTaskMapSyncTask,
15661
16709
  gatherRoutineTaskMapRegistrationTask
@@ -15731,11 +16779,37 @@ function resolveTaskByName(name) {
15731
16779
  const taskName = String(name ?? "");
15732
16780
  return taskName ? CadenzaService.get(taskName) : void 0;
15733
16781
  }
16782
+ function resolveHelperFromMetadataContext(ctx) {
16783
+ const toolRuntime = CadenzaService;
16784
+ const helperName = String(
16785
+ ctx?.helperName ?? ctx?.data?.helperName ?? ctx?.data?.helper_name ?? ctx?.filter?.helperName ?? ctx?.filter?.helper_name ?? ""
16786
+ );
16787
+ return helperName ? toolRuntime.getHelper?.(helperName) : void 0;
16788
+ }
16789
+ function resolveGlobalFromMetadataContext(ctx) {
16790
+ const toolRuntime = CadenzaService;
16791
+ const globalName = String(
16792
+ ctx?.globalName ?? ctx?.data?.globalName ?? ctx?.data?.global_name ?? ctx?.filter?.globalName ?? ctx?.filter?.global_name ?? ""
16793
+ );
16794
+ return globalName ? toolRuntime.getGlobal?.(globalName) : void 0;
16795
+ }
15734
16796
  function resolvePredecessorTaskFromMetadataContext(ctx) {
15735
16797
  return resolveTaskByName(
15736
16798
  ctx?.predecessorTaskName ?? ctx?.data?.predecessorTaskName ?? ctx?.data?.predecessor_task_name ?? ctx?.filter?.predecessorTaskName ?? ctx?.filter?.predecessor_task_name
15737
16799
  );
15738
16800
  }
16801
+ function sanitizePersistedTaskSourceFields2(task, data) {
16802
+ if (!task?.isMeta && !task?.isDeputy) {
16803
+ return data;
16804
+ }
16805
+ return {
16806
+ ...data,
16807
+ functionString: "",
16808
+ function_string: "",
16809
+ tagIdGetter: null,
16810
+ tag_id_getter: null
16811
+ };
16812
+ }
15739
16813
  function shouldSkipDirectTaskMetadata(task) {
15740
16814
  return !task || !task.register || task.isHidden || task.isDeputy;
15741
16815
  }
@@ -15813,6 +16887,9 @@ function shouldPersistBusinessInquiryCompletion(ctx) {
15813
16887
  const inquiryName = String(ctx?.data?.metadata?.inquiryMeta?.inquiry ?? "");
15814
16888
  return inquiryName.length > 0 && !isMetaIntentName(inquiryName);
15815
16889
  }
16890
+ function shouldPersistExecutionTrace(ctx) {
16891
+ return ctx?.data?.isMeta !== true && ctx?.data?.is_meta !== true;
16892
+ }
15816
16893
  function shouldPersistRoutineExecution(ctx) {
15817
16894
  if (ctx?.data?.isMeta === true || ctx?.data?.is_meta === true) {
15818
16895
  return false;
@@ -15876,10 +16953,10 @@ var GraphMetadataController = class _GraphMetadataController {
15876
16953
  task.registrationRequested = true;
15877
16954
  }
15878
16955
  return buildDatabaseTriggerContext(
15879
- {
16956
+ sanitizePersistedTaskSourceFields2(task, {
15880
16957
  ...ctx.data,
15881
16958
  serviceName: CadenzaService.serviceRegistry.serviceName
15882
- },
16959
+ }),
15883
16960
  void 0,
15884
16961
  { onConflict },
15885
16962
  { onConflict }
@@ -15982,6 +17059,88 @@ var GraphMetadataController = class _GraphMetadataController {
15982
17059
  serviceName: CadenzaService.serviceRegistry.serviceName
15983
17060
  });
15984
17061
  }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
17062
+ const buildHelperMetadataContext = (ctx) => {
17063
+ if (!shouldEmitDirectPrimitiveMetadata()) {
17064
+ return false;
17065
+ }
17066
+ const helper = resolveHelperFromMetadataContext(ctx);
17067
+ if (!helper) {
17068
+ return false;
17069
+ }
17070
+ return buildDatabaseTriggerContext({
17071
+ ...ctx.data,
17072
+ serviceName: CadenzaService.serviceRegistry.serviceName
17073
+ });
17074
+ };
17075
+ createLocalGraphMetadataTask("Handle helper creation", buildHelperMetadataContext).doOn("meta.helper.created").emits("global.meta.graph_metadata.helper_created");
17076
+ createLocalGraphMetadataTask("Handle helper update", buildHelperMetadataContext).doOn("meta.helper.updated").emits("global.meta.graph_metadata.helper_updated");
17077
+ const buildGlobalMetadataContext = (ctx) => {
17078
+ if (!shouldEmitDirectPrimitiveMetadata()) {
17079
+ return false;
17080
+ }
17081
+ const globalDefinition = resolveGlobalFromMetadataContext(ctx);
17082
+ if (!globalDefinition) {
17083
+ return false;
17084
+ }
17085
+ return buildDatabaseTriggerContext({
17086
+ ...ctx.data,
17087
+ serviceName: CadenzaService.serviceRegistry.serviceName
17088
+ });
17089
+ };
17090
+ createLocalGraphMetadataTask("Handle global creation", buildGlobalMetadataContext).doOn("meta.global.created").emits("global.meta.graph_metadata.global_created");
17091
+ createLocalGraphMetadataTask("Handle global update", buildGlobalMetadataContext).doOn("meta.global.updated").emits("global.meta.graph_metadata.global_updated");
17092
+ createLocalGraphMetadataTask("Handle task helper association", (ctx) => {
17093
+ if (!shouldEmitDirectPrimitiveMetadata()) {
17094
+ return false;
17095
+ }
17096
+ const task = resolveTaskFromMetadataContext(ctx);
17097
+ if (shouldSkipDirectTaskMetadata(task)) {
17098
+ return false;
17099
+ }
17100
+ return buildDatabaseTriggerContext({
17101
+ ...ctx.data,
17102
+ serviceName: CadenzaService.serviceRegistry.serviceName
17103
+ });
17104
+ }).doOn("meta.task.helper_associated").emits("global.meta.graph_metadata.task_helper_associated");
17105
+ createLocalGraphMetadataTask("Handle helper helper association", (ctx) => {
17106
+ if (!shouldEmitDirectPrimitiveMetadata()) {
17107
+ return false;
17108
+ }
17109
+ const helper = resolveHelperFromMetadataContext(ctx);
17110
+ if (!helper) {
17111
+ return false;
17112
+ }
17113
+ return buildDatabaseTriggerContext({
17114
+ ...ctx.data,
17115
+ serviceName: CadenzaService.serviceRegistry.serviceName
17116
+ });
17117
+ }).doOn("meta.helper.helper_associated").emits("global.meta.graph_metadata.helper_helper_associated");
17118
+ createLocalGraphMetadataTask("Handle task global association", (ctx) => {
17119
+ if (!shouldEmitDirectPrimitiveMetadata()) {
17120
+ return false;
17121
+ }
17122
+ const task = resolveTaskFromMetadataContext(ctx);
17123
+ if (shouldSkipDirectTaskMetadata(task)) {
17124
+ return false;
17125
+ }
17126
+ return buildDatabaseTriggerContext({
17127
+ ...ctx.data,
17128
+ serviceName: CadenzaService.serviceRegistry.serviceName
17129
+ });
17130
+ }).doOn("meta.task.global_associated").emits("global.meta.graph_metadata.task_global_associated");
17131
+ createLocalGraphMetadataTask("Handle helper global association", (ctx) => {
17132
+ if (!shouldEmitDirectPrimitiveMetadata()) {
17133
+ return false;
17134
+ }
17135
+ const helper = resolveHelperFromMetadataContext(ctx);
17136
+ if (!helper) {
17137
+ return false;
17138
+ }
17139
+ return buildDatabaseTriggerContext({
17140
+ ...ctx.data,
17141
+ serviceName: CadenzaService.serviceRegistry.serviceName
17142
+ });
17143
+ }).doOn("meta.helper.global_associated").emits("global.meta.graph_metadata.helper_global_associated");
15985
17144
  createLocalGraphMetadataTask("Handle task unsubscribing signal", (ctx) => {
15986
17145
  if (!shouldEmitDirectPrimitiveMetadata()) {
15987
17146
  return false;
@@ -16049,6 +17208,9 @@ var GraphMetadataController = class _GraphMetadataController {
16049
17208
  });
16050
17209
  }).doOn("meta.routine.task_added").emits("global.meta.graph_metadata.task_added_to_routine");
16051
17210
  createLocalGraphMetadataTask("Handle new trace", (ctx) => {
17211
+ if (!shouldPersistExecutionTrace(ctx)) {
17212
+ return false;
17213
+ }
16052
17214
  return buildDatabaseTriggerContext({
16053
17215
  ...ctx.data,
16054
17216
  service_name: CadenzaService.serviceRegistry.serviceName,
@@ -16062,10 +17224,10 @@ var GraphMetadataController = class _GraphMetadataController {
16062
17224
  return false;
16063
17225
  }
16064
17226
  const routineData = ctx.data ?? {};
16065
- const sanitizedRoutineContext = stripLocalRoutinePersistenceHints(
17227
+ const sanitizedRoutineContext = sanitizeExecutionPersistenceContext(
16066
17228
  routineData.context ?? {}
16067
17229
  );
16068
- const sanitizedRoutineMetaContext = stripLocalRoutinePersistenceHints(
17230
+ const sanitizedRoutineMetaContext = sanitizeExecutionPersistenceContext(
16069
17231
  routineData.metaContext ?? {}
16070
17232
  );
16071
17233
  const routineExecutionRow = {
@@ -16200,12 +17362,13 @@ var GraphMetadataController = class _GraphMetadataController {
16200
17362
  createLocalGraphMetadataTask(
16201
17363
  "Handle routine execution ended",
16202
17364
  (ctx) => {
17365
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
17366
+ ...ctx.data,
17367
+ serviceName: CadenzaService.serviceRegistry.serviceName,
17368
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
17369
+ });
16203
17370
  return buildDatabaseTriggerContext(
16204
- {
16205
- ...ctx.data,
16206
- serviceName: CadenzaService.serviceRegistry.serviceName,
16207
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
16208
- },
17371
+ sanitizedData,
16209
17372
  ctx.filter ?? void 0
16210
17373
  );
16211
17374
  },
@@ -16219,10 +17382,10 @@ var GraphMetadataController = class _GraphMetadataController {
16219
17382
  return false;
16220
17383
  }
16221
17384
  const taskExecutionData = ctx.data ?? {};
16222
- const sanitizedTaskContext = stripLocalRoutinePersistenceHints(
17385
+ const sanitizedTaskContext = sanitizeExecutionPersistenceContext(
16223
17386
  taskExecutionData.context ?? {}
16224
17387
  );
16225
- const sanitizedTaskMetaContext = stripLocalRoutinePersistenceHints(
17388
+ const sanitizedTaskMetaContext = sanitizeExecutionPersistenceContext(
16226
17389
  taskExecutionData.metaContext ?? {}
16227
17390
  );
16228
17391
  const routineMetadata = resolveRoutinePersistenceMetadata(
@@ -16455,12 +17618,13 @@ var GraphMetadataController = class _GraphMetadataController {
16455
17618
  if (!shouldPersistTaskExecutionMetadata(ctx)) {
16456
17619
  return false;
16457
17620
  }
17621
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
17622
+ ...ctx.data,
17623
+ serviceName: CadenzaService.serviceRegistry.serviceName,
17624
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
17625
+ });
16458
17626
  return buildDatabaseTriggerContext(
16459
- {
16460
- ...ctx.data,
16461
- serviceName: CadenzaService.serviceRegistry.serviceName,
16462
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
16463
- },
17627
+ sanitizedData,
16464
17628
  ctx.filter ?? void 0
16465
17629
  );
16466
17630
  },
@@ -17545,9 +18709,17 @@ var CadenzaService = class {
17545
18709
  "meta.task.relationship_added",
17546
18710
  "meta.task.relationship_removed",
17547
18711
  "meta.task.intent_associated",
18712
+ "meta.task.helper_associated",
18713
+ "meta.task.global_associated",
17548
18714
  "meta.task.observed_signal",
17549
18715
  "meta.task.attached_signal",
17550
18716
  "meta.task.detached_signal",
18717
+ "meta.helper.created",
18718
+ "meta.helper.updated",
18719
+ "meta.global.created",
18720
+ "meta.global.updated",
18721
+ "meta.helper.helper_associated",
18722
+ "meta.helper.global_associated",
17551
18723
  "meta.actor.created",
17552
18724
  "meta.actor.task_associated",
17553
18725
  "meta.fetch.handshake_complete",