@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.
package/dist/index.js CHANGED
@@ -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
 
@@ -4142,6 +4290,10 @@ function normalizeServiceInstanceDescriptor(value) {
4142
4290
  return null;
4143
4291
  }
4144
4292
  const transports = normalizeTransportArray(raw.transports, uuid10);
4293
+ const leaseStatusRaw = normalizeString2(raw.leaseStatus ?? raw.lease_status);
4294
+ const leaseStatus = leaseStatusRaw === "active" || leaseStatusRaw === "non_responsive" || leaseStatusRaw === "inactive" || leaseStatusRaw === "deleted" ? leaseStatusRaw : void 0;
4295
+ const isActive = leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isActive ?? raw.is_active ?? true);
4296
+ const isNonResponsive = leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isNonResponsive ?? raw.is_non_responsive ?? false);
4145
4297
  return {
4146
4298
  uuid: uuid10,
4147
4299
  serviceName,
@@ -4152,10 +4304,16 @@ function normalizeServiceInstanceDescriptor(value) {
4152
4304
  )
4153
4305
  ),
4154
4306
  isPrimary: Boolean(raw.isPrimary ?? raw.is_primary ?? false),
4155
- isActive: Boolean(raw.isActive ?? raw.is_active ?? true),
4156
- isNonResponsive: Boolean(
4157
- raw.isNonResponsive ?? raw.is_non_responsive ?? false
4158
- ),
4307
+ leaseStatus,
4308
+ leaseExpiresAt: typeof raw.leaseExpiresAt === "string" ? raw.leaseExpiresAt : typeof raw.lease_expires_at === "string" ? raw.lease_expires_at : void 0,
4309
+ lastLeaseRenewedAt: typeof raw.lastLeaseRenewedAt === "string" ? raw.lastLeaseRenewedAt : typeof raw.last_lease_renewed_at === "string" ? raw.last_lease_renewed_at : void 0,
4310
+ isReady: typeof raw.isReady === "boolean" ? raw.isReady : typeof raw.is_ready === "boolean" ? raw.is_ready : void 0,
4311
+ readinessReason: typeof raw.readinessReason === "string" ? raw.readinessReason : typeof raw.readiness_reason === "string" ? raw.readiness_reason : null,
4312
+ lastReadyAt: typeof raw.lastReadyAt === "string" ? raw.lastReadyAt : typeof raw.last_ready_at === "string" ? raw.last_ready_at : null,
4313
+ lastObservedTransportAt: typeof raw.lastObservedTransportAt === "string" ? raw.lastObservedTransportAt : typeof raw.last_observed_transport_at === "string" ? raw.last_observed_transport_at : null,
4314
+ shutdownRequestedAt: typeof raw.shutdownRequestedAt === "string" ? raw.shutdownRequestedAt : typeof raw.shutdown_requested_at === "string" ? raw.shutdown_requested_at : null,
4315
+ isActive,
4316
+ isNonResponsive,
4159
4317
  isBlocked: Boolean(raw.isBlocked ?? raw.is_blocked ?? false),
4160
4318
  runtimeState: raw.runtimeState === "healthy" || raw.runtimeState === "degraded" || raw.runtimeState === "overloaded" || raw.runtimeState === "unavailable" ? raw.runtimeState : void 0,
4161
4319
  acceptingWork: typeof raw.acceptingWork === "boolean" ? raw.acceptingWork : void 0,
@@ -4608,6 +4766,61 @@ function resolveHealthMetric(input, keys) {
4608
4766
  }
4609
4767
  return void 0;
4610
4768
  }
4769
+ function sanitizeRuntimeMetricsHealthDetail(value) {
4770
+ if (!value || typeof value !== "object") {
4771
+ return void 0;
4772
+ }
4773
+ const input = value;
4774
+ const sampledAt = typeof input.sampledAt === "string" && input.sampledAt.trim().length > 0 ? input.sampledAt : void 0;
4775
+ const cpuUsage = normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4776
+ const memoryUsage = normalizeOptionalMetric(
4777
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4778
+ );
4779
+ const eventLoopLag = normalizeOptionalMetric(
4780
+ input.eventLoopLag ?? input.eventLoopLagMs
4781
+ );
4782
+ const rssBytes = normalizeOptionalMetric(input.rssBytes);
4783
+ const heapUsedBytes = normalizeOptionalMetric(input.heapUsedBytes);
4784
+ const heapTotalBytes = normalizeOptionalMetric(input.heapTotalBytes);
4785
+ const memoryLimitBytes = normalizeOptionalMetric(input.memoryLimitBytes);
4786
+ 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) {
4787
+ return void 0;
4788
+ }
4789
+ return {
4790
+ ...sampledAt !== void 0 ? { sampledAt } : {},
4791
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4792
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4793
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4794
+ ...rssBytes !== void 0 ? { rssBytes } : {},
4795
+ ...heapUsedBytes !== void 0 ? { heapUsedBytes } : {},
4796
+ ...heapTotalBytes !== void 0 ? { heapTotalBytes } : {},
4797
+ ...memoryLimitBytes !== void 0 ? { memoryLimitBytes } : {}
4798
+ };
4799
+ }
4800
+ function sanitizeAuthorityRuntimeStatusHealth(health, options) {
4801
+ const input = health && typeof health === "object" ? health : {};
4802
+ const cpuUsage = options?.cpuUsage !== void 0 ? options.cpuUsage : normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4803
+ const memoryUsage = options?.memoryUsage !== void 0 ? options.memoryUsage : normalizeOptionalMetric(
4804
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4805
+ );
4806
+ const eventLoopLag = options?.eventLoopLag !== void 0 ? options.eventLoopLag : normalizeOptionalMetric(input.eventLoopLag ?? input.eventLoopLagMs);
4807
+ const runtimeMetrics = sanitizeRuntimeMetricsHealthDetail(input.runtimeMetrics);
4808
+ const runtimeStatus = options?.state || options?.reportedAt || typeof options?.acceptingWork === "boolean" ? {
4809
+ ...options?.state ? { state: options.state } : {},
4810
+ ...typeof options?.acceptingWork === "boolean" ? { acceptingWork: options.acceptingWork } : {},
4811
+ ...options?.reportedAt ? { reportedAt: options.reportedAt } : {}
4812
+ } : void 0;
4813
+ if (cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && !runtimeMetrics && !runtimeStatus) {
4814
+ return void 0;
4815
+ }
4816
+ return {
4817
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4818
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4819
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4820
+ ...runtimeMetrics ? { runtimeMetrics } : {},
4821
+ ...runtimeStatus ? { runtimeStatus } : {}
4822
+ };
4823
+ }
4611
4824
  function normalizeAuthorityRuntimeStatusReport(input) {
4612
4825
  if (!input || typeof input !== "object") {
4613
4826
  return null;
@@ -4636,6 +4849,17 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4636
4849
  (protocol) => protocol === "rest" || protocol === "socket"
4637
4850
  ) : [];
4638
4851
  const transportProtocols = transportProtocolList.length > 0 ? Array.from(new Set(transportProtocolList)) : void 0;
4852
+ const acceptingWork = Boolean(input.acceptingWork ?? input.accepting_work);
4853
+ const cpuUsage = resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]);
4854
+ const memoryUsage = resolveHealthMetric(input, [
4855
+ "memoryUsage",
4856
+ "memory",
4857
+ "memoryPressure"
4858
+ ]);
4859
+ const eventLoopLag = resolveHealthMetric(input, [
4860
+ "eventLoopLag",
4861
+ "eventLoopLagMs"
4862
+ ]);
4639
4863
  return {
4640
4864
  serviceName,
4641
4865
  serviceInstanceId,
@@ -4646,7 +4870,7 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4646
4870
  isFrontend: typeof input.isFrontend === "boolean" ? input.isFrontend : typeof input.is_frontend === "boolean" ? input.is_frontend : void 0,
4647
4871
  reportedAt,
4648
4872
  state,
4649
- acceptingWork: Boolean(input.acceptingWork ?? input.accepting_work),
4873
+ acceptingWork,
4650
4874
  numberOfRunningGraphs: Math.max(
4651
4875
  0,
4652
4876
  Math.trunc(
@@ -4655,22 +4879,22 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4655
4879
  ) || 0
4656
4880
  )
4657
4881
  ),
4658
- cpuUsage: resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]),
4659
- memoryUsage: resolveHealthMetric(input, [
4660
- "memoryUsage",
4661
- "memory",
4662
- "memoryPressure"
4663
- ]),
4664
- eventLoopLag: resolveHealthMetric(input, [
4665
- "eventLoopLag",
4666
- "eventLoopLagMs"
4667
- ]),
4882
+ cpuUsage,
4883
+ memoryUsage,
4884
+ eventLoopLag,
4668
4885
  isActive: Boolean(input.isActive ?? input.is_active ?? true),
4669
4886
  isNonResponsive: Boolean(
4670
4887
  input.isNonResponsive ?? input.is_non_responsive ?? false
4671
4888
  ),
4672
4889
  isBlocked: Boolean(input.isBlocked ?? input.is_blocked ?? false),
4673
- health: input.health && typeof input.health === "object" ? input.health : void 0
4890
+ health: sanitizeAuthorityRuntimeStatusHealth(input.health, {
4891
+ state,
4892
+ acceptingWork,
4893
+ reportedAt,
4894
+ cpuUsage,
4895
+ memoryUsage,
4896
+ eventLoopLag
4897
+ })
4674
4898
  };
4675
4899
  }
4676
4900
  function buildAuthorityRuntimeStatusSignature(report) {
@@ -4683,18 +4907,53 @@ function buildAuthorityRuntimeStatusSignature(report) {
4683
4907
  transportProtocols: report.transportProtocols ?? [],
4684
4908
  state: report.state,
4685
4909
  acceptingWork: report.acceptingWork,
4686
- numberOfRunningGraphs: report.numberOfRunningGraphs,
4687
- cpuUsage: report.cpuUsage ?? null,
4688
- memoryUsage: report.memoryUsage ?? null,
4689
- eventLoopLag: report.eventLoopLag ?? null,
4690
4910
  isActive: report.isActive,
4691
4911
  isNonResponsive: report.isNonResponsive,
4692
4912
  isBlocked: report.isBlocked,
4693
- isFrontend: report.isFrontend ?? null,
4694
- health: report.health ?? {}
4913
+ isFrontend: report.isFrontend ?? null
4695
4914
  });
4696
4915
  }
4697
4916
 
4917
+ // src/registry/runtimeJitter.ts
4918
+ function normalizeKey(key) {
4919
+ return key.trim() || "default";
4920
+ }
4921
+ function hashKeyToUnitInterval(key) {
4922
+ const normalizedKey = normalizeKey(key);
4923
+ let hash = 2166136261;
4924
+ for (let index = 0; index < normalizedKey.length; index += 1) {
4925
+ hash ^= normalizedKey.charCodeAt(index);
4926
+ hash = Math.imul(hash, 16777619);
4927
+ }
4928
+ return (hash >>> 0) / 4294967295;
4929
+ }
4930
+ function normalizeJitterRatio(value) {
4931
+ if (!Number.isFinite(value) || value <= 0) {
4932
+ return 0;
4933
+ }
4934
+ return Math.min(value, 1);
4935
+ }
4936
+ function buildDeterministicJitterOffsetMs(baseMs, ratio, key) {
4937
+ if (!Number.isFinite(baseMs) || baseMs <= 0) {
4938
+ return 0;
4939
+ }
4940
+ const normalizedRatio = normalizeJitterRatio(ratio);
4941
+ if (normalizedRatio <= 0) {
4942
+ return 0;
4943
+ }
4944
+ const maxOffsetMs = Math.round(baseMs * normalizedRatio);
4945
+ if (maxOffsetMs <= 0) {
4946
+ return 0;
4947
+ }
4948
+ return Math.round(hashKeyToUnitInterval(key) * maxOffsetMs);
4949
+ }
4950
+ function buildDeterministicJitteredDelayMs(baseMs, ratio, key) {
4951
+ return Math.max(
4952
+ 0,
4953
+ Math.round(baseMs) + buildDeterministicJitterOffsetMs(baseMs, ratio, key)
4954
+ );
4955
+ }
4956
+
4698
4957
  // src/registry/serviceManifestContract.ts
4699
4958
  var AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT = "meta-service-registry-authority-service-manifest-report";
4700
4959
  var AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL = "global.meta.cadenza_db.service_manifest_updated";
@@ -4726,11 +4985,17 @@ function normalizeServiceManifestSnapshot(input) {
4726
4985
  intents: normalizeArray(record.intents),
4727
4986
  actors: normalizeArray(record.actors),
4728
4987
  routines: normalizeArray(record.routines),
4988
+ helpers: normalizeArray(record.helpers),
4989
+ globals: normalizeArray(record.globals),
4729
4990
  directionalTaskMaps: normalizeArray(record.directionalTaskMaps),
4730
4991
  signalToTaskMaps: normalizeArray(record.signalToTaskMaps),
4731
4992
  intentToTaskMaps: normalizeArray(record.intentToTaskMaps),
4732
4993
  actorTaskMaps: normalizeArray(record.actorTaskMaps),
4733
- taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps)
4994
+ taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps),
4995
+ taskToHelperMaps: normalizeArray(record.taskToHelperMaps),
4996
+ helperToHelperMaps: normalizeArray(record.helperToHelperMaps),
4997
+ taskToGlobalMaps: normalizeArray(record.taskToGlobalMaps),
4998
+ helperToGlobalMaps: normalizeArray(record.helperToGlobalMaps)
4734
4999
  };
4735
5000
  }
4736
5001
  function selectLatestServiceManifestSnapshots(snapshots) {
@@ -4994,6 +5259,27 @@ function buildRoutineDefinition(routine, serviceName) {
4994
5259
  is_meta: routine.isMeta === true
4995
5260
  };
4996
5261
  }
5262
+ function buildHelperDefinition(helper, serviceName) {
5263
+ return {
5264
+ name: helper.name,
5265
+ version: helper.version,
5266
+ description: helper.description,
5267
+ service_name: serviceName,
5268
+ is_meta: helper.isMeta === true,
5269
+ handler_source: helper.helperFunction.toString(),
5270
+ language: "js"
5271
+ };
5272
+ }
5273
+ function buildGlobalDefinition(globalDefinition, serviceName) {
5274
+ return {
5275
+ name: globalDefinition.name,
5276
+ version: globalDefinition.version,
5277
+ description: globalDefinition.description,
5278
+ service_name: serviceName,
5279
+ is_meta: globalDefinition.isMeta === true,
5280
+ value: sanitizeManifestValue(globalDefinition.value)
5281
+ };
5282
+ }
4997
5283
  function shouldExportTask(task) {
4998
5284
  return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
4999
5285
  }
@@ -5009,6 +5295,12 @@ function buildActorKey(actor) {
5009
5295
  function buildRoutineKey(routine) {
5010
5296
  return `${routine.service_name}|${routine.name}|${routine.version}`;
5011
5297
  }
5298
+ function buildHelperKey(helper) {
5299
+ return `${helper.service_name}|${helper.name}|${helper.version}`;
5300
+ }
5301
+ function buildGlobalKey(globalDefinition) {
5302
+ return `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`;
5303
+ }
5012
5304
  function listManifestTasks() {
5013
5305
  const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
5014
5306
  (task) => Boolean(task)
@@ -5022,6 +5314,18 @@ function listManifestTasks() {
5022
5314
  ).values()
5023
5315
  );
5024
5316
  }
5317
+ function listManifestHelpers() {
5318
+ const toolRuntime = CadenzaService;
5319
+ return (toolRuntime.getAllHelpers?.() ?? []).filter(
5320
+ (helper) => Boolean(helper && !helper.destroyed)
5321
+ );
5322
+ }
5323
+ function listManifestGlobals() {
5324
+ const toolRuntime = CadenzaService;
5325
+ return (toolRuntime.getAllGlobals?.() ?? []).filter(
5326
+ (globalDefinition) => Boolean(globalDefinition && !globalDefinition.destroyed)
5327
+ );
5328
+ }
5025
5329
  function isRoutingCriticalMetaSignal(_signal) {
5026
5330
  return false;
5027
5331
  }
@@ -5037,6 +5341,8 @@ function buildServiceManifestSnapshot(params) {
5037
5341
  publicationLayer = "business_structural"
5038
5342
  } = params;
5039
5343
  const tasks = listManifestTasks().filter(shouldExportTask);
5344
+ const helpers = listManifestHelpers();
5345
+ const globals = listManifestGlobals();
5040
5346
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
5041
5347
  const actors = CadenzaService.getAllActors();
5042
5348
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -5048,6 +5354,10 @@ function buildServiceManifestSnapshot(params) {
5048
5354
  const directionalTaskMaps = /* @__PURE__ */ new Map();
5049
5355
  const actorTaskMaps = /* @__PURE__ */ new Map();
5050
5356
  const taskToRoutineMaps = /* @__PURE__ */ new Map();
5357
+ const helperTaskMaps = /* @__PURE__ */ new Map();
5358
+ const helperHelperMaps = /* @__PURE__ */ new Map();
5359
+ const taskGlobalMaps = /* @__PURE__ */ new Map();
5360
+ const helperGlobalMaps = /* @__PURE__ */ new Map();
5051
5361
  const registerSignal = (signalName) => {
5052
5362
  const normalizedSignalName = canonicalizeSignalName(signalName);
5053
5363
  if (!normalizedSignalName || signalDefinitions.has(normalizedSignalName)) {
@@ -5131,6 +5441,37 @@ function buildServiceManifestSnapshot(params) {
5131
5441
  is_meta: actorTaskMetadata.actorKind === "meta" || task.isMeta === true
5132
5442
  });
5133
5443
  }
5444
+ const taskTools = task;
5445
+ for (const [alias, helperName] of taskTools.helperAliases?.entries?.() ?? []) {
5446
+ const helper = CadenzaService.getHelper?.(helperName);
5447
+ if (!helper) {
5448
+ continue;
5449
+ }
5450
+ const key = `${task.name}|${task.version}|${alias}|${helper.name}|${helper.version}|${serviceName}`;
5451
+ helperTaskMaps.set(key, {
5452
+ task_name: task.name,
5453
+ task_version: task.version,
5454
+ service_name: serviceName,
5455
+ alias,
5456
+ helper_name: helper.name,
5457
+ helper_version: helper.version
5458
+ });
5459
+ }
5460
+ for (const [alias, globalName] of taskTools.globalAliases?.entries?.() ?? []) {
5461
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5462
+ if (!globalDefinition) {
5463
+ continue;
5464
+ }
5465
+ const key = `${task.name}|${task.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5466
+ taskGlobalMaps.set(key, {
5467
+ task_name: task.name,
5468
+ task_version: task.version,
5469
+ service_name: serviceName,
5470
+ alias,
5471
+ global_name: globalDefinition.name,
5472
+ global_version: globalDefinition.version
5473
+ });
5474
+ }
5134
5475
  }
5135
5476
  const intentDefinitions = Array.from(CadenzaService.inquiryBroker.intents.values()).map((intent) => {
5136
5477
  const intentRecord = intent;
@@ -5162,6 +5503,44 @@ function buildServiceManifestSnapshot(params) {
5162
5503
  ).sort(
5163
5504
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5164
5505
  );
5506
+ const helperDefinitions = helpers.map((helper) => buildHelperDefinition(helper, serviceName)).sort(
5507
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5508
+ );
5509
+ const globalDefinitions = globals.map((globalDefinition) => buildGlobalDefinition(globalDefinition, serviceName)).sort(
5510
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5511
+ );
5512
+ for (const helper of helpers) {
5513
+ for (const [alias, dependencyHelperName] of helper.helperAliases.entries()) {
5514
+ const dependencyHelper = CadenzaService.getHelper?.(dependencyHelperName);
5515
+ if (!dependencyHelper) {
5516
+ continue;
5517
+ }
5518
+ const key = `${helper.name}|${helper.version}|${alias}|${dependencyHelper.name}|${dependencyHelper.version}|${serviceName}`;
5519
+ helperHelperMaps.set(key, {
5520
+ helper_name: helper.name,
5521
+ helper_version: helper.version,
5522
+ service_name: serviceName,
5523
+ alias,
5524
+ dependency_helper_name: dependencyHelper.name,
5525
+ dependency_helper_version: dependencyHelper.version
5526
+ });
5527
+ }
5528
+ for (const [alias, globalName] of helper.globalAliases.entries()) {
5529
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5530
+ if (!globalDefinition) {
5531
+ continue;
5532
+ }
5533
+ const key = `${helper.name}|${helper.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5534
+ helperGlobalMaps.set(key, {
5535
+ helper_name: helper.name,
5536
+ helper_version: helper.version,
5537
+ service_name: serviceName,
5538
+ alias,
5539
+ global_name: globalDefinition.name,
5540
+ global_version: globalDefinition.version
5541
+ });
5542
+ }
5543
+ }
5165
5544
  for (const routine of routines) {
5166
5545
  for (const task of routine.tasks) {
5167
5546
  if (!task) {
@@ -5199,6 +5578,15 @@ function buildServiceManifestSnapshot(params) {
5199
5578
  const routineDefinitionsByKey = new Map(
5200
5579
  routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
5201
5580
  );
5581
+ const helperDefinitionsByKey = new Map(
5582
+ helperDefinitions.map((helper) => [buildHelperKey(helper), helper])
5583
+ );
5584
+ const globalDefinitionsByKey = new Map(
5585
+ globalDefinitions.map((globalDefinition) => [
5586
+ buildGlobalKey(globalDefinition),
5587
+ globalDefinition
5588
+ ])
5589
+ );
5202
5590
  const routingTaskKeys = /* @__PURE__ */ new Set();
5203
5591
  const routingSignalNames = /* @__PURE__ */ new Set();
5204
5592
  const routingIntentNames = /* @__PURE__ */ new Set();
@@ -5516,6 +5904,112 @@ function buildServiceManifestSnapshot(params) {
5516
5904
  ).sort(
5517
5905
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5518
5906
  );
5907
+ const businessHelpers = helperDefinitions.filter((helper) => helper.is_meta !== true).sort(
5908
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5909
+ );
5910
+ const localMetaHelpers = helperDefinitions.filter((helper) => helper.is_meta === true).sort(
5911
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5912
+ );
5913
+ const businessGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta !== true).sort(
5914
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5915
+ );
5916
+ const localMetaGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta === true).sort(
5917
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5918
+ );
5919
+ const businessTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => {
5920
+ const task = taskDefinitionsByKey.get(
5921
+ buildTaskKey({
5922
+ service_name: map.service_name,
5923
+ name: map.task_name,
5924
+ version: map.task_version
5925
+ })
5926
+ );
5927
+ const helper = helperDefinitionsByKey.get(
5928
+ buildHelperKey({
5929
+ service_name: map.service_name,
5930
+ name: map.helper_name,
5931
+ version: map.helper_version
5932
+ })
5933
+ );
5934
+ return task?.is_meta !== true && task?.is_sub_meta !== true && helper?.is_meta !== true;
5935
+ }).sort(
5936
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5937
+ );
5938
+ const localMetaTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => !businessTaskToHelperMaps.includes(map)).sort(
5939
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5940
+ );
5941
+ const businessHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => {
5942
+ const helper = helperDefinitionsByKey.get(
5943
+ buildHelperKey({
5944
+ service_name: map.service_name,
5945
+ name: map.helper_name,
5946
+ version: map.helper_version
5947
+ })
5948
+ );
5949
+ const dependencyHelper = helperDefinitionsByKey.get(
5950
+ buildHelperKey({
5951
+ service_name: map.service_name,
5952
+ name: map.dependency_helper_name,
5953
+ version: map.dependency_helper_version
5954
+ })
5955
+ );
5956
+ return helper?.is_meta !== true && dependencyHelper?.is_meta !== true;
5957
+ }).sort(
5958
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5959
+ );
5960
+ const localMetaHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => !businessHelperToHelperMaps.includes(map)).sort(
5961
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5962
+ );
5963
+ const businessTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => {
5964
+ const task = taskDefinitionsByKey.get(
5965
+ buildTaskKey({
5966
+ service_name: map.service_name,
5967
+ name: map.task_name,
5968
+ version: map.task_version
5969
+ })
5970
+ );
5971
+ const globalDefinition = globalDefinitionsByKey.get(
5972
+ buildGlobalKey({
5973
+ service_name: map.service_name,
5974
+ name: map.global_name,
5975
+ version: map.global_version
5976
+ })
5977
+ );
5978
+ return task?.is_meta !== true && task?.is_sub_meta !== true && globalDefinition?.is_meta !== true;
5979
+ }).sort(
5980
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5981
+ );
5982
+ const localMetaTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => !businessTaskToGlobalMaps.includes(map)).sort(
5983
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5984
+ );
5985
+ const businessHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => {
5986
+ const helper = helperDefinitionsByKey.get(
5987
+ buildHelperKey({
5988
+ service_name: map.service_name,
5989
+ name: map.helper_name,
5990
+ version: map.helper_version
5991
+ })
5992
+ );
5993
+ const globalDefinition = globalDefinitionsByKey.get(
5994
+ buildGlobalKey({
5995
+ service_name: map.service_name,
5996
+ name: map.global_name,
5997
+ version: map.global_version
5998
+ })
5999
+ );
6000
+ return helper?.is_meta !== true && globalDefinition?.is_meta !== true;
6001
+ }).sort(
6002
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
6003
+ );
6004
+ const localMetaHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => !businessHelperToGlobalMaps.includes(map)).sort(
6005
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
6006
+ );
6007
+ const cumulativeHelpers = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelpers : [...businessHelpers, ...localMetaHelpers];
6008
+ const cumulativeGlobals = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessGlobals : [...businessGlobals, ...localMetaGlobals];
6009
+ const cumulativeTaskToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToHelperMaps : [...businessTaskToHelperMaps, ...localMetaTaskToHelperMaps];
6010
+ const cumulativeHelperToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToHelperMaps : [...businessHelperToHelperMaps, ...localMetaHelperToHelperMaps];
6011
+ const cumulativeTaskToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToGlobalMaps : [...businessTaskToGlobalMaps, ...localMetaTaskToGlobalMaps];
6012
+ const cumulativeHelperToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToGlobalMaps : [...businessHelperToGlobalMaps, ...localMetaHelperToGlobalMaps];
5519
6013
  const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
5520
6014
  new Map(
5521
6015
  [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
@@ -5558,11 +6052,17 @@ function buildServiceManifestSnapshot(params) {
5558
6052
  intents: cumulativeIntents,
5559
6053
  actors: cumulativeActors,
5560
6054
  routines: cumulativeRoutines,
6055
+ helpers: cumulativeHelpers,
6056
+ globals: cumulativeGlobals,
5561
6057
  directionalTaskMaps: cumulativeDirectionalTaskMaps,
5562
6058
  signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
5563
6059
  intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
5564
6060
  actorTaskMaps: cumulativeActorTaskMaps,
5565
- taskToRoutineMaps: cumulativeTaskToRoutineMaps
6061
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps,
6062
+ taskToHelperMaps: cumulativeTaskToHelperMaps,
6063
+ helperToHelperMaps: cumulativeHelperToHelperMaps,
6064
+ taskToGlobalMaps: cumulativeTaskToGlobalMaps,
6065
+ helperToGlobalMaps: cumulativeHelperToGlobalMaps
5566
6066
  };
5567
6067
  return {
5568
6068
  ...manifestBody,
@@ -5606,6 +6106,20 @@ function explodeServiceManifestSnapshots(snapshots) {
5606
6106
  `${right.service_name}|${right.name}|${right.version}`
5607
6107
  )
5608
6108
  );
6109
+ const helpers = dedupe(
6110
+ snapshots.flatMap((snapshot) => snapshot.helpers),
6111
+ (helper) => `${helper.service_name}|${helper.name}|${helper.version}`,
6112
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6113
+ `${right.service_name}|${right.name}|${right.version}`
6114
+ )
6115
+ );
6116
+ const globals = dedupe(
6117
+ snapshots.flatMap((snapshot) => snapshot.globals),
6118
+ (globalDefinition) => `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`,
6119
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6120
+ `${right.service_name}|${right.name}|${right.version}`
6121
+ )
6122
+ );
5609
6123
  const directionalTaskMaps = dedupe(
5610
6124
  snapshots.flatMap((snapshot) => snapshot.directionalTaskMaps),
5611
6125
  (map) => `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
@@ -5641,17 +6155,51 @@ function explodeServiceManifestSnapshots(snapshots) {
5641
6155
  `${right.routine_name}|${right.routine_version}|${right.service_name}|${right.task_name}|${right.task_version}`
5642
6156
  )
5643
6157
  );
6158
+ const taskToHelperMaps = dedupe(
6159
+ snapshots.flatMap((snapshot) => snapshot.taskToHelperMaps),
6160
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.helper_name}|${map.helper_version}`,
6161
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.helper_name}`.localeCompare(
6162
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.helper_name}`
6163
+ )
6164
+ );
6165
+ const helperToHelperMaps = dedupe(
6166
+ snapshots.flatMap((snapshot) => snapshot.helperToHelperMaps),
6167
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.dependency_helper_name}|${map.dependency_helper_version}`,
6168
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.dependency_helper_name}`.localeCompare(
6169
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.dependency_helper_name}`
6170
+ )
6171
+ );
6172
+ const taskToGlobalMaps = dedupe(
6173
+ snapshots.flatMap((snapshot) => snapshot.taskToGlobalMaps),
6174
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6175
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.global_name}`.localeCompare(
6176
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.global_name}`
6177
+ )
6178
+ );
6179
+ const helperToGlobalMaps = dedupe(
6180
+ snapshots.flatMap((snapshot) => snapshot.helperToGlobalMaps),
6181
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6182
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.global_name}`.localeCompare(
6183
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.global_name}`
6184
+ )
6185
+ );
5644
6186
  return {
5645
6187
  tasks,
5646
6188
  signals,
5647
6189
  intents,
5648
6190
  actors,
5649
6191
  routines,
6192
+ helpers,
6193
+ globals,
5650
6194
  directionalTaskMaps,
5651
6195
  signalToTaskMaps,
5652
6196
  intentToTaskMaps,
5653
6197
  actorTaskMaps,
5654
- taskToRoutineMaps
6198
+ taskToRoutineMaps,
6199
+ taskToHelperMaps,
6200
+ helperToHelperMaps,
6201
+ taskToGlobalMaps,
6202
+ helperToGlobalMaps
5655
6203
  };
5656
6204
  }
5657
6205
 
@@ -5700,11 +6248,57 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
5700
6248
  function shouldTraceServiceRegistry(serviceName) {
5701
6249
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
5702
6250
  }
5703
- function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
5704
- const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
5705
- const getJoinedValue = (key) => {
5706
- for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
5707
- const joinedContext = joinedContexts[index];
6251
+ function normalizeLeaseStatus(value) {
6252
+ const status = String(value ?? "").trim();
6253
+ if (status === "active" || status === "non_responsive" || status === "inactive" || status === "deleted") {
6254
+ return status;
6255
+ }
6256
+ return null;
6257
+ }
6258
+ function overlayServiceInstancesWithLeases(serviceInstances, serviceInstanceLeases) {
6259
+ if (serviceInstanceLeases.length === 0) {
6260
+ return serviceInstances;
6261
+ }
6262
+ const leasesByInstanceId = /* @__PURE__ */ new Map();
6263
+ for (const row of serviceInstanceLeases) {
6264
+ const serviceInstanceId = String(
6265
+ row.service_instance_id ?? row.serviceInstanceId ?? ""
6266
+ ).trim();
6267
+ if (!serviceInstanceId) {
6268
+ continue;
6269
+ }
6270
+ leasesByInstanceId.set(serviceInstanceId, row);
6271
+ }
6272
+ return serviceInstances.map((row) => {
6273
+ const serviceInstanceId = String(row.uuid ?? "").trim();
6274
+ const lease = serviceInstanceId ? leasesByInstanceId.get(serviceInstanceId) : void 0;
6275
+ if (!lease) {
6276
+ return row;
6277
+ }
6278
+ const leaseStatus = normalizeLeaseStatus(
6279
+ lease.status ?? lease.lease_status ?? lease.leaseStatus
6280
+ );
6281
+ return {
6282
+ ...row,
6283
+ lease_status: leaseStatus ?? void 0,
6284
+ is_ready: typeof lease.is_ready === "boolean" ? lease.is_ready : typeof lease.isReady === "boolean" ? lease.isReady : void 0,
6285
+ readiness_reason: typeof lease.readiness_reason === "string" ? lease.readiness_reason : typeof lease.readinessReason === "string" ? lease.readinessReason : null,
6286
+ lease_expires_at: typeof lease.lease_expires_at === "string" ? lease.lease_expires_at : typeof lease.leaseExpiresAt === "string" ? lease.leaseExpiresAt : null,
6287
+ last_lease_renewed_at: typeof lease.last_lease_renewed_at === "string" ? lease.last_lease_renewed_at : typeof lease.lastLeaseRenewedAt === "string" ? lease.lastLeaseRenewedAt : null,
6288
+ last_ready_at: typeof lease.last_ready_at === "string" ? lease.last_ready_at : typeof lease.lastReadyAt === "string" ? lease.lastReadyAt : null,
6289
+ last_observed_transport_at: typeof lease.last_observed_transport_at === "string" ? lease.last_observed_transport_at : typeof lease.lastObservedTransportAt === "string" ? lease.lastObservedTransportAt : null,
6290
+ shutdown_requested_at: typeof lease.shutdown_requested_at === "string" ? lease.shutdown_requested_at : typeof lease.shutdownRequestedAt === "string" ? lease.shutdownRequestedAt : null,
6291
+ is_active: leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_active,
6292
+ is_non_responsive: leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_non_responsive,
6293
+ deleted: leaseStatus === "deleted" ? true : Boolean(row.deleted ?? false)
6294
+ };
6295
+ });
6296
+ }
6297
+ function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
6298
+ const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
6299
+ const getJoinedValue = (key) => {
6300
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
6301
+ const joinedContext = joinedContexts[index];
5708
6302
  if (joinedContext && typeof joinedContext === "object" && (Object.prototype.hasOwnProperty.call(joinedContext, key) || joinedContext[key] !== void 0)) {
5709
6303
  return joinedContext[key];
5710
6304
  }
@@ -5777,6 +6371,43 @@ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
5777
6371
  }
5778
6372
  return sanitized;
5779
6373
  }
6374
+ var BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS = [
6375
+ "data",
6376
+ "batch",
6377
+ "transaction",
6378
+ "onConflict",
6379
+ "filter",
6380
+ "fields",
6381
+ "joins",
6382
+ "sort",
6383
+ "limit",
6384
+ "offset",
6385
+ "queryMode",
6386
+ "aggregates",
6387
+ "groupBy"
6388
+ ];
6389
+ function isBootstrapDbOperationRoutineName(value) {
6390
+ return /^(Insert|Update|Query|Delete)\s+/.test(String(value ?? "").trim());
6391
+ }
6392
+ function compactAuthorityBootstrapRequestBody(ctx) {
6393
+ if (!isBootstrapDbOperationRoutineName(ctx.__remoteRoutineName)) {
6394
+ return ctx;
6395
+ }
6396
+ const queryData = ctx.queryData && typeof ctx.queryData === "object" ? { ...ctx.queryData } : null;
6397
+ if (!queryData) {
6398
+ return ctx;
6399
+ }
6400
+ const compacted = {
6401
+ ...ctx,
6402
+ queryData
6403
+ };
6404
+ for (const key of BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS) {
6405
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
6406
+ delete compacted[key];
6407
+ }
6408
+ }
6409
+ return compacted;
6410
+ }
5780
6411
  function cloneServiceRegistryContextValue(value) {
5781
6412
  if (value instanceof Date) {
5782
6413
  return new Date(value.getTime());
@@ -6133,6 +6764,92 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
6133
6764
  `Resolve service registry insert for ${tableName}`,
6134
6765
  (ctx, emit2) => new Promise((resolve) => {
6135
6766
  const resolverRequestId = (0, import_uuid3.v4)();
6767
+ const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
6768
+ const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
6769
+ const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
6770
+ const selfBootstrapRetrySignal = CadenzaService.serviceRegistry.serviceName === "CadenzaDB" && resolvedTargetServiceName === "CadenzaDB" && !localInsertTask ? getSelfBootstrapRegistrationRetrySignal(tableName) : null;
6771
+ if (selfBootstrapRetrySignal) {
6772
+ CadenzaService.schedule(
6773
+ selfBootstrapRetrySignal,
6774
+ {
6775
+ ...ctx
6776
+ },
6777
+ 250
6778
+ );
6779
+ resolve(false);
6780
+ return;
6781
+ }
6782
+ if (bootstrapAuthorityInsertSpec) {
6783
+ const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
6784
+ const nextQueryData = buildServiceRegistryInsertQueryData(
6785
+ tableName,
6786
+ sanitizedContext,
6787
+ queryData
6788
+ );
6789
+ const inquiryContext = ensureDelegationContextMetadata({
6790
+ ...sanitizedContext,
6791
+ data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
6792
+ batch: nextQueryData.batch !== void 0 ? nextQueryData.batch : sanitizedContext.batch,
6793
+ onConflict: Object.prototype.hasOwnProperty.call(nextQueryData, "onConflict") ? nextQueryData.onConflict : void 0,
6794
+ transaction: nextQueryData.transaction !== void 0 ? nextQueryData.transaction : sanitizedContext.transaction,
6795
+ queryData: nextQueryData
6796
+ });
6797
+ inquiryContext.__metadata = {
6798
+ ...inquiryContext.__metadata ?? {},
6799
+ __skipRemoteExecution: inquiryContext.__metadata?.__skipRemoteExecution ?? inquiryContext.__skipRemoteExecution ?? false,
6800
+ __blockRemoteExecution: inquiryContext.__metadata?.__blockRemoteExecution ?? inquiryContext.__blockRemoteExecution ?? false
6801
+ };
6802
+ CadenzaService.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
6803
+ bootstrapAuthorityInsertSpec.intentName,
6804
+ inquiryContext
6805
+ );
6806
+ void CadenzaService.inquire(
6807
+ bootstrapAuthorityInsertSpec.intentName,
6808
+ inquiryContext,
6809
+ {
6810
+ requireComplete: true,
6811
+ timeout: bootstrapAuthorityInsertSpec.defaultTimeoutMs
6812
+ }
6813
+ ).then(
6814
+ (result) => resolve(
6815
+ resolveBootstrapAuthorityInsertResult(
6816
+ tableName,
6817
+ sanitizedContext,
6818
+ nextQueryData,
6819
+ result,
6820
+ emit2
6821
+ )
6822
+ )
6823
+ ).catch(
6824
+ (error) => resolve(
6825
+ resolveBootstrapAuthorityInsertResult(
6826
+ tableName,
6827
+ sanitizedContext,
6828
+ nextQueryData,
6829
+ error,
6830
+ emit2
6831
+ )
6832
+ )
6833
+ );
6834
+ return;
6835
+ }
6836
+ const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
6837
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6838
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
6839
+ tableName,
6840
+ executionSignal,
6841
+ hasLocalInsertTask: !!localInsertTask,
6842
+ serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
6843
+ serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
6844
+ hasData: !!ctx.data,
6845
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
6846
+ registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
6847
+ });
6848
+ }
6849
+ if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
6850
+ wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
6851
+ wiredLocalTaskNames.add(localInsertTask.name);
6852
+ }
6136
6853
  CadenzaService.createEphemeralMetaTask(
6137
6854
  `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
6138
6855
  (resultCtx) => {
@@ -6232,95 +6949,11 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
6232
6949
  },
6233
6950
  `Resolves signal-driven ${tableName} service-registry insert execution.`,
6234
6951
  {
6235
- register: false
6952
+ register: false,
6953
+ once: false,
6954
+ destroyCondition: (result) => result !== false
6236
6955
  }
6237
6956
  ).doOn(executionResolvedSignal, executionFailedSignal);
6238
- const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
6239
- const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
6240
- const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
6241
- const selfBootstrapRetrySignal = CadenzaService.serviceRegistry.serviceName === "CadenzaDB" && resolvedTargetServiceName === "CadenzaDB" && !localInsertTask ? getSelfBootstrapRegistrationRetrySignal(tableName) : null;
6242
- if (selfBootstrapRetrySignal) {
6243
- CadenzaService.schedule(
6244
- selfBootstrapRetrySignal,
6245
- {
6246
- ...ctx
6247
- },
6248
- 250
6249
- );
6250
- resolve(false);
6251
- return;
6252
- }
6253
- if (bootstrapAuthorityInsertSpec) {
6254
- const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
6255
- const nextQueryData = buildServiceRegistryInsertQueryData(
6256
- tableName,
6257
- sanitizedContext,
6258
- queryData
6259
- );
6260
- const inquiryContext = ensureDelegationContextMetadata({
6261
- ...sanitizedContext,
6262
- data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
6263
- batch: nextQueryData.batch !== void 0 ? nextQueryData.batch : sanitizedContext.batch,
6264
- onConflict: Object.prototype.hasOwnProperty.call(nextQueryData, "onConflict") ? nextQueryData.onConflict : void 0,
6265
- transaction: nextQueryData.transaction !== void 0 ? nextQueryData.transaction : sanitizedContext.transaction,
6266
- queryData: nextQueryData
6267
- });
6268
- inquiryContext.__metadata = {
6269
- ...inquiryContext.__metadata ?? {},
6270
- __skipRemoteExecution: inquiryContext.__metadata?.__skipRemoteExecution ?? inquiryContext.__skipRemoteExecution ?? false,
6271
- __blockRemoteExecution: inquiryContext.__metadata?.__blockRemoteExecution ?? inquiryContext.__blockRemoteExecution ?? false
6272
- };
6273
- CadenzaService.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
6274
- bootstrapAuthorityInsertSpec.intentName,
6275
- inquiryContext
6276
- );
6277
- void CadenzaService.inquire(
6278
- bootstrapAuthorityInsertSpec.intentName,
6279
- inquiryContext,
6280
- {
6281
- requireComplete: true,
6282
- timeout: bootstrapAuthorityInsertSpec.defaultTimeoutMs
6283
- }
6284
- ).then(
6285
- (result) => resolve(
6286
- resolveBootstrapAuthorityInsertResult(
6287
- tableName,
6288
- sanitizedContext,
6289
- nextQueryData,
6290
- result,
6291
- emit2
6292
- )
6293
- )
6294
- ).catch(
6295
- (error) => resolve(
6296
- resolveBootstrapAuthorityInsertResult(
6297
- tableName,
6298
- sanitizedContext,
6299
- nextQueryData,
6300
- error,
6301
- emit2
6302
- )
6303
- )
6304
- );
6305
- return;
6306
- }
6307
- const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
6308
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6309
- console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
6310
- tableName,
6311
- executionSignal,
6312
- hasLocalInsertTask: !!localInsertTask,
6313
- serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
6314
- serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
6315
- hasData: !!ctx.data,
6316
- dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
6317
- registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
6318
- });
6319
- }
6320
- if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
6321
- wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
6322
- wiredLocalTaskNames.add(localInsertTask.name);
6323
- }
6324
6957
  emit2(executionSignal, {
6325
6958
  ...ctx,
6326
6959
  __resolverRequestId: resolverRequestId
@@ -6345,6 +6978,17 @@ function readPositiveIntegerEnv(name, fallback) {
6345
6978
  }
6346
6979
  return normalized;
6347
6980
  }
6981
+ function readNonNegativeFloatEnv(name, fallback) {
6982
+ if (typeof process === "undefined") {
6983
+ return fallback;
6984
+ }
6985
+ const raw = process.env?.[name];
6986
+ const parsed = Number(raw);
6987
+ if (!Number.isFinite(parsed) || parsed < 0) {
6988
+ return fallback;
6989
+ }
6990
+ return parsed;
6991
+ }
6348
6992
  var ServiceRegistry = class _ServiceRegistry {
6349
6993
  /**
6350
6994
  * Initializes a private constructor for managing service instances, remote signals,
@@ -6394,6 +7038,9 @@ var ServiceRegistry = class _ServiceRegistry {
6394
7038
  "CADENZA_RUNTIME_STATUS_REST_REFRESH_MS",
6395
7039
  this.runtimeMetricsSampleIntervalMs
6396
7040
  );
7041
+ this.runtimeStatusLoopJitterRatio = normalizeJitterRatio(
7042
+ readNonNegativeFloatEnv("CADENZA_RUNTIME_STATUS_JITTER_RATIO", 0.2)
7043
+ );
6397
7044
  this.runtimeStatusMissThreshold = readPositiveIntegerEnv(
6398
7045
  "CADENZA_RUNTIME_STATUS_MISSED_HEARTBEATS",
6399
7046
  3
@@ -6442,6 +7089,18 @@ var ServiceRegistry = class _ServiceRegistry {
6442
7089
  "CADENZA_RUNTIME_STATUS_OVERLOADED_GRAPH_THRESHOLD",
6443
7090
  20
6444
7091
  );
7092
+ this.bootstrapFullSyncRetryJitterRatio = normalizeJitterRatio(
7093
+ readNonNegativeFloatEnv(
7094
+ "CADENZA_BOOTSTRAP_FULL_SYNC_RETRY_JITTER_RATIO",
7095
+ 0.2
7096
+ )
7097
+ );
7098
+ this.serviceCommunicationRetryJitterRatio = normalizeJitterRatio(
7099
+ readNonNegativeFloatEnv(
7100
+ "CADENZA_SERVICE_COMMUNICATION_RETRY_JITTER_RATIO",
7101
+ 0.2
7102
+ )
7103
+ );
6445
7104
  this.serviceName = null;
6446
7105
  this.serviceInstanceId = null;
6447
7106
  this.numberOfRunningGraphs = 0;
@@ -7420,6 +8079,12 @@ var ServiceRegistry = class _ServiceRegistry {
7420
8079
  const tasks = this.readArrayPayload(inquiryResult, [
7421
8080
  "tasks"
7422
8081
  ]);
8082
+ const helpers = this.readArrayPayload(inquiryResult, [
8083
+ "helpers"
8084
+ ]);
8085
+ const globals = this.readArrayPayload(inquiryResult, [
8086
+ "globals"
8087
+ ]);
7423
8088
  const signals = this.readArrayPayload(inquiryResult, [
7424
8089
  "signals"
7425
8090
  ]);
@@ -7444,6 +8109,22 @@ var ServiceRegistry = class _ServiceRegistry {
7444
8109
  inquiryResult,
7445
8110
  ["taskToRoutineMaps", "task_to_routine_maps"]
7446
8111
  );
8112
+ const taskToHelperMaps = this.readArrayPayload(
8113
+ inquiryResult,
8114
+ ["taskToHelperMaps", "task_to_helper_maps"]
8115
+ );
8116
+ const helperToHelperMaps = this.readArrayPayload(
8117
+ inquiryResult,
8118
+ ["helperToHelperMaps", "helper_to_helper_maps"]
8119
+ );
8120
+ const taskToGlobalMaps = this.readArrayPayload(
8121
+ inquiryResult,
8122
+ ["taskToGlobalMaps", "task_to_global_maps"]
8123
+ );
8124
+ const helperToGlobalMaps = this.readArrayPayload(
8125
+ inquiryResult,
8126
+ ["helperToGlobalMaps", "helper_to_global_maps"]
8127
+ );
7447
8128
  const serviceInstances = this.normalizeServiceInstancesFromSync(
7448
8129
  inquiryResult
7449
8130
  );
@@ -7477,6 +8158,8 @@ var ServiceRegistry = class _ServiceRegistry {
7477
8158
  serviceInstanceTransports: serviceInstanceTransports.length,
7478
8159
  serviceManifests: serviceManifests.length,
7479
8160
  tasks: tasks.length,
8161
+ helpers: helpers.length,
8162
+ globals: globals.length,
7480
8163
  signals: signals.length,
7481
8164
  intents: intents.length,
7482
8165
  actors: actors.length,
@@ -7502,6 +8185,8 @@ var ServiceRegistry = class _ServiceRegistry {
7502
8185
  serviceInstanceTransports,
7503
8186
  serviceManifests,
7504
8187
  tasks,
8188
+ helpers,
8189
+ globals,
7505
8190
  signals,
7506
8191
  intents,
7507
8192
  actors,
@@ -7509,6 +8194,10 @@ var ServiceRegistry = class _ServiceRegistry {
7509
8194
  directionalTaskMaps,
7510
8195
  actorTaskMaps,
7511
8196
  taskToRoutineMaps,
8197
+ taskToHelperMaps,
8198
+ helperToHelperMaps,
8199
+ taskToGlobalMaps,
8200
+ helperToGlobalMaps,
7512
8201
  __inquiryMeta: inquiryResult.__inquiryMeta
7513
8202
  };
7514
8203
  },
@@ -8128,29 +8817,51 @@ var ServiceRegistry = class _ServiceRegistry {
8128
8817
  this.runtimeStatusHeartbeatStarted = true;
8129
8818
  if (!this.runtimeMetricsSamplingStarted) {
8130
8819
  this.runtimeMetricsSamplingStarted = true;
8820
+ CadenzaService.emit(META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL, {});
8131
8821
  CadenzaService.interval(
8132
8822
  META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL,
8133
8823
  {},
8134
8824
  this.runtimeMetricsSampleIntervalMs,
8135
- true
8825
+ false,
8826
+ this.buildJitteredIntervalStartDate(
8827
+ this.runtimeMetricsSampleIntervalMs,
8828
+ "runtime-metrics-sample"
8829
+ )
8136
8830
  );
8137
8831
  }
8832
+ CadenzaService.emit(META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL, {
8833
+ reason: "heartbeat"
8834
+ });
8138
8835
  CadenzaService.interval(
8139
8836
  META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL,
8140
8837
  { reason: "heartbeat" },
8141
8838
  this.runtimeStatusHeartbeatIntervalMs,
8142
- true
8839
+ false,
8840
+ this.buildJitteredIntervalStartDate(
8841
+ this.runtimeStatusHeartbeatIntervalMs,
8842
+ "runtime-status-heartbeat"
8843
+ )
8143
8844
  );
8144
8845
  CadenzaService.interval(
8145
8846
  META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL,
8146
8847
  {},
8147
- this.runtimeStatusHeartbeatIntervalMs
8848
+ this.runtimeStatusHeartbeatIntervalMs,
8849
+ false,
8850
+ this.buildJitteredIntervalStartDate(
8851
+ this.runtimeStatusHeartbeatIntervalMs,
8852
+ "runtime-status-monitor"
8853
+ )
8148
8854
  );
8855
+ CadenzaService.emit(META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL, {});
8149
8856
  CadenzaService.interval(
8150
8857
  META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL,
8151
8858
  {},
8152
8859
  this.runtimeStatusRestRefreshIntervalMs,
8153
- true
8860
+ false,
8861
+ this.buildJitteredIntervalStartDate(
8862
+ this.runtimeStatusRestRefreshIntervalMs,
8863
+ "runtime-status-rest-refresh"
8864
+ )
8154
8865
  );
8155
8866
  return true;
8156
8867
  },
@@ -9155,11 +9866,14 @@ var ServiceRegistry = class _ServiceRegistry {
9155
9866
  }
9156
9867
  collectBootstrapFullSyncPayload(ctx) {
9157
9868
  const serviceInstances = [];
9869
+ const serviceInstanceLeases = [];
9158
9870
  const serviceInstanceTransports = [];
9159
9871
  const manifestSnapshots = [];
9160
9872
  const signalToTaskMaps = [];
9161
9873
  const intentToTaskMaps = [];
9162
9874
  const tasks = [];
9875
+ const helpers = [];
9876
+ const globals = [];
9163
9877
  const signals = [];
9164
9878
  const intents = [];
9165
9879
  const actors = [];
@@ -9167,11 +9881,18 @@ var ServiceRegistry = class _ServiceRegistry {
9167
9881
  const directionalTaskMaps = [];
9168
9882
  const actorTaskMaps = [];
9169
9883
  const taskToRoutineMaps = [];
9884
+ const taskToHelperMaps = [];
9885
+ const helperToHelperMaps = [];
9886
+ const taskToGlobalMaps = [];
9887
+ const helperToGlobalMaps = [];
9170
9888
  const seenServiceInstances = /* @__PURE__ */ new Set();
9889
+ const seenServiceInstanceLeases = /* @__PURE__ */ new Set();
9171
9890
  const seenServiceInstanceTransports = /* @__PURE__ */ new Set();
9172
9891
  const seenSignalMaps = /* @__PURE__ */ new Set();
9173
9892
  const seenIntentMaps = /* @__PURE__ */ new Set();
9174
9893
  const seenTasks = /* @__PURE__ */ new Set();
9894
+ const seenHelpers = /* @__PURE__ */ new Set();
9895
+ const seenGlobals = /* @__PURE__ */ new Set();
9175
9896
  const seenSignals = /* @__PURE__ */ new Set();
9176
9897
  const seenIntents = /* @__PURE__ */ new Set();
9177
9898
  const seenActors = /* @__PURE__ */ new Set();
@@ -9179,6 +9900,10 @@ var ServiceRegistry = class _ServiceRegistry {
9179
9900
  const seenDirectionalTaskMaps = /* @__PURE__ */ new Set();
9180
9901
  const seenActorTaskMaps = /* @__PURE__ */ new Set();
9181
9902
  const seenTaskToRoutineMaps = /* @__PURE__ */ new Set();
9903
+ const seenTaskToHelperMaps = /* @__PURE__ */ new Set();
9904
+ const seenHelperToHelperMaps = /* @__PURE__ */ new Set();
9905
+ const seenTaskToGlobalMaps = /* @__PURE__ */ new Set();
9906
+ const seenHelperToGlobalMaps = /* @__PURE__ */ new Set();
9182
9907
  const contexts = Array.isArray(ctx.joinedContexts) ? [ctx, ...ctx.joinedContexts] : [ctx];
9183
9908
  const pushUnique = (rows, target, seen, keyResolver) => {
9184
9909
  for (const row of rows) {
@@ -9209,6 +9934,12 @@ var ServiceRegistry = class _ServiceRegistry {
9209
9934
  "serviceInstance",
9210
9935
  "service_instance"
9211
9936
  ]);
9937
+ const serviceInstanceLeaseRows = readDirectArrayPayload(candidate, [
9938
+ "serviceInstanceLeases",
9939
+ "service_instance_leases",
9940
+ "serviceInstanceLease",
9941
+ "service_instance_lease"
9942
+ ]);
9212
9943
  const serviceInstanceTransportRows = readDirectArrayPayload(candidate, [
9213
9944
  "serviceInstanceTransports",
9214
9945
  "service_instance_transports",
@@ -9239,6 +9970,12 @@ var ServiceRegistry = class _ServiceRegistry {
9239
9970
  seenServiceInstances,
9240
9971
  (row) => String(row.uuid ?? "").trim()
9241
9972
  );
9973
+ pushUnique(
9974
+ serviceInstanceLeaseRows,
9975
+ serviceInstanceLeases,
9976
+ seenServiceInstanceLeases,
9977
+ (row) => String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
9978
+ );
9242
9979
  pushUnique(
9243
9980
  serviceInstanceTransportRows,
9244
9981
  serviceInstanceTransports,
@@ -9301,6 +10038,17 @@ var ServiceRegistry = class _ServiceRegistry {
9301
10038
  );
9302
10039
  continue;
9303
10040
  }
10041
+ if (row.status !== void 0 && (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0)) {
10042
+ pushUnique(
10043
+ [row],
10044
+ serviceInstanceLeases,
10045
+ seenServiceInstanceLeases,
10046
+ (entry) => String(
10047
+ entry.service_instance_id ?? entry.serviceInstanceId ?? ""
10048
+ ).trim()
10049
+ );
10050
+ continue;
10051
+ }
9304
10052
  if (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0) {
9305
10053
  pushUnique(
9306
10054
  [row],
@@ -9329,12 +10077,16 @@ var ServiceRegistry = class _ServiceRegistry {
9329
10077
  }
9330
10078
  }
9331
10079
  }
10080
+ const mergedServiceInstances = overlayServiceInstancesWithLeases(
10081
+ serviceInstances,
10082
+ serviceInstanceLeases
10083
+ );
9332
10084
  const activeServiceInstanceIds = new Set(
9333
- serviceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
10085
+ mergedServiceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
9334
10086
  );
9335
- const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? serviceInstances.filter(
10087
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? mergedServiceInstances.filter(
9336
10088
  (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
9337
- ) : serviceInstances;
10089
+ ) : mergedServiceInstances;
9338
10090
  const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
9339
10091
  (row) => activeServiceInstanceIds.has(
9340
10092
  String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
@@ -9378,6 +10130,22 @@ var ServiceRegistry = class _ServiceRegistry {
9378
10130
  row.version ?? 1
9379
10131
  ).trim()}`
9380
10132
  );
10133
+ pushUnique(
10134
+ explodedManifest.helpers,
10135
+ helpers,
10136
+ seenHelpers,
10137
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10138
+ row.version ?? 1
10139
+ ).trim()}`
10140
+ );
10141
+ pushUnique(
10142
+ explodedManifest.globals,
10143
+ globals,
10144
+ seenGlobals,
10145
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10146
+ row.version ?? 1
10147
+ ).trim()}`
10148
+ );
9381
10149
  pushUnique(
9382
10150
  explodedManifest.signals,
9383
10151
  signals,
@@ -9438,6 +10206,50 @@ var ServiceRegistry = class _ServiceRegistry {
9438
10206
  row.task_version ?? 1
9439
10207
  ).trim()}`
9440
10208
  );
10209
+ pushUnique(
10210
+ explodedManifest.taskToHelperMaps,
10211
+ taskToHelperMaps,
10212
+ seenTaskToHelperMaps,
10213
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10214
+ row.task_version ?? 1
10215
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10216
+ row.helper_name ?? ""
10217
+ ).trim()}|${String(row.helper_version ?? 1).trim()}`
10218
+ );
10219
+ pushUnique(
10220
+ explodedManifest.helperToHelperMaps,
10221
+ helperToHelperMaps,
10222
+ seenHelperToHelperMaps,
10223
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10224
+ row.helper_name ?? ""
10225
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10226
+ row.alias ?? ""
10227
+ ).trim()}|${String(row.dependency_helper_name ?? "").trim()}|${String(
10228
+ row.dependency_helper_version ?? 1
10229
+ ).trim()}`
10230
+ );
10231
+ pushUnique(
10232
+ explodedManifest.taskToGlobalMaps,
10233
+ taskToGlobalMaps,
10234
+ seenTaskToGlobalMaps,
10235
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10236
+ row.task_version ?? 1
10237
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10238
+ row.global_name ?? ""
10239
+ ).trim()}|${String(row.global_version ?? 1).trim()}`
10240
+ );
10241
+ pushUnique(
10242
+ explodedManifest.helperToGlobalMaps,
10243
+ helperToGlobalMaps,
10244
+ seenHelperToGlobalMaps,
10245
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10246
+ row.helper_name ?? ""
10247
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10248
+ row.alias ?? ""
10249
+ ).trim()}|${String(row.global_name ?? "").trim()}|${String(
10250
+ row.global_version ?? 1
10251
+ ).trim()}`
10252
+ );
9441
10253
  if (!hasExplicitSignalRoutingRows) {
9442
10254
  pushUnique(
9443
10255
  explodedManifest.signalToTaskMaps,
@@ -9464,9 +10276,12 @@ var ServiceRegistry = class _ServiceRegistry {
9464
10276
  }
9465
10277
  return {
9466
10278
  serviceInstances: filteredServiceInstances,
10279
+ serviceInstanceLeases,
9467
10280
  serviceInstanceTransports: filteredServiceInstanceTransports,
9468
10281
  serviceManifests,
9469
10282
  tasks,
10283
+ helpers,
10284
+ globals,
9470
10285
  signals,
9471
10286
  intents,
9472
10287
  actors,
@@ -9474,6 +10289,10 @@ var ServiceRegistry = class _ServiceRegistry {
9474
10289
  directionalTaskMaps,
9475
10290
  actorTaskMaps,
9476
10291
  taskToRoutineMaps,
10292
+ taskToHelperMaps,
10293
+ helperToHelperMaps,
10294
+ taskToGlobalMaps,
10295
+ helperToGlobalMaps,
9477
10296
  signalToTaskMaps: filteredSignalToTaskMaps,
9478
10297
  intentToTaskMaps: filteredIntentToTaskMaps
9479
10298
  };
@@ -9899,35 +10718,37 @@ var ServiceRegistry = class _ServiceRegistry {
9899
10718
  ...context,
9900
10719
  __error: "Authority bootstrap route is not established yet. Waiting for authority handshake.",
9901
10720
  errored: true
9902
- };
9903
- }
9904
- const controller = typeof AbortController === "function" ? new AbortController() : null;
9905
- const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
9906
- try {
9907
- const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
9908
- const requestBody = stripDelegationRequestSnapshot(
9909
- ensureDelegationContextMetadata(
9910
- attachDelegationRequestSnapshot({
9911
- ...sanitizedContext,
9912
- __remoteRoutineName: remoteRoutineName,
9913
- __serviceName: "CadenzaDB",
9914
- __localServiceName: this.serviceName,
9915
- __timeout: timeoutMs,
9916
- __syncing: true,
9917
- __transportOrigin: target.origin,
9918
- __transportProtocol: "rest",
9919
- __transportProtocols: ["rest"],
9920
- __routeKey: target.routeKey,
9921
- routeKey: target.routeKey,
9922
- __fetchId: target.fetchId,
9923
- fetchId: target.fetchId,
9924
- __metadata: {
9925
- ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
10721
+ };
10722
+ }
10723
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
10724
+ const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
10725
+ try {
10726
+ const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
10727
+ const requestBody = compactAuthorityBootstrapRequestBody(
10728
+ stripDelegationRequestSnapshot(
10729
+ ensureDelegationContextMetadata(
10730
+ attachDelegationRequestSnapshot({
10731
+ ...sanitizedContext,
10732
+ __remoteRoutineName: remoteRoutineName,
10733
+ __serviceName: "CadenzaDB",
10734
+ __localServiceName: this.serviceName,
9926
10735
  __timeout: timeoutMs,
9927
10736
  __syncing: true,
9928
- __authorityBootstrapChannel: true
9929
- }
9930
- })
10737
+ __transportOrigin: target.origin,
10738
+ __transportProtocol: "rest",
10739
+ __transportProtocols: ["rest"],
10740
+ __routeKey: target.routeKey,
10741
+ routeKey: target.routeKey,
10742
+ __fetchId: target.fetchId,
10743
+ fetchId: target.fetchId,
10744
+ __metadata: {
10745
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
10746
+ __timeout: timeoutMs,
10747
+ __syncing: true,
10748
+ __authorityBootstrapChannel: true
10749
+ }
10750
+ })
10751
+ )
9931
10752
  )
9932
10753
  );
9933
10754
  const response = await globalThis.fetch(`${target.origin}/delegation`, {
@@ -10082,12 +10903,14 @@ var ServiceRegistry = class _ServiceRegistry {
10082
10903
  };
10083
10904
  const [
10084
10905
  serviceInstances,
10906
+ serviceInstanceLeases,
10085
10907
  serviceInstanceTransports,
10086
10908
  serviceManifests,
10087
10909
  signalToTaskMaps,
10088
10910
  intentToTaskMaps
10089
10911
  ] = await Promise.all([
10090
10912
  DatabaseController.instance.queryAuthorityTableRows("service_instance"),
10913
+ queryOptionalAuthorityRoutingRows("service_instance_lease"),
10091
10914
  DatabaseController.instance.queryAuthorityTableRows(
10092
10915
  "service_instance_transport"
10093
10916
  ),
@@ -10100,6 +10923,7 @@ var ServiceRegistry = class _ServiceRegistry {
10100
10923
  __syncing: true,
10101
10924
  ...this.collectBootstrapFullSyncPayload({
10102
10925
  serviceInstances,
10926
+ serviceInstanceLeases,
10103
10927
  serviceInstanceTransports,
10104
10928
  serviceManifests,
10105
10929
  signalToTaskMaps,
@@ -10132,9 +10956,14 @@ var ServiceRegistry = class _ServiceRegistry {
10132
10956
  return false;
10133
10957
  }
10134
10958
  const scheduleRetry = (reason, error) => {
10135
- const delayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
10959
+ const baseDelayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
10136
10960
  const nextAttempt = descriptor.retryAttempt + 1;
10137
- if (delayMs !== void 0) {
10961
+ if (baseDelayMs !== void 0) {
10962
+ const delayMs = buildDeterministicJitteredDelayMs(
10963
+ baseDelayMs,
10964
+ this.serviceCommunicationRetryJitterRatio,
10965
+ `${descriptor.serviceInstanceId}:${descriptor.communicationType}:${descriptor.retryAttempt}`
10966
+ );
10138
10967
  CadenzaService.schedule(
10139
10968
  retrySignal,
10140
10969
  buildServiceCommunicationRetryContext({
@@ -10282,6 +11111,31 @@ var ServiceRegistry = class _ServiceRegistry {
10282
11111
  })
10283
11112
  );
10284
11113
  }
11114
+ buildDeterministicInstanceJitterKey(scope) {
11115
+ const serviceName = String(this.serviceName ?? "").trim() || "unknown-service";
11116
+ const serviceInstanceId = String(this.serviceInstanceId ?? "").trim() || "pending-instance";
11117
+ return `${serviceName}:${serviceInstanceId}:${scope}`;
11118
+ }
11119
+ buildJitteredIntervalStartDate(intervalMs, scope) {
11120
+ const jitterOffsetMs = buildDeterministicJitterOffsetMs(
11121
+ intervalMs,
11122
+ this.runtimeStatusLoopJitterRatio,
11123
+ this.buildDeterministicInstanceJitterKey(scope)
11124
+ );
11125
+ if (jitterOffsetMs <= 0) {
11126
+ return void 0;
11127
+ }
11128
+ return new Date(Date.now() + intervalMs + jitterOffsetMs);
11129
+ }
11130
+ buildJitteredBootstrapRetryDelayMs(baseDelayMs, attempt) {
11131
+ return buildDeterministicJitteredDelayMs(
11132
+ baseDelayMs,
11133
+ this.bootstrapFullSyncRetryJitterRatio,
11134
+ this.buildDeterministicInstanceJitterKey(
11135
+ `bootstrap-full-sync-retry-${attempt}`
11136
+ )
11137
+ );
11138
+ }
10285
11139
  ensureAuthorityBootstrapSignalTransmissions() {
10286
11140
  if (this.serviceName !== "CadenzaDB") {
10287
11141
  return false;
@@ -10359,8 +11213,11 @@ var ServiceRegistry = class _ServiceRegistry {
10359
11213
  }
10360
11214
  const retryGeneration = this.bootstrapFullSyncRetryGeneration;
10361
11215
  const retryReason = this.bootstrapFullSyncRetryReason ?? "service_registry_bootstrap_retry";
10362
- const delayMs = EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex];
10363
11216
  const attempt = this.bootstrapFullSyncRetryIndex + 1;
11217
+ const delayMs = this.buildJitteredBootstrapRetryDelayMs(
11218
+ EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex],
11219
+ attempt
11220
+ );
10364
11221
  this.bootstrapFullSyncRetryIndex += 1;
10365
11222
  this.bootstrapFullSyncRetryTimer = setTimeout(() => {
10366
11223
  this.bootstrapFullSyncRetryTimer = null;
@@ -12263,6 +13120,18 @@ var ServiceRegistry = class _ServiceRegistry {
12263
13120
  isNonResponsive,
12264
13121
  isBlocked
12265
13122
  );
13123
+ const cpuUsage = this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad");
13124
+ const memoryUsage = this.readRuntimeStatusMetric(
13125
+ ctx,
13126
+ "memoryUsage",
13127
+ "memory",
13128
+ "memoryPressure"
13129
+ );
13130
+ const eventLoopLag = this.readRuntimeStatusMetric(
13131
+ ctx,
13132
+ "eventLoopLag",
13133
+ "eventLoopLagMs"
13134
+ );
12266
13135
  return {
12267
13136
  serviceName,
12268
13137
  serviceInstanceId,
@@ -12275,22 +13144,20 @@ var ServiceRegistry = class _ServiceRegistry {
12275
13144
  state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
12276
13145
  acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
12277
13146
  numberOfRunningGraphs,
12278
- cpuUsage: this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad"),
12279
- memoryUsage: this.readRuntimeStatusMetric(
12280
- ctx,
12281
- "memoryUsage",
12282
- "memory",
12283
- "memoryPressure"
12284
- ),
12285
- eventLoopLag: this.readRuntimeStatusMetric(
12286
- ctx,
12287
- "eventLoopLag",
12288
- "eventLoopLagMs"
12289
- ),
13147
+ cpuUsage,
13148
+ memoryUsage,
13149
+ eventLoopLag,
12290
13150
  isActive,
12291
13151
  isNonResponsive,
12292
13152
  isBlocked,
12293
- health: ctx.health ?? ctx.__health ?? {}
13153
+ health: sanitizeAuthorityRuntimeStatusHealth(ctx.health ?? ctx.__health, {
13154
+ state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
13155
+ acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
13156
+ reportedAt: ctx.reportedAt ?? (typeof ctx.__reportedAt === "string" ? ctx.__reportedAt : void 0) ?? (/* @__PURE__ */ new Date()).toISOString(),
13157
+ cpuUsage,
13158
+ memoryUsage,
13159
+ eventLoopLag
13160
+ })
12294
13161
  };
12295
13162
  }
12296
13163
  applyRuntimeStatusReport(report) {
@@ -12331,12 +13198,14 @@ var ServiceRegistry = class _ServiceRegistry {
12331
13198
  instance.isFrontend = report.isFrontend;
12332
13199
  }
12333
13200
  instance.numberOfRunningGraphs = report.numberOfRunningGraphs;
12334
- const runtimeMetricsHealth = {
13201
+ const runtimeStatusHealth = sanitizeAuthorityRuntimeStatusHealth(report.health, {
13202
+ state: report.state,
13203
+ acceptingWork: report.acceptingWork,
13204
+ reportedAt: report.reportedAt,
12335
13205
  cpuUsage: report.cpuUsage ?? null,
12336
13206
  memoryUsage: report.memoryUsage ?? null,
12337
- eventLoopLag: report.eventLoopLag ?? null,
12338
- runtimeMetrics: report.health?.runtimeMetrics && typeof report.health.runtimeMetrics === "object" ? report.health.runtimeMetrics : void 0
12339
- };
13207
+ eventLoopLag: report.eventLoopLag ?? null
13208
+ });
12340
13209
  instance.isActive = report.isActive;
12341
13210
  instance.isNonResponsive = report.isNonResponsive;
12342
13211
  instance.isBlocked = report.isBlocked;
@@ -12345,13 +13214,7 @@ var ServiceRegistry = class _ServiceRegistry {
12345
13214
  instance.reportedAt = report.reportedAt;
12346
13215
  instance.health = {
12347
13216
  ...instance.health ?? {},
12348
- ...report.health ?? {},
12349
- ...runtimeMetricsHealth,
12350
- runtimeStatus: {
12351
- state: report.state,
12352
- acceptingWork: report.acceptingWork,
12353
- reportedAt: report.reportedAt
12354
- }
13217
+ ...runtimeStatusHealth ?? {}
12355
13218
  };
12356
13219
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
12357
13220
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -12523,15 +13386,20 @@ var ServiceRegistry = class _ServiceRegistry {
12523
13386
  isActive: snapshot.isActive,
12524
13387
  isNonResponsive: snapshot.isNonResponsive,
12525
13388
  isBlocked: snapshot.isBlocked,
12526
- health: {
12527
- ...localInstance.health ?? {},
12528
- ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {},
12529
- runtimeStatus: {
13389
+ health: sanitizeAuthorityRuntimeStatusHealth(
13390
+ {
13391
+ ...localInstance.health ?? {},
13392
+ ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {}
13393
+ },
13394
+ {
12530
13395
  state: snapshot.state,
12531
13396
  acceptingWork: snapshot.acceptingWork,
12532
- reportedAt
13397
+ reportedAt,
13398
+ cpuUsage: runtimeMetricsSnapshot?.cpuUsage ?? null,
13399
+ memoryUsage: runtimeMetricsSnapshot?.memoryUsage ?? null,
13400
+ eventLoopLag: runtimeMetricsSnapshot?.eventLoopLag ?? null
12533
13401
  }
12534
- }
13402
+ )
12535
13403
  };
12536
13404
  this.applyRuntimeStatusReport(report);
12537
13405
  return detailLevel === "full" ? report : this.stripRuntimeStatusReportForPeer(report);
@@ -12885,6 +13753,32 @@ var ServiceRegistry = class _ServiceRegistry {
12885
13753
  if (!instancePersisted) {
12886
13754
  return false;
12887
13755
  }
13756
+ await this.delegateAuthorityLifecycleUpdate(
13757
+ "Update service_instance_lease",
13758
+ {
13759
+ reason,
13760
+ graceful: true,
13761
+ data: {
13762
+ status: "inactive",
13763
+ is_ready: false,
13764
+ readiness_reason: "graceful_shutdown",
13765
+ lease_expires_at: reportedAt,
13766
+ last_lease_renewed_at: reportedAt,
13767
+ last_ready_at: null,
13768
+ last_observed_transport_at: reportedAt,
13769
+ shutdown_requested_at: reportedAt,
13770
+ deleted: false,
13771
+ modified: reportedAt
13772
+ },
13773
+ queryData: {
13774
+ filter: {
13775
+ service_instance_id: localInstance.uuid
13776
+ }
13777
+ },
13778
+ __serviceInstanceId: localInstance.uuid
13779
+ },
13780
+ Math.max(1e3, timeoutMs)
13781
+ );
12888
13782
  for (const transport of localInstance.transports) {
12889
13783
  if (!isPersistedUuid(transport.uuid)) {
12890
13784
  continue;
@@ -13036,6 +13930,7 @@ var ServiceRegistry = class _ServiceRegistry {
13036
13930
  };
13037
13931
  }
13038
13932
  reset() {
13933
+ this.clearBootstrapFullSyncRetryTimer();
13039
13934
  this.instances.clear();
13040
13935
  this.deputies.clear();
13041
13936
  this.remoteSignals.clear();
@@ -13059,6 +13954,23 @@ var ServiceRegistry = class _ServiceRegistry {
13059
13954
  this.lastRuntimeStatusSnapshot = null;
13060
13955
  this.isFrontend = false;
13061
13956
  this.localInstanceSeed = null;
13957
+ this.bootstrapFullSyncRetryIndex = 0;
13958
+ this.bootstrapFullSyncRetryGeneration = 0;
13959
+ this.bootstrapFullSyncSatisfied = false;
13960
+ this.bootstrapFullSyncRetryReason = null;
13961
+ this.knownGlobalSignalMaps.clear();
13962
+ this.authorityBootstrapRoute = {
13963
+ origin: null,
13964
+ role: "internal",
13965
+ routeKey: null,
13966
+ fetchId: null,
13967
+ serviceInstanceId: null,
13968
+ serviceTransportId: null,
13969
+ handshakeEstablished: false
13970
+ };
13971
+ this.authorityBootstrapHandshakeInFlight = false;
13972
+ this.authorityFullSyncResponderTask = null;
13973
+ this.authorityServiceCommunicationPersistenceTask = null;
13062
13974
  }
13063
13975
  };
13064
13976
 
@@ -13167,7 +14079,25 @@ var SignalTransmissionTask = class extends import_core3.Task {
13167
14079
  ...ctx
13168
14080
  })
13169
14081
  );
13170
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
14082
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
14083
+ this,
14084
+ deputyContext,
14085
+ emit2,
14086
+ inquire,
14087
+ progressCallback
14088
+ ) : {
14089
+ helpers: {},
14090
+ globals: {}
14091
+ };
14092
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
14093
+ };
14094
+ return this.taskFunction(
14095
+ deputyContext,
14096
+ emit2,
14097
+ inquire,
14098
+ resolvedTools,
14099
+ resolvedProgressCallback
14100
+ );
13171
14101
  }
13172
14102
  };
13173
14103
 
@@ -13496,16 +14426,16 @@ var RestController = class _RestController {
13496
14426
  };
13497
14427
  CadenzaService.createEphemeralMetaTask(
13498
14428
  "Resolve delegation",
13499
- (endCtx) => resolveDelegation(endCtx, "success"),
14429
+ (endCtx) => resolveDelegation(
14430
+ endCtx,
14431
+ endCtx?.errored || endCtx?.failed ? "error" : "success"
14432
+ ),
13500
14433
  "Resolves a delegation request",
13501
14434
  { register: false }
13502
- ).doOn(`meta.node.graph_completed:${deputyExecId}`).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
13503
- CadenzaService.createEphemeralMetaTask(
13504
- "Resolve delegation target lookup failure",
13505
- (endCtx) => resolveDelegation(endCtx, "error"),
13506
- "Resolves delegation requests that cannot find a local task or routine",
13507
- { register: false }
13508
- ).doOn(targetNotFoundSignal);
14435
+ ).doOn(
14436
+ `meta.node.graph_completed:${deputyExecId}`,
14437
+ targetNotFoundSignal
14438
+ ).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
13509
14439
  if (!CadenzaService.get(remoteRoutineName) && !CadenzaService.registry.routines.get(remoteRoutineName)) {
13510
14440
  CadenzaService.emit(targetNotFoundSignal, {
13511
14441
  ...ctx2,
@@ -16496,7 +17426,7 @@ var SignalController = class _SignalController {
16496
17426
  }
16497
17427
  const traceContext = { ...ctx };
16498
17428
  delete traceContext.__traceCreatedBySignalBroker;
16499
- const sanitizedTraceContext = stripLocalRoutinePersistenceHints(traceContext);
17429
+ const sanitizedTraceContext = sanitizeExecutionPersistenceContext(traceContext);
16500
17430
  const routineMetadata = resolveRoutinePersistenceMetadata(traceContext);
16501
17431
  const { context: routineContext, metaContext: routineMetaContext } = splitRoutinePersistenceContext(traceContext);
16502
17432
  const traceCreatedBySignalBroker = ctx.__traceCreatedBySignalBroker === true || signalEmission.__traceCreatedBySignalBroker === true;
@@ -17178,6 +18108,16 @@ function buildActorRegistrationData(actor) {
17178
18108
  version: 1
17179
18109
  };
17180
18110
  }
18111
+ function sanitizePersistedTaskSourceFields(task, data) {
18112
+ if (!task.isMeta && !task.isDeputy) {
18113
+ return data;
18114
+ }
18115
+ return {
18116
+ ...data,
18117
+ function_string: "",
18118
+ tag_id_getter: null
18119
+ };
18120
+ }
17181
18121
  function resolveSyncServiceName(task) {
17182
18122
  const ownerServiceName = typeof task?.ownerServiceName === "string" ? task.ownerServiceName.trim() : "";
17183
18123
  const taskServiceName = typeof task?.serviceName === "string" ? task.serviceName.trim() : "";
@@ -18295,40 +19235,41 @@ var GraphSyncController = class _GraphSyncController {
18295
19235
  if (task.registered) continue;
18296
19236
  const { __functionString, __getTagCallback } = task.export();
18297
19237
  this.tasksSynced = false;
19238
+ const taskRegistrationData = sanitizePersistedTaskSourceFields(task, {
19239
+ name: task.name,
19240
+ version: task.version,
19241
+ description: task.description,
19242
+ function_string: __functionString,
19243
+ tag_id_getter: __getTagCallback,
19244
+ layer_index: task.layerIndex,
19245
+ concurrency: task.concurrency,
19246
+ timeout: task.timeout,
19247
+ is_unique: task.isUnique,
19248
+ is_signal: task.isSignal,
19249
+ is_throttled: task.isThrottled,
19250
+ is_debounce: task.isDebounce,
19251
+ is_ephemeral: task.isEphemeral,
19252
+ is_meta: task.isMeta,
19253
+ is_sub_meta: task.isSubMeta,
19254
+ is_hidden: task.isHidden,
19255
+ validate_input_context: task.validateInputContext,
19256
+ validate_output_context: task.validateOutputContext,
19257
+ retry_count: task.retryCount,
19258
+ retry_delay: task.retryDelay,
19259
+ retry_delay_max: task.retryDelayMax,
19260
+ retry_delay_factor: task.retryDelayFactor,
19261
+ service_name: serviceName2,
19262
+ signals: {
19263
+ emits: Array.from(task.emitsSignals),
19264
+ signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
19265
+ signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
19266
+ observed: Array.from(task.observedSignals)
19267
+ },
19268
+ intents: Array.from(task.handlesIntents)
19269
+ });
18298
19270
  yield {
18299
19271
  __syncing: ctx.__syncing,
18300
- data: {
18301
- name: task.name,
18302
- version: task.version,
18303
- description: task.description,
18304
- function_string: __functionString,
18305
- tag_id_getter: __getTagCallback,
18306
- layer_index: task.layerIndex,
18307
- concurrency: task.concurrency,
18308
- timeout: task.timeout,
18309
- is_unique: task.isUnique,
18310
- is_signal: task.isSignal,
18311
- is_throttled: task.isThrottled,
18312
- is_debounce: task.isDebounce,
18313
- is_ephemeral: task.isEphemeral,
18314
- is_meta: task.isMeta,
18315
- is_sub_meta: task.isSubMeta,
18316
- is_hidden: task.isHidden,
18317
- validate_input_context: task.validateInputContext,
18318
- validate_output_context: task.validateOutputContext,
18319
- retry_count: task.retryCount,
18320
- retry_delay: task.retryDelay,
18321
- retry_delay_max: task.retryDelayMax,
18322
- retry_delay_factor: task.retryDelayFactor,
18323
- service_name: serviceName2,
18324
- signals: {
18325
- emits: Array.from(task.emitsSignals),
18326
- signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
18327
- signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
18328
- observed: Array.from(task.observedSignals)
18329
- },
18330
- intents: Array.from(task.handlesIntents)
18331
- },
19272
+ data: taskRegistrationData,
18332
19273
  __taskName: task.name
18333
19274
  };
18334
19275
  }
@@ -19487,13 +20428,50 @@ var GraphSyncController = class _GraphSyncController {
19487
20428
  startActorPrimitiveSyncTask,
19488
20429
  startRoutinePrimitiveSyncTask
19489
20430
  );
19490
- const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
20431
+ const getAllTasksForSyncTask = CadenzaService.createMetaTask(
20432
+ "Get all tasks for sync",
20433
+ (ctx) => ({
20434
+ ...ctx,
20435
+ tasks: Array.from(CadenzaService.registry.tasks.values())
20436
+ }),
20437
+ "Collects local tasks for the primitive sync phase.",
20438
+ {
20439
+ register: false,
20440
+ isHidden: true
20441
+ }
20442
+ );
19491
20443
  startTaskPrimitiveSyncTask.then(
19492
20444
  getAllTasksForSyncTask,
19493
20445
  gatherTaskRegistrationTask
19494
20446
  );
19495
20447
  getAllTasksForSyncTask.then(this.splitTasksForRegistration);
19496
- const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
20448
+ const getSignalsForSyncTask = CadenzaService.createMetaTask(
20449
+ "Get signals for sync",
20450
+ (ctx) => {
20451
+ const uniqueSignals = Array.from(
20452
+ /* @__PURE__ */ new Set([
20453
+ ...CadenzaService.signalBroker.signalObservers.keys(),
20454
+ ...CadenzaService.signalBroker.emittedSignalsRegistry
20455
+ ])
20456
+ ).filter((signal) => !signal.includes(":"));
20457
+ const processedSignals = uniqueSignals.map((signal) => ({
20458
+ signal,
20459
+ data: {
20460
+ registered: CadenzaService.signalBroker.signalObservers.get(signal)?.registered ?? false,
20461
+ metadata: CadenzaService.signalBroker.getSignalMetadata(signal) ?? null
20462
+ }
20463
+ }));
20464
+ return {
20465
+ ...ctx,
20466
+ signals: processedSignals
20467
+ };
20468
+ },
20469
+ "Collects local signals for the primitive sync phase.",
20470
+ {
20471
+ register: false,
20472
+ isHidden: true
20473
+ }
20474
+ );
19497
20475
  startSignalPrimitiveSyncTask.then(
19498
20476
  getSignalsForSyncTask,
19499
20477
  gatherSignalRegistrationTask
@@ -19535,40 +20513,110 @@ var GraphSyncController = class _GraphSyncController {
19535
20513
  gatherActorRegistrationTask
19536
20514
  );
19537
20515
  getAllActorsForSyncTask.then(this.splitActorsForRegistration);
19538
- const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
20516
+ const getAllRoutinesForSyncTask = CadenzaService.createMetaTask(
20517
+ "Get all routines for sync",
20518
+ (ctx) => ({
20519
+ ...ctx,
20520
+ routines: Array.from(CadenzaService.registry.routines.values())
20521
+ }),
20522
+ "Collects local routines for the primitive sync phase.",
20523
+ {
20524
+ register: false,
20525
+ isHidden: true
20526
+ }
20527
+ );
19539
20528
  startRoutinePrimitiveSyncTask.then(
19540
20529
  getAllRoutinesForSyncTask,
19541
20530
  gatherRoutineRegistrationTask
19542
20531
  );
19543
20532
  getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
19544
- const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20533
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
20534
+ "Iterate tasks for directional task map sync",
20535
+ function* (ctx) {
20536
+ for (const task of CadenzaService.registry.tasks.values()) {
20537
+ yield { ...ctx, task };
20538
+ }
20539
+ },
20540
+ "Iterates local tasks for directional task-map sync.",
20541
+ {
20542
+ register: false,
20543
+ isHidden: true
20544
+ }
20545
+ );
19545
20546
  startDirectionalTaskMapSyncTask.then(
19546
20547
  iterateTasksForDirectionalTaskMapSyncTask,
19547
20548
  gatherDirectionalTaskMapRegistrationTask
19548
20549
  );
19549
20550
  iterateTasksForDirectionalTaskMapSyncTask.then(this.registerTaskMapTask);
19550
20551
  recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
19551
- const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20552
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.createMetaTask(
20553
+ "Iterate tasks for signal task map sync",
20554
+ function* (ctx) {
20555
+ for (const task of CadenzaService.registry.tasks.values()) {
20556
+ yield { ...ctx, task };
20557
+ }
20558
+ },
20559
+ "Iterates local tasks for signal-to-task map sync.",
20560
+ {
20561
+ register: false,
20562
+ isHidden: true
20563
+ }
20564
+ );
19552
20565
  startSignalTaskMapSyncTask.then(
19553
20566
  iterateTasksForSignalTaskMapSyncTask,
19554
20567
  gatherSignalTaskMapRegistrationTask
19555
20568
  );
19556
20569
  iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
19557
20570
  this.registerSignalToTaskMapTask.then(gatherSignalTaskMapRegistrationTask);
19558
- const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20571
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.createMetaTask(
20572
+ "Iterate tasks for intent task map sync",
20573
+ function* (ctx) {
20574
+ for (const task of CadenzaService.registry.tasks.values()) {
20575
+ yield { ...ctx, task };
20576
+ }
20577
+ },
20578
+ "Iterates local tasks for intent-to-task map sync.",
20579
+ {
20580
+ register: false,
20581
+ isHidden: true
20582
+ }
20583
+ );
19559
20584
  startIntentTaskMapSyncTask.then(
19560
20585
  iterateTasksForIntentTaskMapSyncTask,
19561
20586
  gatherIntentTaskMapRegistrationTask
19562
20587
  );
19563
20588
  iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
19564
20589
  this.registerIntentToTaskMapTask.then(gatherIntentTaskMapRegistrationTask);
19565
- const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20590
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.createMetaTask(
20591
+ "Iterate tasks for actor task map sync",
20592
+ function* (ctx) {
20593
+ for (const task of CadenzaService.registry.tasks.values()) {
20594
+ yield { ...ctx, task };
20595
+ }
20596
+ },
20597
+ "Iterates local tasks for actor-to-task map sync.",
20598
+ {
20599
+ register: false,
20600
+ isHidden: true
20601
+ }
20602
+ );
19566
20603
  startActorTaskMapSyncTask.then(
19567
20604
  iterateTasksForActorTaskMapSyncTask,
19568
20605
  gatherActorTaskMapRegistrationTask
19569
20606
  );
19570
20607
  iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
19571
- const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
20608
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.createMetaTask(
20609
+ "Get all routines for task map sync",
20610
+ (ctx) => ({
20611
+ ...ctx,
20612
+ routines: Array.from(CadenzaService.registry.routines.values())
20613
+ }),
20614
+ "Collects local routines for routine-to-task map sync.",
20615
+ {
20616
+ register: false,
20617
+ isHidden: true
20618
+ }
20619
+ );
19572
20620
  startRoutineTaskMapSyncTask.then(
19573
20621
  getAllRoutinesForTaskMapSyncTask,
19574
20622
  gatherRoutineTaskMapRegistrationTask
@@ -19644,11 +20692,37 @@ function resolveTaskByName(name) {
19644
20692
  const taskName = String(name ?? "");
19645
20693
  return taskName ? CadenzaService.get(taskName) : void 0;
19646
20694
  }
20695
+ function resolveHelperFromMetadataContext(ctx) {
20696
+ const toolRuntime = CadenzaService;
20697
+ const helperName = String(
20698
+ ctx?.helperName ?? ctx?.data?.helperName ?? ctx?.data?.helper_name ?? ctx?.filter?.helperName ?? ctx?.filter?.helper_name ?? ""
20699
+ );
20700
+ return helperName ? toolRuntime.getHelper?.(helperName) : void 0;
20701
+ }
20702
+ function resolveGlobalFromMetadataContext(ctx) {
20703
+ const toolRuntime = CadenzaService;
20704
+ const globalName = String(
20705
+ ctx?.globalName ?? ctx?.data?.globalName ?? ctx?.data?.global_name ?? ctx?.filter?.globalName ?? ctx?.filter?.global_name ?? ""
20706
+ );
20707
+ return globalName ? toolRuntime.getGlobal?.(globalName) : void 0;
20708
+ }
19647
20709
  function resolvePredecessorTaskFromMetadataContext(ctx) {
19648
20710
  return resolveTaskByName(
19649
20711
  ctx?.predecessorTaskName ?? ctx?.data?.predecessorTaskName ?? ctx?.data?.predecessor_task_name ?? ctx?.filter?.predecessorTaskName ?? ctx?.filter?.predecessor_task_name
19650
20712
  );
19651
20713
  }
20714
+ function sanitizePersistedTaskSourceFields2(task, data) {
20715
+ if (!task?.isMeta && !task?.isDeputy) {
20716
+ return data;
20717
+ }
20718
+ return {
20719
+ ...data,
20720
+ functionString: "",
20721
+ function_string: "",
20722
+ tagIdGetter: null,
20723
+ tag_id_getter: null
20724
+ };
20725
+ }
19652
20726
  function shouldSkipDirectTaskMetadata(task) {
19653
20727
  return !task || !task.register || task.isHidden || task.isDeputy;
19654
20728
  }
@@ -19726,6 +20800,9 @@ function shouldPersistBusinessInquiryCompletion(ctx) {
19726
20800
  const inquiryName = String(ctx?.data?.metadata?.inquiryMeta?.inquiry ?? "");
19727
20801
  return inquiryName.length > 0 && !isMetaIntentName(inquiryName);
19728
20802
  }
20803
+ function shouldPersistExecutionTrace(ctx) {
20804
+ return ctx?.data?.isMeta !== true && ctx?.data?.is_meta !== true;
20805
+ }
19729
20806
  function shouldPersistRoutineExecution(ctx) {
19730
20807
  if (ctx?.data?.isMeta === true || ctx?.data?.is_meta === true) {
19731
20808
  return false;
@@ -19789,10 +20866,10 @@ var GraphMetadataController = class _GraphMetadataController {
19789
20866
  task.registrationRequested = true;
19790
20867
  }
19791
20868
  return buildDatabaseTriggerContext(
19792
- {
20869
+ sanitizePersistedTaskSourceFields2(task, {
19793
20870
  ...ctx.data,
19794
20871
  serviceName: CadenzaService.serviceRegistry.serviceName
19795
- },
20872
+ }),
19796
20873
  void 0,
19797
20874
  { onConflict },
19798
20875
  { onConflict }
@@ -19895,6 +20972,88 @@ var GraphMetadataController = class _GraphMetadataController {
19895
20972
  serviceName: CadenzaService.serviceRegistry.serviceName
19896
20973
  });
19897
20974
  }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
20975
+ const buildHelperMetadataContext = (ctx) => {
20976
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20977
+ return false;
20978
+ }
20979
+ const helper = resolveHelperFromMetadataContext(ctx);
20980
+ if (!helper) {
20981
+ return false;
20982
+ }
20983
+ return buildDatabaseTriggerContext({
20984
+ ...ctx.data,
20985
+ serviceName: CadenzaService.serviceRegistry.serviceName
20986
+ });
20987
+ };
20988
+ createLocalGraphMetadataTask("Handle helper creation", buildHelperMetadataContext).doOn("meta.helper.created").emits("global.meta.graph_metadata.helper_created");
20989
+ createLocalGraphMetadataTask("Handle helper update", buildHelperMetadataContext).doOn("meta.helper.updated").emits("global.meta.graph_metadata.helper_updated");
20990
+ const buildGlobalMetadataContext = (ctx) => {
20991
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20992
+ return false;
20993
+ }
20994
+ const globalDefinition = resolveGlobalFromMetadataContext(ctx);
20995
+ if (!globalDefinition) {
20996
+ return false;
20997
+ }
20998
+ return buildDatabaseTriggerContext({
20999
+ ...ctx.data,
21000
+ serviceName: CadenzaService.serviceRegistry.serviceName
21001
+ });
21002
+ };
21003
+ createLocalGraphMetadataTask("Handle global creation", buildGlobalMetadataContext).doOn("meta.global.created").emits("global.meta.graph_metadata.global_created");
21004
+ createLocalGraphMetadataTask("Handle global update", buildGlobalMetadataContext).doOn("meta.global.updated").emits("global.meta.graph_metadata.global_updated");
21005
+ createLocalGraphMetadataTask("Handle task helper association", (ctx) => {
21006
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21007
+ return false;
21008
+ }
21009
+ const task = resolveTaskFromMetadataContext(ctx);
21010
+ if (shouldSkipDirectTaskMetadata(task)) {
21011
+ return false;
21012
+ }
21013
+ return buildDatabaseTriggerContext({
21014
+ ...ctx.data,
21015
+ serviceName: CadenzaService.serviceRegistry.serviceName
21016
+ });
21017
+ }).doOn("meta.task.helper_associated").emits("global.meta.graph_metadata.task_helper_associated");
21018
+ createLocalGraphMetadataTask("Handle helper helper association", (ctx) => {
21019
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21020
+ return false;
21021
+ }
21022
+ const helper = resolveHelperFromMetadataContext(ctx);
21023
+ if (!helper) {
21024
+ return false;
21025
+ }
21026
+ return buildDatabaseTriggerContext({
21027
+ ...ctx.data,
21028
+ serviceName: CadenzaService.serviceRegistry.serviceName
21029
+ });
21030
+ }).doOn("meta.helper.helper_associated").emits("global.meta.graph_metadata.helper_helper_associated");
21031
+ createLocalGraphMetadataTask("Handle task global association", (ctx) => {
21032
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21033
+ return false;
21034
+ }
21035
+ const task = resolveTaskFromMetadataContext(ctx);
21036
+ if (shouldSkipDirectTaskMetadata(task)) {
21037
+ return false;
21038
+ }
21039
+ return buildDatabaseTriggerContext({
21040
+ ...ctx.data,
21041
+ serviceName: CadenzaService.serviceRegistry.serviceName
21042
+ });
21043
+ }).doOn("meta.task.global_associated").emits("global.meta.graph_metadata.task_global_associated");
21044
+ createLocalGraphMetadataTask("Handle helper global association", (ctx) => {
21045
+ if (!shouldEmitDirectPrimitiveMetadata()) {
21046
+ return false;
21047
+ }
21048
+ const helper = resolveHelperFromMetadataContext(ctx);
21049
+ if (!helper) {
21050
+ return false;
21051
+ }
21052
+ return buildDatabaseTriggerContext({
21053
+ ...ctx.data,
21054
+ serviceName: CadenzaService.serviceRegistry.serviceName
21055
+ });
21056
+ }).doOn("meta.helper.global_associated").emits("global.meta.graph_metadata.helper_global_associated");
19898
21057
  createLocalGraphMetadataTask("Handle task unsubscribing signal", (ctx) => {
19899
21058
  if (!shouldEmitDirectPrimitiveMetadata()) {
19900
21059
  return false;
@@ -19962,6 +21121,9 @@ var GraphMetadataController = class _GraphMetadataController {
19962
21121
  });
19963
21122
  }).doOn("meta.routine.task_added").emits("global.meta.graph_metadata.task_added_to_routine");
19964
21123
  createLocalGraphMetadataTask("Handle new trace", (ctx) => {
21124
+ if (!shouldPersistExecutionTrace(ctx)) {
21125
+ return false;
21126
+ }
19965
21127
  return buildDatabaseTriggerContext({
19966
21128
  ...ctx.data,
19967
21129
  service_name: CadenzaService.serviceRegistry.serviceName,
@@ -19975,10 +21137,10 @@ var GraphMetadataController = class _GraphMetadataController {
19975
21137
  return false;
19976
21138
  }
19977
21139
  const routineData = ctx.data ?? {};
19978
- const sanitizedRoutineContext = stripLocalRoutinePersistenceHints(
21140
+ const sanitizedRoutineContext = sanitizeExecutionPersistenceContext(
19979
21141
  routineData.context ?? {}
19980
21142
  );
19981
- const sanitizedRoutineMetaContext = stripLocalRoutinePersistenceHints(
21143
+ const sanitizedRoutineMetaContext = sanitizeExecutionPersistenceContext(
19982
21144
  routineData.metaContext ?? {}
19983
21145
  );
19984
21146
  const routineExecutionRow = {
@@ -20113,12 +21275,13 @@ var GraphMetadataController = class _GraphMetadataController {
20113
21275
  createLocalGraphMetadataTask(
20114
21276
  "Handle routine execution ended",
20115
21277
  (ctx) => {
21278
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21279
+ ...ctx.data,
21280
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21281
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21282
+ });
20116
21283
  return buildDatabaseTriggerContext(
20117
- {
20118
- ...ctx.data,
20119
- serviceName: CadenzaService.serviceRegistry.serviceName,
20120
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
20121
- },
21284
+ sanitizedData,
20122
21285
  ctx.filter ?? void 0
20123
21286
  );
20124
21287
  },
@@ -20132,10 +21295,10 @@ var GraphMetadataController = class _GraphMetadataController {
20132
21295
  return false;
20133
21296
  }
20134
21297
  const taskExecutionData = ctx.data ?? {};
20135
- const sanitizedTaskContext = stripLocalRoutinePersistenceHints(
21298
+ const sanitizedTaskContext = sanitizeExecutionPersistenceContext(
20136
21299
  taskExecutionData.context ?? {}
20137
21300
  );
20138
- const sanitizedTaskMetaContext = stripLocalRoutinePersistenceHints(
21301
+ const sanitizedTaskMetaContext = sanitizeExecutionPersistenceContext(
20139
21302
  taskExecutionData.metaContext ?? {}
20140
21303
  );
20141
21304
  const routineMetadata = resolveRoutinePersistenceMetadata(
@@ -20368,12 +21531,13 @@ var GraphMetadataController = class _GraphMetadataController {
20368
21531
  if (!shouldPersistTaskExecutionMetadata(ctx)) {
20369
21532
  return false;
20370
21533
  }
21534
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21535
+ ...ctx.data,
21536
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21537
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21538
+ });
20371
21539
  return buildDatabaseTriggerContext(
20372
- {
20373
- ...ctx.data,
20374
- serviceName: CadenzaService.serviceRegistry.serviceName,
20375
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
20376
- },
21540
+ sanitizedData,
20377
21541
  ctx.filter ?? void 0
20378
21542
  );
20379
21543
  },
@@ -21458,9 +22622,17 @@ var CadenzaService = class {
21458
22622
  "meta.task.relationship_added",
21459
22623
  "meta.task.relationship_removed",
21460
22624
  "meta.task.intent_associated",
22625
+ "meta.task.helper_associated",
22626
+ "meta.task.global_associated",
21461
22627
  "meta.task.observed_signal",
21462
22628
  "meta.task.attached_signal",
21463
22629
  "meta.task.detached_signal",
22630
+ "meta.helper.created",
22631
+ "meta.helper.updated",
22632
+ "meta.global.created",
22633
+ "meta.global.updated",
22634
+ "meta.helper.helper_associated",
22635
+ "meta.helper.global_associated",
21464
22636
  "meta.actor.created",
21465
22637
  "meta.actor.task_associated",
21466
22638
  "meta.fetch.handshake_complete",