@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.mjs CHANGED
@@ -21,6 +21,30 @@ var LOCAL_ROUTINE_PERSISTENCE_KEYS = [
21
21
  "__routineCreatedAt",
22
22
  "__routineIsMeta"
23
23
  ];
24
+ var BULKY_EXECUTION_PERSISTENCE_KEYS = [
25
+ "rows",
26
+ "joinedContexts",
27
+ "serviceInstances",
28
+ "serviceInstanceLeases",
29
+ "serviceInstanceTransports",
30
+ "serviceManifests",
31
+ "tasks",
32
+ "helpers",
33
+ "globals",
34
+ "signals",
35
+ "intents",
36
+ "actors",
37
+ "routines",
38
+ "directionalTaskMaps",
39
+ "actorTaskMaps",
40
+ "taskToRoutineMaps",
41
+ "taskToHelperMaps",
42
+ "helperToHelperMaps",
43
+ "taskToGlobalMaps",
44
+ "helperToGlobalMaps",
45
+ "signalToTaskMaps",
46
+ "intentToTaskMaps"
47
+ ];
24
48
  function readHintValue(source, key) {
25
49
  if (!source || typeof source !== "object") {
26
50
  return void 0;
@@ -47,8 +71,80 @@ function stripLocalRoutinePersistenceHints(input) {
47
71
  }
48
72
  return context;
49
73
  }
74
+ function summarizeQueryData(queryData) {
75
+ if (!queryData || typeof queryData !== "object") {
76
+ return void 0;
77
+ }
78
+ const summary = {};
79
+ if (queryData.data && typeof queryData.data === "object") {
80
+ summary.dataKeys = Object.keys(queryData.data).sort();
81
+ }
82
+ if (queryData.filter && typeof queryData.filter === "object") {
83
+ summary.filterKeys = Object.keys(queryData.filter).sort();
84
+ }
85
+ if (queryData.onConflict && typeof queryData.onConflict === "object") {
86
+ const onConflict = queryData.onConflict;
87
+ summary.onConflictTarget = Array.isArray(onConflict.target) ? [...onConflict.target] : onConflict.target ?? null;
88
+ }
89
+ return Object.keys(summary).length > 0 ? summary : void 0;
90
+ }
91
+ function sanitizeExecutionPersistenceContext(input) {
92
+ const context = stripLocalRoutinePersistenceHints(input);
93
+ for (const key of BULKY_EXECUTION_PERSISTENCE_KEYS) {
94
+ const value = context[key];
95
+ if (value === void 0) {
96
+ continue;
97
+ }
98
+ const countKey = `${key}Count`;
99
+ if (context[countKey] === void 0) {
100
+ if (Array.isArray(value)) {
101
+ context[countKey] = value.length;
102
+ } else if (value && typeof value === "object") {
103
+ context[countKey] = Object.keys(value).length;
104
+ }
105
+ }
106
+ delete context[key];
107
+ }
108
+ if (context.queryData && typeof context.queryData === "object") {
109
+ const queryDataSummary = summarizeQueryData(context.queryData);
110
+ if (queryDataSummary) {
111
+ context.queryData = queryDataSummary;
112
+ } else {
113
+ delete context.queryData;
114
+ }
115
+ }
116
+ return context;
117
+ }
118
+ function sanitizeExecutionPersistenceResultPayload(input) {
119
+ const payload = input && typeof input === "object" ? { ...input } : {};
120
+ const resultContext = payload.resultContext && typeof payload.resultContext === "object" ? sanitizeExecutionPersistenceContext(
121
+ payload.resultContext
122
+ ) : payload.resultContext;
123
+ const metaResultContext = payload.metaResultContext && typeof payload.metaResultContext === "object" ? sanitizeExecutionPersistenceContext(
124
+ payload.metaResultContext
125
+ ) : payload.metaResultContext;
126
+ const snakeResultContext = payload.result_context && typeof payload.result_context === "object" ? sanitizeExecutionPersistenceContext(
127
+ payload.result_context
128
+ ) : payload.result_context;
129
+ const snakeMetaResultContext = payload.meta_result_context && typeof payload.meta_result_context === "object" ? sanitizeExecutionPersistenceContext(
130
+ payload.meta_result_context
131
+ ) : payload.meta_result_context;
132
+ if (resultContext !== void 0) {
133
+ payload.resultContext = resultContext;
134
+ }
135
+ if (metaResultContext !== void 0) {
136
+ payload.metaResultContext = metaResultContext;
137
+ }
138
+ if (snakeResultContext !== void 0) {
139
+ payload.result_context = snakeResultContext;
140
+ }
141
+ if (snakeMetaResultContext !== void 0) {
142
+ payload.meta_result_context = snakeMetaResultContext;
143
+ }
144
+ return payload;
145
+ }
50
146
  function splitRoutinePersistenceContext(input) {
51
- const sanitized = stripLocalRoutinePersistenceHints(input);
147
+ const sanitized = sanitizeExecutionPersistenceContext(input);
52
148
  return {
53
149
  context: Object.fromEntries(
54
150
  Object.entries(sanitized).filter(([key]) => !key.startsWith("__"))
@@ -237,6 +333,90 @@ function ensureDelegationContextMetadata(input) {
237
333
 
238
334
  // src/graph/definition/DeputyTask.ts
239
335
  var SERVICE_REGISTRY_TRACE_SERVICE = (process.env.CADENZA_SERVICE_REGISTRY_TRACE_SERVICE ?? "").trim();
336
+ function deputyTaskExecutor(context, emit2, inquire, _tools, progressCallback) {
337
+ const task = this;
338
+ return new Promise((resolve, reject) => {
339
+ if (context.__metadata.__blockRemoteExecution) {
340
+ reject(new Error("Blocked remote execution"));
341
+ return;
342
+ }
343
+ if (context.__metadata.__skipRemoteExecution) {
344
+ resolve(context);
345
+ return;
346
+ }
347
+ const processId = uuid2();
348
+ context.__metadata.__deputyExecId = processId;
349
+ if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
350
+ console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
351
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
352
+ localTaskName: context.__localTaskName ?? null,
353
+ remoteRoutineName: context.__remoteRoutineName ?? null,
354
+ targetServiceName: context.__serviceName ?? null,
355
+ deputyExecId: processId,
356
+ dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
357
+ queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
358
+ queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
359
+ });
360
+ }
361
+ emit2("meta.deputy.delegation_requested", {
362
+ ...context
363
+ });
364
+ CadenzaService.createEphemeralMetaTask(
365
+ `On progress deputy ${task.remoteRoutineName}`,
366
+ (ctx) => {
367
+ if (typeof progressCallback === "function" && ctx.progress) {
368
+ progressCallback(ctx.progress * ctx.weight);
369
+ }
370
+ },
371
+ `Ephemeral task for deputy process ${processId}`,
372
+ {
373
+ once: false,
374
+ destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
375
+ register: false
376
+ }
377
+ ).doOn(
378
+ `meta.socket_client.delegation_progress:${processId}`,
379
+ `meta.socket_client.delegated:${processId}`,
380
+ `meta.fetch.delegated:${processId}`,
381
+ `meta.service_registry.load_balance_failed:${processId}`
382
+ );
383
+ CadenzaService.createEphemeralMetaTask(
384
+ `Resolve deputy ${task.remoteRoutineName}`,
385
+ (responseCtx) => {
386
+ const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
387
+ ...context,
388
+ ...responseCtx
389
+ } : responseCtx;
390
+ if (responseCtx?.errored) {
391
+ reject(new Error(responseCtx.__error));
392
+ } else {
393
+ if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
394
+ console.log(
395
+ "[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved",
396
+ {
397
+ localServiceName: CadenzaService.serviceRegistry.serviceName,
398
+ targetServiceName: context.__serviceName ?? null,
399
+ resolverRequestId: context.__resolverRequestId ?? null,
400
+ serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
401
+ hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
402
+ }
403
+ );
404
+ }
405
+ if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
406
+ delete mergedResponseCtx.__isDeputy;
407
+ }
408
+ resolve(mergedResponseCtx);
409
+ }
410
+ },
411
+ `Ephemeral resolver for deputy process ${processId}`,
412
+ { register: false }
413
+ ).doOn(
414
+ `meta.socket_client.delegated:${processId}`,
415
+ `meta.fetch.delegated:${processId}`,
416
+ `meta.service_registry.load_balance_failed:${processId}`
417
+ );
418
+ });
419
+ }
240
420
  var DeputyTask = class extends Task {
241
421
  /**
242
422
  * Constructs a new instance of the class with the specified parameters.
@@ -264,87 +444,9 @@ var DeputyTask = class extends Task {
264
444
  * @return {void} This constructor does not return a value.
265
445
  */
266
446
  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) {
267
- const taskFunction = (context, emit2, inquire, progressCallback) => {
268
- return new Promise((resolve, reject) => {
269
- if (context.__metadata.__blockRemoteExecution) {
270
- reject(new Error("Blocked remote execution"));
271
- return;
272
- }
273
- if (context.__metadata.__skipRemoteExecution) {
274
- resolve(context);
275
- return;
276
- }
277
- const processId = uuid2();
278
- context.__metadata.__deputyExecId = processId;
279
- if ((process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true") && context.__remoteRoutineName === "Insert service_instance") {
280
- console.log("[CADENZA_INSTANCE_DEBUG] deputy_delegation_requested", {
281
- localServiceName: CadenzaService.serviceRegistry.serviceName,
282
- localTaskName: context.__localTaskName ?? null,
283
- remoteRoutineName: context.__remoteRoutineName ?? null,
284
- targetServiceName: context.__serviceName ?? null,
285
- deputyExecId: processId,
286
- dataKeys: context.data && typeof context.data === "object" ? Object.keys(context.data) : [],
287
- queryDataKeys: context.queryData && typeof context.queryData === "object" ? Object.keys(context.queryData) : [],
288
- queryDataDataKeys: context.queryData?.data && typeof context.queryData.data === "object" ? Object.keys(context.queryData.data) : []
289
- });
290
- }
291
- emit2("meta.deputy.delegation_requested", {
292
- ...context
293
- });
294
- CadenzaService.createEphemeralMetaTask(
295
- `On progress deputy ${this.remoteRoutineName}`,
296
- (ctx) => {
297
- if (ctx.progress) progressCallback(ctx.progress * ctx.weight);
298
- },
299
- `Ephemeral task for deputy process ${processId}`,
300
- {
301
- once: false,
302
- destroyCondition: (ctx) => ctx.progress === 1 || ctx.progress === void 0,
303
- register: false
304
- }
305
- ).doOn(
306
- `meta.socket_client.delegation_progress:${processId}`,
307
- `meta.socket_client.delegated:${processId}`,
308
- `meta.fetch.delegated:${processId}`,
309
- `meta.service_registry.load_balance_failed:${processId}`
310
- );
311
- CadenzaService.createEphemeralMetaTask(
312
- `Resolve deputy ${this.remoteRoutineName}`,
313
- (responseCtx) => {
314
- const mergedResponseCtx = responseCtx && typeof responseCtx === "object" ? {
315
- ...context,
316
- ...responseCtx
317
- } : responseCtx;
318
- if (responseCtx?.errored) {
319
- reject(new Error(responseCtx.__error));
320
- } else {
321
- if (SERVICE_REGISTRY_TRACE_SERVICE.length > 0 && CadenzaService.serviceRegistry.serviceName === SERVICE_REGISTRY_TRACE_SERVICE && context.__remoteRoutineName === "Insert service_instance") {
322
- console.log("[CADENZA_SERVICE_REGISTRY_TRACE] deputy_insert_service_instance_resolved", {
323
- localServiceName: CadenzaService.serviceRegistry.serviceName,
324
- targetServiceName: context.__serviceName ?? null,
325
- resolverRequestId: context.__resolverRequestId ?? null,
326
- serviceInstanceId: mergedResponseCtx && typeof mergedResponseCtx === "object" ? mergedResponseCtx.__serviceInstanceId ?? mergedResponseCtx.uuid ?? mergedResponseCtx.data?.uuid ?? null : null,
327
- hasResolverQueryData: mergedResponseCtx && typeof mergedResponseCtx === "object" && mergedResponseCtx.__resolverQueryData !== void 0
328
- });
329
- }
330
- if (mergedResponseCtx && typeof mergedResponseCtx === "object") {
331
- delete mergedResponseCtx.__isDeputy;
332
- }
333
- resolve(mergedResponseCtx);
334
- }
335
- },
336
- `Ephemeral resolver for deputy process ${processId}`,
337
- { register: false }
338
- ).doOn(
339
- `meta.socket_client.delegated:${processId}`,
340
- `meta.fetch.delegated:${processId}`,
341
- `meta.service_registry.load_balance_failed:${processId}`
342
- );
343
- });
344
- };
345
447
  super(
346
448
  name,
347
- taskFunction,
449
+ deputyTaskExecutor,
348
450
  description,
349
451
  concurrency,
350
452
  timeout,
@@ -376,6 +478,11 @@ var DeputyTask = class extends Task {
376
478
  communicationType: "delegation"
377
479
  });
378
480
  }
481
+ clone() {
482
+ throw new Error(
483
+ `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.`
484
+ );
485
+ }
379
486
  /**
380
487
  * Executes the specified task function within the provided execution context.
381
488
  *
@@ -419,7 +526,25 @@ var DeputyTask = class extends Task {
419
526
  })
420
527
  )
421
528
  );
422
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
529
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
530
+ this,
531
+ deputyContext,
532
+ emit2,
533
+ inquire,
534
+ progressCallback
535
+ ) : {
536
+ helpers: {},
537
+ globals: {}
538
+ };
539
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
540
+ };
541
+ return this.taskFunction(
542
+ deputyContext,
543
+ emit2,
544
+ inquire,
545
+ resolvedTools,
546
+ resolvedProgressCallback
547
+ );
423
548
  }
424
549
  };
425
550
 
@@ -488,6 +613,11 @@ var DatabaseTask = class extends DeputyTask {
488
613
  );
489
614
  this.queryData = queryData;
490
615
  }
616
+ clone() {
617
+ throw new Error(
618
+ `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.`
619
+ );
620
+ }
491
621
  /**
492
622
  * Executes the specified task within the given context.
493
623
  *
@@ -613,7 +743,25 @@ var DatabaseTask = class extends DeputyTask {
613
743
  sourceTaskName: rawContext.__localTaskName ?? rawContext.__metadata?.__localTaskName ?? null
614
744
  });
615
745
  }
616
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
746
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
747
+ this,
748
+ deputyContext,
749
+ emit2,
750
+ inquire,
751
+ progressCallback
752
+ ) : {
753
+ helpers: {},
754
+ globals: {}
755
+ };
756
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
757
+ };
758
+ return this.taskFunction(
759
+ deputyContext,
760
+ emit2,
761
+ inquire,
762
+ resolvedTools,
763
+ resolvedProgressCallback
764
+ );
617
765
  }
618
766
  };
619
767
 
@@ -4058,6 +4206,10 @@ function normalizeServiceInstanceDescriptor(value) {
4058
4206
  return null;
4059
4207
  }
4060
4208
  const transports = normalizeTransportArray(raw.transports, uuid10);
4209
+ const leaseStatusRaw = normalizeString2(raw.leaseStatus ?? raw.lease_status);
4210
+ const leaseStatus = leaseStatusRaw === "active" || leaseStatusRaw === "non_responsive" || leaseStatusRaw === "inactive" || leaseStatusRaw === "deleted" ? leaseStatusRaw : void 0;
4211
+ const isActive = leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isActive ?? raw.is_active ?? true);
4212
+ const isNonResponsive = leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : Boolean(raw.isNonResponsive ?? raw.is_non_responsive ?? false);
4061
4213
  return {
4062
4214
  uuid: uuid10,
4063
4215
  serviceName,
@@ -4068,10 +4220,16 @@ function normalizeServiceInstanceDescriptor(value) {
4068
4220
  )
4069
4221
  ),
4070
4222
  isPrimary: Boolean(raw.isPrimary ?? raw.is_primary ?? false),
4071
- isActive: Boolean(raw.isActive ?? raw.is_active ?? true),
4072
- isNonResponsive: Boolean(
4073
- raw.isNonResponsive ?? raw.is_non_responsive ?? false
4074
- ),
4223
+ leaseStatus,
4224
+ leaseExpiresAt: typeof raw.leaseExpiresAt === "string" ? raw.leaseExpiresAt : typeof raw.lease_expires_at === "string" ? raw.lease_expires_at : void 0,
4225
+ lastLeaseRenewedAt: typeof raw.lastLeaseRenewedAt === "string" ? raw.lastLeaseRenewedAt : typeof raw.last_lease_renewed_at === "string" ? raw.last_lease_renewed_at : void 0,
4226
+ isReady: typeof raw.isReady === "boolean" ? raw.isReady : typeof raw.is_ready === "boolean" ? raw.is_ready : void 0,
4227
+ readinessReason: typeof raw.readinessReason === "string" ? raw.readinessReason : typeof raw.readiness_reason === "string" ? raw.readiness_reason : null,
4228
+ lastReadyAt: typeof raw.lastReadyAt === "string" ? raw.lastReadyAt : typeof raw.last_ready_at === "string" ? raw.last_ready_at : null,
4229
+ lastObservedTransportAt: typeof raw.lastObservedTransportAt === "string" ? raw.lastObservedTransportAt : typeof raw.last_observed_transport_at === "string" ? raw.last_observed_transport_at : null,
4230
+ shutdownRequestedAt: typeof raw.shutdownRequestedAt === "string" ? raw.shutdownRequestedAt : typeof raw.shutdown_requested_at === "string" ? raw.shutdown_requested_at : null,
4231
+ isActive,
4232
+ isNonResponsive,
4075
4233
  isBlocked: Boolean(raw.isBlocked ?? raw.is_blocked ?? false),
4076
4234
  runtimeState: raw.runtimeState === "healthy" || raw.runtimeState === "degraded" || raw.runtimeState === "overloaded" || raw.runtimeState === "unavailable" ? raw.runtimeState : void 0,
4077
4235
  acceptingWork: typeof raw.acceptingWork === "boolean" ? raw.acceptingWork : void 0,
@@ -4524,6 +4682,61 @@ function resolveHealthMetric(input, keys) {
4524
4682
  }
4525
4683
  return void 0;
4526
4684
  }
4685
+ function sanitizeRuntimeMetricsHealthDetail(value) {
4686
+ if (!value || typeof value !== "object") {
4687
+ return void 0;
4688
+ }
4689
+ const input = value;
4690
+ const sampledAt = typeof input.sampledAt === "string" && input.sampledAt.trim().length > 0 ? input.sampledAt : void 0;
4691
+ const cpuUsage = normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4692
+ const memoryUsage = normalizeOptionalMetric(
4693
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4694
+ );
4695
+ const eventLoopLag = normalizeOptionalMetric(
4696
+ input.eventLoopLag ?? input.eventLoopLagMs
4697
+ );
4698
+ const rssBytes = normalizeOptionalMetric(input.rssBytes);
4699
+ const heapUsedBytes = normalizeOptionalMetric(input.heapUsedBytes);
4700
+ const heapTotalBytes = normalizeOptionalMetric(input.heapTotalBytes);
4701
+ const memoryLimitBytes = normalizeOptionalMetric(input.memoryLimitBytes);
4702
+ 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) {
4703
+ return void 0;
4704
+ }
4705
+ return {
4706
+ ...sampledAt !== void 0 ? { sampledAt } : {},
4707
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4708
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4709
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4710
+ ...rssBytes !== void 0 ? { rssBytes } : {},
4711
+ ...heapUsedBytes !== void 0 ? { heapUsedBytes } : {},
4712
+ ...heapTotalBytes !== void 0 ? { heapTotalBytes } : {},
4713
+ ...memoryLimitBytes !== void 0 ? { memoryLimitBytes } : {}
4714
+ };
4715
+ }
4716
+ function sanitizeAuthorityRuntimeStatusHealth(health, options) {
4717
+ const input = health && typeof health === "object" ? health : {};
4718
+ const cpuUsage = options?.cpuUsage !== void 0 ? options.cpuUsage : normalizeOptionalMetric(input.cpuUsage ?? input.cpu ?? input.cpuLoad);
4719
+ const memoryUsage = options?.memoryUsage !== void 0 ? options.memoryUsage : normalizeOptionalMetric(
4720
+ input.memoryUsage ?? input.memory ?? input.memoryPressure
4721
+ );
4722
+ const eventLoopLag = options?.eventLoopLag !== void 0 ? options.eventLoopLag : normalizeOptionalMetric(input.eventLoopLag ?? input.eventLoopLagMs);
4723
+ const runtimeMetrics = sanitizeRuntimeMetricsHealthDetail(input.runtimeMetrics);
4724
+ const runtimeStatus = options?.state || options?.reportedAt || typeof options?.acceptingWork === "boolean" ? {
4725
+ ...options?.state ? { state: options.state } : {},
4726
+ ...typeof options?.acceptingWork === "boolean" ? { acceptingWork: options.acceptingWork } : {},
4727
+ ...options?.reportedAt ? { reportedAt: options.reportedAt } : {}
4728
+ } : void 0;
4729
+ if (cpuUsage === void 0 && memoryUsage === void 0 && eventLoopLag === void 0 && !runtimeMetrics && !runtimeStatus) {
4730
+ return void 0;
4731
+ }
4732
+ return {
4733
+ ...cpuUsage !== void 0 ? { cpuUsage } : {},
4734
+ ...memoryUsage !== void 0 ? { memoryUsage } : {},
4735
+ ...eventLoopLag !== void 0 ? { eventLoopLag } : {},
4736
+ ...runtimeMetrics ? { runtimeMetrics } : {},
4737
+ ...runtimeStatus ? { runtimeStatus } : {}
4738
+ };
4739
+ }
4527
4740
  function normalizeAuthorityRuntimeStatusReport(input) {
4528
4741
  if (!input || typeof input !== "object") {
4529
4742
  return null;
@@ -4552,6 +4765,17 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4552
4765
  (protocol) => protocol === "rest" || protocol === "socket"
4553
4766
  ) : [];
4554
4767
  const transportProtocols = transportProtocolList.length > 0 ? Array.from(new Set(transportProtocolList)) : void 0;
4768
+ const acceptingWork = Boolean(input.acceptingWork ?? input.accepting_work);
4769
+ const cpuUsage = resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]);
4770
+ const memoryUsage = resolveHealthMetric(input, [
4771
+ "memoryUsage",
4772
+ "memory",
4773
+ "memoryPressure"
4774
+ ]);
4775
+ const eventLoopLag = resolveHealthMetric(input, [
4776
+ "eventLoopLag",
4777
+ "eventLoopLagMs"
4778
+ ]);
4555
4779
  return {
4556
4780
  serviceName,
4557
4781
  serviceInstanceId,
@@ -4562,7 +4786,7 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4562
4786
  isFrontend: typeof input.isFrontend === "boolean" ? input.isFrontend : typeof input.is_frontend === "boolean" ? input.is_frontend : void 0,
4563
4787
  reportedAt,
4564
4788
  state,
4565
- acceptingWork: Boolean(input.acceptingWork ?? input.accepting_work),
4789
+ acceptingWork,
4566
4790
  numberOfRunningGraphs: Math.max(
4567
4791
  0,
4568
4792
  Math.trunc(
@@ -4571,22 +4795,22 @@ function normalizeAuthorityRuntimeStatusReport(input) {
4571
4795
  ) || 0
4572
4796
  )
4573
4797
  ),
4574
- cpuUsage: resolveHealthMetric(input, ["cpuUsage", "cpu", "cpuLoad"]),
4575
- memoryUsage: resolveHealthMetric(input, [
4576
- "memoryUsage",
4577
- "memory",
4578
- "memoryPressure"
4579
- ]),
4580
- eventLoopLag: resolveHealthMetric(input, [
4581
- "eventLoopLag",
4582
- "eventLoopLagMs"
4583
- ]),
4798
+ cpuUsage,
4799
+ memoryUsage,
4800
+ eventLoopLag,
4584
4801
  isActive: Boolean(input.isActive ?? input.is_active ?? true),
4585
4802
  isNonResponsive: Boolean(
4586
4803
  input.isNonResponsive ?? input.is_non_responsive ?? false
4587
4804
  ),
4588
4805
  isBlocked: Boolean(input.isBlocked ?? input.is_blocked ?? false),
4589
- health: input.health && typeof input.health === "object" ? input.health : void 0
4806
+ health: sanitizeAuthorityRuntimeStatusHealth(input.health, {
4807
+ state,
4808
+ acceptingWork,
4809
+ reportedAt,
4810
+ cpuUsage,
4811
+ memoryUsage,
4812
+ eventLoopLag
4813
+ })
4590
4814
  };
4591
4815
  }
4592
4816
  function buildAuthorityRuntimeStatusSignature(report) {
@@ -4599,18 +4823,53 @@ function buildAuthorityRuntimeStatusSignature(report) {
4599
4823
  transportProtocols: report.transportProtocols ?? [],
4600
4824
  state: report.state,
4601
4825
  acceptingWork: report.acceptingWork,
4602
- numberOfRunningGraphs: report.numberOfRunningGraphs,
4603
- cpuUsage: report.cpuUsage ?? null,
4604
- memoryUsage: report.memoryUsage ?? null,
4605
- eventLoopLag: report.eventLoopLag ?? null,
4606
4826
  isActive: report.isActive,
4607
4827
  isNonResponsive: report.isNonResponsive,
4608
4828
  isBlocked: report.isBlocked,
4609
- isFrontend: report.isFrontend ?? null,
4610
- health: report.health ?? {}
4829
+ isFrontend: report.isFrontend ?? null
4611
4830
  });
4612
4831
  }
4613
4832
 
4833
+ // src/registry/runtimeJitter.ts
4834
+ function normalizeKey(key) {
4835
+ return key.trim() || "default";
4836
+ }
4837
+ function hashKeyToUnitInterval(key) {
4838
+ const normalizedKey = normalizeKey(key);
4839
+ let hash = 2166136261;
4840
+ for (let index = 0; index < normalizedKey.length; index += 1) {
4841
+ hash ^= normalizedKey.charCodeAt(index);
4842
+ hash = Math.imul(hash, 16777619);
4843
+ }
4844
+ return (hash >>> 0) / 4294967295;
4845
+ }
4846
+ function normalizeJitterRatio(value) {
4847
+ if (!Number.isFinite(value) || value <= 0) {
4848
+ return 0;
4849
+ }
4850
+ return Math.min(value, 1);
4851
+ }
4852
+ function buildDeterministicJitterOffsetMs(baseMs, ratio, key) {
4853
+ if (!Number.isFinite(baseMs) || baseMs <= 0) {
4854
+ return 0;
4855
+ }
4856
+ const normalizedRatio = normalizeJitterRatio(ratio);
4857
+ if (normalizedRatio <= 0) {
4858
+ return 0;
4859
+ }
4860
+ const maxOffsetMs = Math.round(baseMs * normalizedRatio);
4861
+ if (maxOffsetMs <= 0) {
4862
+ return 0;
4863
+ }
4864
+ return Math.round(hashKeyToUnitInterval(key) * maxOffsetMs);
4865
+ }
4866
+ function buildDeterministicJitteredDelayMs(baseMs, ratio, key) {
4867
+ return Math.max(
4868
+ 0,
4869
+ Math.round(baseMs) + buildDeterministicJitterOffsetMs(baseMs, ratio, key)
4870
+ );
4871
+ }
4872
+
4614
4873
  // src/registry/serviceManifestContract.ts
4615
4874
  var AUTHORITY_SERVICE_MANIFEST_REPORT_INTENT = "meta-service-registry-authority-service-manifest-report";
4616
4875
  var AUTHORITY_SERVICE_MANIFEST_UPDATED_SIGNAL = "global.meta.cadenza_db.service_manifest_updated";
@@ -4642,11 +4901,17 @@ function normalizeServiceManifestSnapshot(input) {
4642
4901
  intents: normalizeArray(record.intents),
4643
4902
  actors: normalizeArray(record.actors),
4644
4903
  routines: normalizeArray(record.routines),
4904
+ helpers: normalizeArray(record.helpers),
4905
+ globals: normalizeArray(record.globals),
4645
4906
  directionalTaskMaps: normalizeArray(record.directionalTaskMaps),
4646
4907
  signalToTaskMaps: normalizeArray(record.signalToTaskMaps),
4647
4908
  intentToTaskMaps: normalizeArray(record.intentToTaskMaps),
4648
4909
  actorTaskMaps: normalizeArray(record.actorTaskMaps),
4649
- taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps)
4910
+ taskToRoutineMaps: normalizeArray(record.taskToRoutineMaps),
4911
+ taskToHelperMaps: normalizeArray(record.taskToHelperMaps),
4912
+ helperToHelperMaps: normalizeArray(record.helperToHelperMaps),
4913
+ taskToGlobalMaps: normalizeArray(record.taskToGlobalMaps),
4914
+ helperToGlobalMaps: normalizeArray(record.helperToGlobalMaps)
4650
4915
  };
4651
4916
  }
4652
4917
  function selectLatestServiceManifestSnapshots(snapshots) {
@@ -4910,6 +5175,27 @@ function buildRoutineDefinition(routine, serviceName) {
4910
5175
  is_meta: routine.isMeta === true
4911
5176
  };
4912
5177
  }
5178
+ function buildHelperDefinition(helper, serviceName) {
5179
+ return {
5180
+ name: helper.name,
5181
+ version: helper.version,
5182
+ description: helper.description,
5183
+ service_name: serviceName,
5184
+ is_meta: helper.isMeta === true,
5185
+ handler_source: helper.helperFunction.toString(),
5186
+ language: "js"
5187
+ };
5188
+ }
5189
+ function buildGlobalDefinition(globalDefinition, serviceName) {
5190
+ return {
5191
+ name: globalDefinition.name,
5192
+ version: globalDefinition.version,
5193
+ description: globalDefinition.description,
5194
+ service_name: serviceName,
5195
+ is_meta: globalDefinition.isMeta === true,
5196
+ value: sanitizeManifestValue(globalDefinition.value)
5197
+ };
5198
+ }
4913
5199
  function shouldExportTask(task) {
4914
5200
  return task.register !== false && task.isHidden !== true && !task.isDeputy && !task.isEphemeral;
4915
5201
  }
@@ -4925,6 +5211,12 @@ function buildActorKey(actor) {
4925
5211
  function buildRoutineKey(routine) {
4926
5212
  return `${routine.service_name}|${routine.name}|${routine.version}`;
4927
5213
  }
5214
+ function buildHelperKey(helper) {
5215
+ return `${helper.service_name}|${helper.name}|${helper.version}`;
5216
+ }
5217
+ function buildGlobalKey(globalDefinition) {
5218
+ return `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`;
5219
+ }
4928
5220
  function listManifestTasks() {
4929
5221
  const registryTasks = Array.from(CadenzaService.registry.tasks.values()).filter(
4930
5222
  (task) => Boolean(task)
@@ -4938,6 +5230,18 @@ function listManifestTasks() {
4938
5230
  ).values()
4939
5231
  );
4940
5232
  }
5233
+ function listManifestHelpers() {
5234
+ const toolRuntime = CadenzaService;
5235
+ return (toolRuntime.getAllHelpers?.() ?? []).filter(
5236
+ (helper) => Boolean(helper && !helper.destroyed)
5237
+ );
5238
+ }
5239
+ function listManifestGlobals() {
5240
+ const toolRuntime = CadenzaService;
5241
+ return (toolRuntime.getAllGlobals?.() ?? []).filter(
5242
+ (globalDefinition) => Boolean(globalDefinition && !globalDefinition.destroyed)
5243
+ );
5244
+ }
4941
5245
  function isRoutingCriticalMetaSignal(_signal) {
4942
5246
  return false;
4943
5247
  }
@@ -4953,6 +5257,8 @@ function buildServiceManifestSnapshot(params) {
4953
5257
  publicationLayer = "business_structural"
4954
5258
  } = params;
4955
5259
  const tasks = listManifestTasks().filter(shouldExportTask);
5260
+ const helpers = listManifestHelpers();
5261
+ const globals = listManifestGlobals();
4956
5262
  const routines = Array.from(CadenzaService.registry.routines.values()).filter((routine) => Boolean(routine)).filter(shouldExportRoutine);
4957
5263
  const actors = CadenzaService.getAllActors();
4958
5264
  const taskDefinitions = tasks.map((task) => buildTaskDefinition(task, serviceName)).sort(
@@ -4964,6 +5270,10 @@ function buildServiceManifestSnapshot(params) {
4964
5270
  const directionalTaskMaps = /* @__PURE__ */ new Map();
4965
5271
  const actorTaskMaps = /* @__PURE__ */ new Map();
4966
5272
  const taskToRoutineMaps = /* @__PURE__ */ new Map();
5273
+ const helperTaskMaps = /* @__PURE__ */ new Map();
5274
+ const helperHelperMaps = /* @__PURE__ */ new Map();
5275
+ const taskGlobalMaps = /* @__PURE__ */ new Map();
5276
+ const helperGlobalMaps = /* @__PURE__ */ new Map();
4967
5277
  const registerSignal = (signalName) => {
4968
5278
  const normalizedSignalName = canonicalizeSignalName(signalName);
4969
5279
  if (!normalizedSignalName || signalDefinitions.has(normalizedSignalName)) {
@@ -5047,6 +5357,37 @@ function buildServiceManifestSnapshot(params) {
5047
5357
  is_meta: actorTaskMetadata.actorKind === "meta" || task.isMeta === true
5048
5358
  });
5049
5359
  }
5360
+ const taskTools = task;
5361
+ for (const [alias, helperName] of taskTools.helperAliases?.entries?.() ?? []) {
5362
+ const helper = CadenzaService.getHelper?.(helperName);
5363
+ if (!helper) {
5364
+ continue;
5365
+ }
5366
+ const key = `${task.name}|${task.version}|${alias}|${helper.name}|${helper.version}|${serviceName}`;
5367
+ helperTaskMaps.set(key, {
5368
+ task_name: task.name,
5369
+ task_version: task.version,
5370
+ service_name: serviceName,
5371
+ alias,
5372
+ helper_name: helper.name,
5373
+ helper_version: helper.version
5374
+ });
5375
+ }
5376
+ for (const [alias, globalName] of taskTools.globalAliases?.entries?.() ?? []) {
5377
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5378
+ if (!globalDefinition) {
5379
+ continue;
5380
+ }
5381
+ const key = `${task.name}|${task.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5382
+ taskGlobalMaps.set(key, {
5383
+ task_name: task.name,
5384
+ task_version: task.version,
5385
+ service_name: serviceName,
5386
+ alias,
5387
+ global_name: globalDefinition.name,
5388
+ global_version: globalDefinition.version
5389
+ });
5390
+ }
5050
5391
  }
5051
5392
  const intentDefinitions = Array.from(CadenzaService.inquiryBroker.intents.values()).map((intent) => {
5052
5393
  const intentRecord = intent;
@@ -5078,6 +5419,44 @@ function buildServiceManifestSnapshot(params) {
5078
5419
  ).sort(
5079
5420
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5080
5421
  );
5422
+ const helperDefinitions = helpers.map((helper) => buildHelperDefinition(helper, serviceName)).sort(
5423
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5424
+ );
5425
+ const globalDefinitions = globals.map((globalDefinition) => buildGlobalDefinition(globalDefinition, serviceName)).sort(
5426
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5427
+ );
5428
+ for (const helper of helpers) {
5429
+ for (const [alias, dependencyHelperName] of helper.helperAliases.entries()) {
5430
+ const dependencyHelper = CadenzaService.getHelper?.(dependencyHelperName);
5431
+ if (!dependencyHelper) {
5432
+ continue;
5433
+ }
5434
+ const key = `${helper.name}|${helper.version}|${alias}|${dependencyHelper.name}|${dependencyHelper.version}|${serviceName}`;
5435
+ helperHelperMaps.set(key, {
5436
+ helper_name: helper.name,
5437
+ helper_version: helper.version,
5438
+ service_name: serviceName,
5439
+ alias,
5440
+ dependency_helper_name: dependencyHelper.name,
5441
+ dependency_helper_version: dependencyHelper.version
5442
+ });
5443
+ }
5444
+ for (const [alias, globalName] of helper.globalAliases.entries()) {
5445
+ const globalDefinition = CadenzaService.getGlobal?.(globalName);
5446
+ if (!globalDefinition) {
5447
+ continue;
5448
+ }
5449
+ const key = `${helper.name}|${helper.version}|${alias}|${globalDefinition.name}|${globalDefinition.version}|${serviceName}`;
5450
+ helperGlobalMaps.set(key, {
5451
+ helper_name: helper.name,
5452
+ helper_version: helper.version,
5453
+ service_name: serviceName,
5454
+ alias,
5455
+ global_name: globalDefinition.name,
5456
+ global_version: globalDefinition.version
5457
+ });
5458
+ }
5459
+ }
5081
5460
  for (const routine of routines) {
5082
5461
  for (const task of routine.tasks) {
5083
5462
  if (!task) {
@@ -5115,6 +5494,15 @@ function buildServiceManifestSnapshot(params) {
5115
5494
  const routineDefinitionsByKey = new Map(
5116
5495
  routineDefinitions.map((routine) => [buildRoutineKey(routine), routine])
5117
5496
  );
5497
+ const helperDefinitionsByKey = new Map(
5498
+ helperDefinitions.map((helper) => [buildHelperKey(helper), helper])
5499
+ );
5500
+ const globalDefinitionsByKey = new Map(
5501
+ globalDefinitions.map((globalDefinition) => [
5502
+ buildGlobalKey(globalDefinition),
5503
+ globalDefinition
5504
+ ])
5505
+ );
5118
5506
  const routingTaskKeys = /* @__PURE__ */ new Set();
5119
5507
  const routingSignalNames = /* @__PURE__ */ new Set();
5120
5508
  const routingIntentNames = /* @__PURE__ */ new Set();
@@ -5432,6 +5820,112 @@ function buildServiceManifestSnapshot(params) {
5432
5820
  ).sort(
5433
5821
  (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5434
5822
  );
5823
+ const businessHelpers = helperDefinitions.filter((helper) => helper.is_meta !== true).sort(
5824
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5825
+ );
5826
+ const localMetaHelpers = helperDefinitions.filter((helper) => helper.is_meta === true).sort(
5827
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5828
+ );
5829
+ const businessGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta !== true).sort(
5830
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5831
+ );
5832
+ const localMetaGlobals = globalDefinitions.filter((globalDefinition) => globalDefinition.is_meta === true).sort(
5833
+ (left, right) => `${left.name}:${left.version}`.localeCompare(`${right.name}:${right.version}`)
5834
+ );
5835
+ const businessTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => {
5836
+ const task = taskDefinitionsByKey.get(
5837
+ buildTaskKey({
5838
+ service_name: map.service_name,
5839
+ name: map.task_name,
5840
+ version: map.task_version
5841
+ })
5842
+ );
5843
+ const helper = helperDefinitionsByKey.get(
5844
+ buildHelperKey({
5845
+ service_name: map.service_name,
5846
+ name: map.helper_name,
5847
+ version: map.helper_version
5848
+ })
5849
+ );
5850
+ return task?.is_meta !== true && task?.is_sub_meta !== true && helper?.is_meta !== true;
5851
+ }).sort(
5852
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5853
+ );
5854
+ const localMetaTaskToHelperMaps = Array.from(helperTaskMaps.values()).filter((map) => !businessTaskToHelperMaps.includes(map)).sort(
5855
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5856
+ );
5857
+ const businessHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => {
5858
+ const helper = helperDefinitionsByKey.get(
5859
+ buildHelperKey({
5860
+ service_name: map.service_name,
5861
+ name: map.helper_name,
5862
+ version: map.helper_version
5863
+ })
5864
+ );
5865
+ const dependencyHelper = helperDefinitionsByKey.get(
5866
+ buildHelperKey({
5867
+ service_name: map.service_name,
5868
+ name: map.dependency_helper_name,
5869
+ version: map.dependency_helper_version
5870
+ })
5871
+ );
5872
+ return helper?.is_meta !== true && dependencyHelper?.is_meta !== true;
5873
+ }).sort(
5874
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5875
+ );
5876
+ const localMetaHelperToHelperMaps = Array.from(helperHelperMaps.values()).filter((map) => !businessHelperToHelperMaps.includes(map)).sort(
5877
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5878
+ );
5879
+ const businessTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => {
5880
+ const task = taskDefinitionsByKey.get(
5881
+ buildTaskKey({
5882
+ service_name: map.service_name,
5883
+ name: map.task_name,
5884
+ version: map.task_version
5885
+ })
5886
+ );
5887
+ const globalDefinition = globalDefinitionsByKey.get(
5888
+ buildGlobalKey({
5889
+ service_name: map.service_name,
5890
+ name: map.global_name,
5891
+ version: map.global_version
5892
+ })
5893
+ );
5894
+ return task?.is_meta !== true && task?.is_sub_meta !== true && globalDefinition?.is_meta !== true;
5895
+ }).sort(
5896
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5897
+ );
5898
+ const localMetaTaskToGlobalMaps = Array.from(taskGlobalMaps.values()).filter((map) => !businessTaskToGlobalMaps.includes(map)).sort(
5899
+ (left, right) => `${left.task_name}:${left.alias}`.localeCompare(`${right.task_name}:${right.alias}`)
5900
+ );
5901
+ const businessHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => {
5902
+ const helper = helperDefinitionsByKey.get(
5903
+ buildHelperKey({
5904
+ service_name: map.service_name,
5905
+ name: map.helper_name,
5906
+ version: map.helper_version
5907
+ })
5908
+ );
5909
+ const globalDefinition = globalDefinitionsByKey.get(
5910
+ buildGlobalKey({
5911
+ service_name: map.service_name,
5912
+ name: map.global_name,
5913
+ version: map.global_version
5914
+ })
5915
+ );
5916
+ return helper?.is_meta !== true && globalDefinition?.is_meta !== true;
5917
+ }).sort(
5918
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5919
+ );
5920
+ const localMetaHelperToGlobalMaps = Array.from(helperGlobalMaps.values()).filter((map) => !businessHelperToGlobalMaps.includes(map)).sort(
5921
+ (left, right) => `${left.helper_name}:${left.alias}`.localeCompare(`${right.helper_name}:${right.alias}`)
5922
+ );
5923
+ const cumulativeHelpers = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelpers : [...businessHelpers, ...localMetaHelpers];
5924
+ const cumulativeGlobals = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessGlobals : [...businessGlobals, ...localMetaGlobals];
5925
+ const cumulativeTaskToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToHelperMaps : [...businessTaskToHelperMaps, ...localMetaTaskToHelperMaps];
5926
+ const cumulativeHelperToHelperMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToHelperMaps : [...businessHelperToHelperMaps, ...localMetaHelperToHelperMaps];
5927
+ const cumulativeTaskToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessTaskToGlobalMaps : [...businessTaskToGlobalMaps, ...localMetaTaskToGlobalMaps];
5928
+ const cumulativeHelperToGlobalMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessHelperToGlobalMaps : [...businessHelperToGlobalMaps, ...localMetaHelperToGlobalMaps];
5435
5929
  const cumulativeDirectionalTaskMaps = publicationLayer === "routing_capability" ? [] : publicationLayer === "business_structural" ? businessDirectionalTaskMaps : Array.from(
5436
5930
  new Map(
5437
5931
  [...businessDirectionalTaskMaps, ...localMetaDirectionalTaskMaps].map(
@@ -5474,11 +5968,17 @@ function buildServiceManifestSnapshot(params) {
5474
5968
  intents: cumulativeIntents,
5475
5969
  actors: cumulativeActors,
5476
5970
  routines: cumulativeRoutines,
5971
+ helpers: cumulativeHelpers,
5972
+ globals: cumulativeGlobals,
5477
5973
  directionalTaskMaps: cumulativeDirectionalTaskMaps,
5478
5974
  signalToTaskMaps: publicationLayer === "routing_capability" ? publishedSignalTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps] : [...publishedSignalTaskMaps, ...localMetaSignalTaskMaps],
5479
5975
  intentToTaskMaps: publicationLayer === "routing_capability" ? publishedIntentTaskMaps : publicationLayer === "local_meta_structural" ? [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps] : [...publishedIntentTaskMaps, ...localMetaIntentTaskMaps],
5480
5976
  actorTaskMaps: cumulativeActorTaskMaps,
5481
- taskToRoutineMaps: cumulativeTaskToRoutineMaps
5977
+ taskToRoutineMaps: cumulativeTaskToRoutineMaps,
5978
+ taskToHelperMaps: cumulativeTaskToHelperMaps,
5979
+ helperToHelperMaps: cumulativeHelperToHelperMaps,
5980
+ taskToGlobalMaps: cumulativeTaskToGlobalMaps,
5981
+ helperToGlobalMaps: cumulativeHelperToGlobalMaps
5482
5982
  };
5483
5983
  return {
5484
5984
  ...manifestBody,
@@ -5522,6 +6022,20 @@ function explodeServiceManifestSnapshots(snapshots) {
5522
6022
  `${right.service_name}|${right.name}|${right.version}`
5523
6023
  )
5524
6024
  );
6025
+ const helpers = dedupe(
6026
+ snapshots.flatMap((snapshot) => snapshot.helpers),
6027
+ (helper) => `${helper.service_name}|${helper.name}|${helper.version}`,
6028
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6029
+ `${right.service_name}|${right.name}|${right.version}`
6030
+ )
6031
+ );
6032
+ const globals = dedupe(
6033
+ snapshots.flatMap((snapshot) => snapshot.globals),
6034
+ (globalDefinition) => `${globalDefinition.service_name}|${globalDefinition.name}|${globalDefinition.version}`,
6035
+ (left, right) => `${left.service_name}|${left.name}|${left.version}`.localeCompare(
6036
+ `${right.service_name}|${right.name}|${right.version}`
6037
+ )
6038
+ );
5525
6039
  const directionalTaskMaps = dedupe(
5526
6040
  snapshots.flatMap((snapshot) => snapshot.directionalTaskMaps),
5527
6041
  (map) => `${map.predecessor_service_name}|${map.predecessor_task_name}|${map.predecessor_task_version}|${map.service_name}|${map.task_name}|${map.task_version}`,
@@ -5557,17 +6071,51 @@ function explodeServiceManifestSnapshots(snapshots) {
5557
6071
  `${right.routine_name}|${right.routine_version}|${right.service_name}|${right.task_name}|${right.task_version}`
5558
6072
  )
5559
6073
  );
6074
+ const taskToHelperMaps = dedupe(
6075
+ snapshots.flatMap((snapshot) => snapshot.taskToHelperMaps),
6076
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.helper_name}|${map.helper_version}`,
6077
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.helper_name}`.localeCompare(
6078
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.helper_name}`
6079
+ )
6080
+ );
6081
+ const helperToHelperMaps = dedupe(
6082
+ snapshots.flatMap((snapshot) => snapshot.helperToHelperMaps),
6083
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.dependency_helper_name}|${map.dependency_helper_version}`,
6084
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.dependency_helper_name}`.localeCompare(
6085
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.dependency_helper_name}`
6086
+ )
6087
+ );
6088
+ const taskToGlobalMaps = dedupe(
6089
+ snapshots.flatMap((snapshot) => snapshot.taskToGlobalMaps),
6090
+ (map) => `${map.service_name}|${map.task_name}|${map.task_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6091
+ (left, right) => `${left.service_name}|${left.task_name}|${left.alias}|${left.global_name}`.localeCompare(
6092
+ `${right.service_name}|${right.task_name}|${right.alias}|${right.global_name}`
6093
+ )
6094
+ );
6095
+ const helperToGlobalMaps = dedupe(
6096
+ snapshots.flatMap((snapshot) => snapshot.helperToGlobalMaps),
6097
+ (map) => `${map.service_name}|${map.helper_name}|${map.helper_version}|${map.alias}|${map.global_name}|${map.global_version}`,
6098
+ (left, right) => `${left.service_name}|${left.helper_name}|${left.alias}|${left.global_name}`.localeCompare(
6099
+ `${right.service_name}|${right.helper_name}|${right.alias}|${right.global_name}`
6100
+ )
6101
+ );
5560
6102
  return {
5561
6103
  tasks,
5562
6104
  signals,
5563
6105
  intents,
5564
6106
  actors,
5565
6107
  routines,
6108
+ helpers,
6109
+ globals,
5566
6110
  directionalTaskMaps,
5567
6111
  signalToTaskMaps,
5568
6112
  intentToTaskMaps,
5569
6113
  actorTaskMaps,
5570
- taskToRoutineMaps
6114
+ taskToRoutineMaps,
6115
+ taskToHelperMaps,
6116
+ helperToHelperMaps,
6117
+ taskToGlobalMaps,
6118
+ helperToGlobalMaps
5571
6119
  };
5572
6120
  }
5573
6121
 
@@ -5616,11 +6164,57 @@ var SERVICE_REGISTRY_TRACE_SERVICE2 = (process.env.CADENZA_SERVICE_REGISTRY_TRAC
5616
6164
  function shouldTraceServiceRegistry(serviceName) {
5617
6165
  return SERVICE_REGISTRY_TRACE_SERVICE2.length > 0 && serviceName === SERVICE_REGISTRY_TRACE_SERVICE2;
5618
6166
  }
5619
- function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
5620
- const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
5621
- const getJoinedValue = (key) => {
5622
- for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
5623
- const joinedContext = joinedContexts[index];
6167
+ function normalizeLeaseStatus(value) {
6168
+ const status = String(value ?? "").trim();
6169
+ if (status === "active" || status === "non_responsive" || status === "inactive" || status === "deleted") {
6170
+ return status;
6171
+ }
6172
+ return null;
6173
+ }
6174
+ function overlayServiceInstancesWithLeases(serviceInstances, serviceInstanceLeases) {
6175
+ if (serviceInstanceLeases.length === 0) {
6176
+ return serviceInstances;
6177
+ }
6178
+ const leasesByInstanceId = /* @__PURE__ */ new Map();
6179
+ for (const row of serviceInstanceLeases) {
6180
+ const serviceInstanceId = String(
6181
+ row.service_instance_id ?? row.serviceInstanceId ?? ""
6182
+ ).trim();
6183
+ if (!serviceInstanceId) {
6184
+ continue;
6185
+ }
6186
+ leasesByInstanceId.set(serviceInstanceId, row);
6187
+ }
6188
+ return serviceInstances.map((row) => {
6189
+ const serviceInstanceId = String(row.uuid ?? "").trim();
6190
+ const lease = serviceInstanceId ? leasesByInstanceId.get(serviceInstanceId) : void 0;
6191
+ if (!lease) {
6192
+ return row;
6193
+ }
6194
+ const leaseStatus = normalizeLeaseStatus(
6195
+ lease.status ?? lease.lease_status ?? lease.leaseStatus
6196
+ );
6197
+ return {
6198
+ ...row,
6199
+ lease_status: leaseStatus ?? void 0,
6200
+ is_ready: typeof lease.is_ready === "boolean" ? lease.is_ready : typeof lease.isReady === "boolean" ? lease.isReady : void 0,
6201
+ readiness_reason: typeof lease.readiness_reason === "string" ? lease.readiness_reason : typeof lease.readinessReason === "string" ? lease.readinessReason : null,
6202
+ lease_expires_at: typeof lease.lease_expires_at === "string" ? lease.lease_expires_at : typeof lease.leaseExpiresAt === "string" ? lease.leaseExpiresAt : null,
6203
+ last_lease_renewed_at: typeof lease.last_lease_renewed_at === "string" ? lease.last_lease_renewed_at : typeof lease.lastLeaseRenewedAt === "string" ? lease.lastLeaseRenewedAt : null,
6204
+ last_ready_at: typeof lease.last_ready_at === "string" ? lease.last_ready_at : typeof lease.lastReadyAt === "string" ? lease.lastReadyAt : null,
6205
+ last_observed_transport_at: typeof lease.last_observed_transport_at === "string" ? lease.last_observed_transport_at : typeof lease.lastObservedTransportAt === "string" ? lease.lastObservedTransportAt : null,
6206
+ shutdown_requested_at: typeof lease.shutdown_requested_at === "string" ? lease.shutdown_requested_at : typeof lease.shutdownRequestedAt === "string" ? lease.shutdownRequestedAt : null,
6207
+ is_active: leaseStatus === "active" ? true : leaseStatus === "non_responsive" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_active,
6208
+ is_non_responsive: leaseStatus === "non_responsive" ? true : leaseStatus === "active" || leaseStatus === "inactive" || leaseStatus === "deleted" ? false : row.is_non_responsive,
6209
+ deleted: leaseStatus === "deleted" ? true : Boolean(row.deleted ?? false)
6210
+ };
6211
+ });
6212
+ }
6213
+ function buildServiceRegistryInsertQueryData(tableName, ctx, queryData) {
6214
+ const joinedContexts = Array.isArray(ctx.joinedContexts) ? ctx.joinedContexts : [];
6215
+ const getJoinedValue = (key) => {
6216
+ for (let index = joinedContexts.length - 1; index >= 0; index -= 1) {
6217
+ const joinedContext = joinedContexts[index];
5624
6218
  if (joinedContext && typeof joinedContext === "object" && (Object.prototype.hasOwnProperty.call(joinedContext, key) || joinedContext[key] !== void 0)) {
5625
6219
  return joinedContext[key];
5626
6220
  }
@@ -5693,6 +6287,43 @@ function sanitizeAuthorityBootstrapDelegationContext(ctx) {
5693
6287
  }
5694
6288
  return sanitized;
5695
6289
  }
6290
+ var BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS = [
6291
+ "data",
6292
+ "batch",
6293
+ "transaction",
6294
+ "onConflict",
6295
+ "filter",
6296
+ "fields",
6297
+ "joins",
6298
+ "sort",
6299
+ "limit",
6300
+ "offset",
6301
+ "queryMode",
6302
+ "aggregates",
6303
+ "groupBy"
6304
+ ];
6305
+ function isBootstrapDbOperationRoutineName(value) {
6306
+ return /^(Insert|Update|Query|Delete)\s+/.test(String(value ?? "").trim());
6307
+ }
6308
+ function compactAuthorityBootstrapRequestBody(ctx) {
6309
+ if (!isBootstrapDbOperationRoutineName(ctx.__remoteRoutineName)) {
6310
+ return ctx;
6311
+ }
6312
+ const queryData = ctx.queryData && typeof ctx.queryData === "object" ? { ...ctx.queryData } : null;
6313
+ if (!queryData) {
6314
+ return ctx;
6315
+ }
6316
+ const compacted = {
6317
+ ...ctx,
6318
+ queryData
6319
+ };
6320
+ for (const key of BOOTSTRAP_DB_OPERATION_CONTEXT_KEYS) {
6321
+ if (Object.prototype.hasOwnProperty.call(queryData, key)) {
6322
+ delete compacted[key];
6323
+ }
6324
+ }
6325
+ return compacted;
6326
+ }
5696
6327
  function cloneServiceRegistryContextValue(value) {
5697
6328
  if (value instanceof Date) {
5698
6329
  return new Date(value.getTime());
@@ -6049,6 +6680,92 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
6049
6680
  `Resolve service registry insert for ${tableName}`,
6050
6681
  (ctx, emit2) => new Promise((resolve) => {
6051
6682
  const resolverRequestId = uuid3();
6683
+ const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
6684
+ const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
6685
+ const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
6686
+ const selfBootstrapRetrySignal = CadenzaService.serviceRegistry.serviceName === "CadenzaDB" && resolvedTargetServiceName === "CadenzaDB" && !localInsertTask ? getSelfBootstrapRegistrationRetrySignal(tableName) : null;
6687
+ if (selfBootstrapRetrySignal) {
6688
+ CadenzaService.schedule(
6689
+ selfBootstrapRetrySignal,
6690
+ {
6691
+ ...ctx
6692
+ },
6693
+ 250
6694
+ );
6695
+ resolve(false);
6696
+ return;
6697
+ }
6698
+ if (bootstrapAuthorityInsertSpec) {
6699
+ const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
6700
+ const nextQueryData = buildServiceRegistryInsertQueryData(
6701
+ tableName,
6702
+ sanitizedContext,
6703
+ queryData
6704
+ );
6705
+ const inquiryContext = ensureDelegationContextMetadata({
6706
+ ...sanitizedContext,
6707
+ data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
6708
+ batch: nextQueryData.batch !== void 0 ? nextQueryData.batch : sanitizedContext.batch,
6709
+ onConflict: Object.prototype.hasOwnProperty.call(nextQueryData, "onConflict") ? nextQueryData.onConflict : void 0,
6710
+ transaction: nextQueryData.transaction !== void 0 ? nextQueryData.transaction : sanitizedContext.transaction,
6711
+ queryData: nextQueryData
6712
+ });
6713
+ inquiryContext.__metadata = {
6714
+ ...inquiryContext.__metadata ?? {},
6715
+ __skipRemoteExecution: inquiryContext.__metadata?.__skipRemoteExecution ?? inquiryContext.__skipRemoteExecution ?? false,
6716
+ __blockRemoteExecution: inquiryContext.__metadata?.__blockRemoteExecution ?? inquiryContext.__blockRemoteExecution ?? false
6717
+ };
6718
+ CadenzaService.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
6719
+ bootstrapAuthorityInsertSpec.intentName,
6720
+ inquiryContext
6721
+ );
6722
+ void CadenzaService.inquire(
6723
+ bootstrapAuthorityInsertSpec.intentName,
6724
+ inquiryContext,
6725
+ {
6726
+ requireComplete: true,
6727
+ timeout: bootstrapAuthorityInsertSpec.defaultTimeoutMs
6728
+ }
6729
+ ).then(
6730
+ (result) => resolve(
6731
+ resolveBootstrapAuthorityInsertResult(
6732
+ tableName,
6733
+ sanitizedContext,
6734
+ nextQueryData,
6735
+ result,
6736
+ emit2
6737
+ )
6738
+ )
6739
+ ).catch(
6740
+ (error) => resolve(
6741
+ resolveBootstrapAuthorityInsertResult(
6742
+ tableName,
6743
+ sanitizedContext,
6744
+ nextQueryData,
6745
+ error,
6746
+ emit2
6747
+ )
6748
+ )
6749
+ );
6750
+ return;
6751
+ }
6752
+ const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
6753
+ if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6754
+ console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
6755
+ tableName,
6756
+ executionSignal,
6757
+ hasLocalInsertTask: !!localInsertTask,
6758
+ serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
6759
+ serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
6760
+ hasData: !!ctx.data,
6761
+ dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
6762
+ registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
6763
+ });
6764
+ }
6765
+ if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
6766
+ wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
6767
+ wiredLocalTaskNames.add(localInsertTask.name);
6768
+ }
6052
6769
  CadenzaService.createEphemeralMetaTask(
6053
6770
  `Resolve service registry insert execution for ${tableName} (${resolverRequestId})`,
6054
6771
  (resultCtx) => {
@@ -6148,95 +6865,11 @@ function resolveServiceRegistryInsertTask(tableName, queryData = {}, options = {
6148
6865
  },
6149
6866
  `Resolves signal-driven ${tableName} service-registry insert execution.`,
6150
6867
  {
6151
- register: false
6868
+ register: false,
6869
+ once: false,
6870
+ destroyCondition: (result) => result !== false
6152
6871
  }
6153
6872
  ).doOn(executionResolvedSignal, executionFailedSignal);
6154
- const localInsertTask = CadenzaService.getLocalCadenzaDBInsertTask(tableName);
6155
- const bootstrapAuthorityInsertSpec = !localInsertTask && CadenzaService.serviceRegistry.connectsToCadenzaDB ? getAuthorityBootstrapInsertIntentSpecForTable(tableName) : null;
6156
- const resolvedTargetServiceName = resolveServiceNameFromContext(ctx);
6157
- const selfBootstrapRetrySignal = CadenzaService.serviceRegistry.serviceName === "CadenzaDB" && resolvedTargetServiceName === "CadenzaDB" && !localInsertTask ? getSelfBootstrapRegistrationRetrySignal(tableName) : null;
6158
- if (selfBootstrapRetrySignal) {
6159
- CadenzaService.schedule(
6160
- selfBootstrapRetrySignal,
6161
- {
6162
- ...ctx
6163
- },
6164
- 250
6165
- );
6166
- resolve(false);
6167
- return;
6168
- }
6169
- if (bootstrapAuthorityInsertSpec) {
6170
- const sanitizedContext = sanitizeServiceRegistryInsertExecutionContext(ctx);
6171
- const nextQueryData = buildServiceRegistryInsertQueryData(
6172
- tableName,
6173
- sanitizedContext,
6174
- queryData
6175
- );
6176
- const inquiryContext = ensureDelegationContextMetadata({
6177
- ...sanitizedContext,
6178
- data: nextQueryData.data !== void 0 ? nextQueryData.data : sanitizedContext.data,
6179
- batch: nextQueryData.batch !== void 0 ? nextQueryData.batch : sanitizedContext.batch,
6180
- onConflict: Object.prototype.hasOwnProperty.call(nextQueryData, "onConflict") ? nextQueryData.onConflict : void 0,
6181
- transaction: nextQueryData.transaction !== void 0 ? nextQueryData.transaction : sanitizedContext.transaction,
6182
- queryData: nextQueryData
6183
- });
6184
- inquiryContext.__metadata = {
6185
- ...inquiryContext.__metadata ?? {},
6186
- __skipRemoteExecution: inquiryContext.__metadata?.__skipRemoteExecution ?? inquiryContext.__skipRemoteExecution ?? false,
6187
- __blockRemoteExecution: inquiryContext.__metadata?.__blockRemoteExecution ?? inquiryContext.__blockRemoteExecution ?? false
6188
- };
6189
- CadenzaService.serviceRegistry.ensureBootstrapAuthorityControlPlaneForInquiry(
6190
- bootstrapAuthorityInsertSpec.intentName,
6191
- inquiryContext
6192
- );
6193
- void CadenzaService.inquire(
6194
- bootstrapAuthorityInsertSpec.intentName,
6195
- inquiryContext,
6196
- {
6197
- requireComplete: true,
6198
- timeout: bootstrapAuthorityInsertSpec.defaultTimeoutMs
6199
- }
6200
- ).then(
6201
- (result) => resolve(
6202
- resolveBootstrapAuthorityInsertResult(
6203
- tableName,
6204
- sanitizedContext,
6205
- nextQueryData,
6206
- result,
6207
- emit2
6208
- )
6209
- )
6210
- ).catch(
6211
- (error) => resolve(
6212
- resolveBootstrapAuthorityInsertResult(
6213
- tableName,
6214
- sanitizedContext,
6215
- nextQueryData,
6216
- error,
6217
- emit2
6218
- )
6219
- )
6220
- );
6221
- return;
6222
- }
6223
- const executionSignal = localInsertTask ? localExecutionRequestedSignal : remoteExecutionRequestedSignal;
6224
- if ((tableName === "service_instance" || tableName === "service") && (process.env.CADENZA_INSTANCE_DEBUG === "1" || process.env.CADENZA_INSTANCE_DEBUG === "true")) {
6225
- console.log("[CADENZA_INSTANCE_DEBUG] resolve_service_registry_insert", {
6226
- tableName,
6227
- executionSignal,
6228
- hasLocalInsertTask: !!localInsertTask,
6229
- serviceName: ctx.__serviceName ?? ctx.data?.service_name ?? null,
6230
- serviceInstanceId: ctx.__serviceInstanceId ?? ctx.data?.uuid ?? null,
6231
- hasData: !!ctx.data,
6232
- dataKeys: ctx.data && typeof ctx.data === "object" ? Object.keys(ctx.data) : [],
6233
- registrationKeys: ctx.__registrationData && typeof ctx.__registrationData === "object" ? Object.keys(ctx.__registrationData) : []
6234
- });
6235
- }
6236
- if (localInsertTask && !wiredLocalTaskNames.has(localInsertTask.name)) {
6237
- wireExecutionTarget(localInsertTask, prepareLocalExecutionTask);
6238
- wiredLocalTaskNames.add(localInsertTask.name);
6239
- }
6240
6873
  emit2(executionSignal, {
6241
6874
  ...ctx,
6242
6875
  __resolverRequestId: resolverRequestId
@@ -6261,6 +6894,17 @@ function readPositiveIntegerEnv(name, fallback) {
6261
6894
  }
6262
6895
  return normalized;
6263
6896
  }
6897
+ function readNonNegativeFloatEnv(name, fallback) {
6898
+ if (typeof process === "undefined") {
6899
+ return fallback;
6900
+ }
6901
+ const raw = process.env?.[name];
6902
+ const parsed = Number(raw);
6903
+ if (!Number.isFinite(parsed) || parsed < 0) {
6904
+ return fallback;
6905
+ }
6906
+ return parsed;
6907
+ }
6264
6908
  var ServiceRegistry = class _ServiceRegistry {
6265
6909
  /**
6266
6910
  * Initializes a private constructor for managing service instances, remote signals,
@@ -6310,6 +6954,9 @@ var ServiceRegistry = class _ServiceRegistry {
6310
6954
  "CADENZA_RUNTIME_STATUS_REST_REFRESH_MS",
6311
6955
  this.runtimeMetricsSampleIntervalMs
6312
6956
  );
6957
+ this.runtimeStatusLoopJitterRatio = normalizeJitterRatio(
6958
+ readNonNegativeFloatEnv("CADENZA_RUNTIME_STATUS_JITTER_RATIO", 0.2)
6959
+ );
6313
6960
  this.runtimeStatusMissThreshold = readPositiveIntegerEnv(
6314
6961
  "CADENZA_RUNTIME_STATUS_MISSED_HEARTBEATS",
6315
6962
  3
@@ -6358,6 +7005,18 @@ var ServiceRegistry = class _ServiceRegistry {
6358
7005
  "CADENZA_RUNTIME_STATUS_OVERLOADED_GRAPH_THRESHOLD",
6359
7006
  20
6360
7007
  );
7008
+ this.bootstrapFullSyncRetryJitterRatio = normalizeJitterRatio(
7009
+ readNonNegativeFloatEnv(
7010
+ "CADENZA_BOOTSTRAP_FULL_SYNC_RETRY_JITTER_RATIO",
7011
+ 0.2
7012
+ )
7013
+ );
7014
+ this.serviceCommunicationRetryJitterRatio = normalizeJitterRatio(
7015
+ readNonNegativeFloatEnv(
7016
+ "CADENZA_SERVICE_COMMUNICATION_RETRY_JITTER_RATIO",
7017
+ 0.2
7018
+ )
7019
+ );
6361
7020
  this.serviceName = null;
6362
7021
  this.serviceInstanceId = null;
6363
7022
  this.numberOfRunningGraphs = 0;
@@ -7336,6 +7995,12 @@ var ServiceRegistry = class _ServiceRegistry {
7336
7995
  const tasks = this.readArrayPayload(inquiryResult, [
7337
7996
  "tasks"
7338
7997
  ]);
7998
+ const helpers = this.readArrayPayload(inquiryResult, [
7999
+ "helpers"
8000
+ ]);
8001
+ const globals = this.readArrayPayload(inquiryResult, [
8002
+ "globals"
8003
+ ]);
7339
8004
  const signals = this.readArrayPayload(inquiryResult, [
7340
8005
  "signals"
7341
8006
  ]);
@@ -7360,6 +8025,22 @@ var ServiceRegistry = class _ServiceRegistry {
7360
8025
  inquiryResult,
7361
8026
  ["taskToRoutineMaps", "task_to_routine_maps"]
7362
8027
  );
8028
+ const taskToHelperMaps = this.readArrayPayload(
8029
+ inquiryResult,
8030
+ ["taskToHelperMaps", "task_to_helper_maps"]
8031
+ );
8032
+ const helperToHelperMaps = this.readArrayPayload(
8033
+ inquiryResult,
8034
+ ["helperToHelperMaps", "helper_to_helper_maps"]
8035
+ );
8036
+ const taskToGlobalMaps = this.readArrayPayload(
8037
+ inquiryResult,
8038
+ ["taskToGlobalMaps", "task_to_global_maps"]
8039
+ );
8040
+ const helperToGlobalMaps = this.readArrayPayload(
8041
+ inquiryResult,
8042
+ ["helperToGlobalMaps", "helper_to_global_maps"]
8043
+ );
7363
8044
  const serviceInstances = this.normalizeServiceInstancesFromSync(
7364
8045
  inquiryResult
7365
8046
  );
@@ -7393,6 +8074,8 @@ var ServiceRegistry = class _ServiceRegistry {
7393
8074
  serviceInstanceTransports: serviceInstanceTransports.length,
7394
8075
  serviceManifests: serviceManifests.length,
7395
8076
  tasks: tasks.length,
8077
+ helpers: helpers.length,
8078
+ globals: globals.length,
7396
8079
  signals: signals.length,
7397
8080
  intents: intents.length,
7398
8081
  actors: actors.length,
@@ -7418,6 +8101,8 @@ var ServiceRegistry = class _ServiceRegistry {
7418
8101
  serviceInstanceTransports,
7419
8102
  serviceManifests,
7420
8103
  tasks,
8104
+ helpers,
8105
+ globals,
7421
8106
  signals,
7422
8107
  intents,
7423
8108
  actors,
@@ -7425,6 +8110,10 @@ var ServiceRegistry = class _ServiceRegistry {
7425
8110
  directionalTaskMaps,
7426
8111
  actorTaskMaps,
7427
8112
  taskToRoutineMaps,
8113
+ taskToHelperMaps,
8114
+ helperToHelperMaps,
8115
+ taskToGlobalMaps,
8116
+ helperToGlobalMaps,
7428
8117
  __inquiryMeta: inquiryResult.__inquiryMeta
7429
8118
  };
7430
8119
  },
@@ -8044,29 +8733,51 @@ var ServiceRegistry = class _ServiceRegistry {
8044
8733
  this.runtimeStatusHeartbeatStarted = true;
8045
8734
  if (!this.runtimeMetricsSamplingStarted) {
8046
8735
  this.runtimeMetricsSamplingStarted = true;
8736
+ CadenzaService.emit(META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL, {});
8047
8737
  CadenzaService.interval(
8048
8738
  META_RUNTIME_METRICS_SAMPLE_TICK_SIGNAL,
8049
8739
  {},
8050
8740
  this.runtimeMetricsSampleIntervalMs,
8051
- true
8741
+ false,
8742
+ this.buildJitteredIntervalStartDate(
8743
+ this.runtimeMetricsSampleIntervalMs,
8744
+ "runtime-metrics-sample"
8745
+ )
8052
8746
  );
8053
8747
  }
8748
+ CadenzaService.emit(META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL, {
8749
+ reason: "heartbeat"
8750
+ });
8054
8751
  CadenzaService.interval(
8055
8752
  META_RUNTIME_STATUS_HEARTBEAT_TICK_SIGNAL,
8056
8753
  { reason: "heartbeat" },
8057
8754
  this.runtimeStatusHeartbeatIntervalMs,
8058
- true
8755
+ false,
8756
+ this.buildJitteredIntervalStartDate(
8757
+ this.runtimeStatusHeartbeatIntervalMs,
8758
+ "runtime-status-heartbeat"
8759
+ )
8059
8760
  );
8060
8761
  CadenzaService.interval(
8061
8762
  META_RUNTIME_STATUS_MONITOR_TICK_SIGNAL,
8062
8763
  {},
8063
- this.runtimeStatusHeartbeatIntervalMs
8764
+ this.runtimeStatusHeartbeatIntervalMs,
8765
+ false,
8766
+ this.buildJitteredIntervalStartDate(
8767
+ this.runtimeStatusHeartbeatIntervalMs,
8768
+ "runtime-status-monitor"
8769
+ )
8064
8770
  );
8771
+ CadenzaService.emit(META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL, {});
8065
8772
  CadenzaService.interval(
8066
8773
  META_RUNTIME_STATUS_REST_REFRESH_TICK_SIGNAL,
8067
8774
  {},
8068
8775
  this.runtimeStatusRestRefreshIntervalMs,
8069
- true
8776
+ false,
8777
+ this.buildJitteredIntervalStartDate(
8778
+ this.runtimeStatusRestRefreshIntervalMs,
8779
+ "runtime-status-rest-refresh"
8780
+ )
8070
8781
  );
8071
8782
  return true;
8072
8783
  },
@@ -9071,11 +9782,14 @@ var ServiceRegistry = class _ServiceRegistry {
9071
9782
  }
9072
9783
  collectBootstrapFullSyncPayload(ctx) {
9073
9784
  const serviceInstances = [];
9785
+ const serviceInstanceLeases = [];
9074
9786
  const serviceInstanceTransports = [];
9075
9787
  const manifestSnapshots = [];
9076
9788
  const signalToTaskMaps = [];
9077
9789
  const intentToTaskMaps = [];
9078
9790
  const tasks = [];
9791
+ const helpers = [];
9792
+ const globals = [];
9079
9793
  const signals = [];
9080
9794
  const intents = [];
9081
9795
  const actors = [];
@@ -9083,11 +9797,18 @@ var ServiceRegistry = class _ServiceRegistry {
9083
9797
  const directionalTaskMaps = [];
9084
9798
  const actorTaskMaps = [];
9085
9799
  const taskToRoutineMaps = [];
9800
+ const taskToHelperMaps = [];
9801
+ const helperToHelperMaps = [];
9802
+ const taskToGlobalMaps = [];
9803
+ const helperToGlobalMaps = [];
9086
9804
  const seenServiceInstances = /* @__PURE__ */ new Set();
9805
+ const seenServiceInstanceLeases = /* @__PURE__ */ new Set();
9087
9806
  const seenServiceInstanceTransports = /* @__PURE__ */ new Set();
9088
9807
  const seenSignalMaps = /* @__PURE__ */ new Set();
9089
9808
  const seenIntentMaps = /* @__PURE__ */ new Set();
9090
9809
  const seenTasks = /* @__PURE__ */ new Set();
9810
+ const seenHelpers = /* @__PURE__ */ new Set();
9811
+ const seenGlobals = /* @__PURE__ */ new Set();
9091
9812
  const seenSignals = /* @__PURE__ */ new Set();
9092
9813
  const seenIntents = /* @__PURE__ */ new Set();
9093
9814
  const seenActors = /* @__PURE__ */ new Set();
@@ -9095,6 +9816,10 @@ var ServiceRegistry = class _ServiceRegistry {
9095
9816
  const seenDirectionalTaskMaps = /* @__PURE__ */ new Set();
9096
9817
  const seenActorTaskMaps = /* @__PURE__ */ new Set();
9097
9818
  const seenTaskToRoutineMaps = /* @__PURE__ */ new Set();
9819
+ const seenTaskToHelperMaps = /* @__PURE__ */ new Set();
9820
+ const seenHelperToHelperMaps = /* @__PURE__ */ new Set();
9821
+ const seenTaskToGlobalMaps = /* @__PURE__ */ new Set();
9822
+ const seenHelperToGlobalMaps = /* @__PURE__ */ new Set();
9098
9823
  const contexts = Array.isArray(ctx.joinedContexts) ? [ctx, ...ctx.joinedContexts] : [ctx];
9099
9824
  const pushUnique = (rows, target, seen, keyResolver) => {
9100
9825
  for (const row of rows) {
@@ -9125,6 +9850,12 @@ var ServiceRegistry = class _ServiceRegistry {
9125
9850
  "serviceInstance",
9126
9851
  "service_instance"
9127
9852
  ]);
9853
+ const serviceInstanceLeaseRows = readDirectArrayPayload(candidate, [
9854
+ "serviceInstanceLeases",
9855
+ "service_instance_leases",
9856
+ "serviceInstanceLease",
9857
+ "service_instance_lease"
9858
+ ]);
9128
9859
  const serviceInstanceTransportRows = readDirectArrayPayload(candidate, [
9129
9860
  "serviceInstanceTransports",
9130
9861
  "service_instance_transports",
@@ -9155,6 +9886,12 @@ var ServiceRegistry = class _ServiceRegistry {
9155
9886
  seenServiceInstances,
9156
9887
  (row) => String(row.uuid ?? "").trim()
9157
9888
  );
9889
+ pushUnique(
9890
+ serviceInstanceLeaseRows,
9891
+ serviceInstanceLeases,
9892
+ seenServiceInstanceLeases,
9893
+ (row) => String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
9894
+ );
9158
9895
  pushUnique(
9159
9896
  serviceInstanceTransportRows,
9160
9897
  serviceInstanceTransports,
@@ -9217,6 +9954,17 @@ var ServiceRegistry = class _ServiceRegistry {
9217
9954
  );
9218
9955
  continue;
9219
9956
  }
9957
+ if (row.status !== void 0 && (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0)) {
9958
+ pushUnique(
9959
+ [row],
9960
+ serviceInstanceLeases,
9961
+ seenServiceInstanceLeases,
9962
+ (entry) => String(
9963
+ entry.service_instance_id ?? entry.serviceInstanceId ?? ""
9964
+ ).trim()
9965
+ );
9966
+ continue;
9967
+ }
9220
9968
  if (row.service_instance_id !== void 0 || row.serviceInstanceId !== void 0) {
9221
9969
  pushUnique(
9222
9970
  [row],
@@ -9245,12 +9993,16 @@ var ServiceRegistry = class _ServiceRegistry {
9245
9993
  }
9246
9994
  }
9247
9995
  }
9996
+ const mergedServiceInstances = overlayServiceInstancesWithLeases(
9997
+ serviceInstances,
9998
+ serviceInstanceLeases
9999
+ );
9248
10000
  const activeServiceInstanceIds = new Set(
9249
- serviceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
10001
+ mergedServiceInstances.filter((row) => row.is_active === true || row.isActive === true).map((row) => String(row.uuid ?? "").trim()).filter((uuid10) => uuid10.length > 0)
9250
10002
  );
9251
- const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? serviceInstances.filter(
10003
+ const filteredServiceInstances = activeServiceInstanceIds.size > 0 ? mergedServiceInstances.filter(
9252
10004
  (row) => activeServiceInstanceIds.has(String(row.uuid ?? "").trim())
9253
- ) : serviceInstances;
10005
+ ) : mergedServiceInstances;
9254
10006
  const filteredServiceInstanceTransports = activeServiceInstanceIds.size > 0 ? serviceInstanceTransports.filter(
9255
10007
  (row) => activeServiceInstanceIds.has(
9256
10008
  String(row.service_instance_id ?? row.serviceInstanceId ?? "").trim()
@@ -9294,6 +10046,22 @@ var ServiceRegistry = class _ServiceRegistry {
9294
10046
  row.version ?? 1
9295
10047
  ).trim()}`
9296
10048
  );
10049
+ pushUnique(
10050
+ explodedManifest.helpers,
10051
+ helpers,
10052
+ seenHelpers,
10053
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10054
+ row.version ?? 1
10055
+ ).trim()}`
10056
+ );
10057
+ pushUnique(
10058
+ explodedManifest.globals,
10059
+ globals,
10060
+ seenGlobals,
10061
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.name ?? "").trim()}|${String(
10062
+ row.version ?? 1
10063
+ ).trim()}`
10064
+ );
9297
10065
  pushUnique(
9298
10066
  explodedManifest.signals,
9299
10067
  signals,
@@ -9354,6 +10122,50 @@ var ServiceRegistry = class _ServiceRegistry {
9354
10122
  row.task_version ?? 1
9355
10123
  ).trim()}`
9356
10124
  );
10125
+ pushUnique(
10126
+ explodedManifest.taskToHelperMaps,
10127
+ taskToHelperMaps,
10128
+ seenTaskToHelperMaps,
10129
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10130
+ row.task_version ?? 1
10131
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10132
+ row.helper_name ?? ""
10133
+ ).trim()}|${String(row.helper_version ?? 1).trim()}`
10134
+ );
10135
+ pushUnique(
10136
+ explodedManifest.helperToHelperMaps,
10137
+ helperToHelperMaps,
10138
+ seenHelperToHelperMaps,
10139
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10140
+ row.helper_name ?? ""
10141
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10142
+ row.alias ?? ""
10143
+ ).trim()}|${String(row.dependency_helper_name ?? "").trim()}|${String(
10144
+ row.dependency_helper_version ?? 1
10145
+ ).trim()}`
10146
+ );
10147
+ pushUnique(
10148
+ explodedManifest.taskToGlobalMaps,
10149
+ taskToGlobalMaps,
10150
+ seenTaskToGlobalMaps,
10151
+ (row) => `${String(row.service_name ?? "").trim()}|${String(row.task_name ?? "").trim()}|${String(
10152
+ row.task_version ?? 1
10153
+ ).trim()}|${String(row.alias ?? "").trim()}|${String(
10154
+ row.global_name ?? ""
10155
+ ).trim()}|${String(row.global_version ?? 1).trim()}`
10156
+ );
10157
+ pushUnique(
10158
+ explodedManifest.helperToGlobalMaps,
10159
+ helperToGlobalMaps,
10160
+ seenHelperToGlobalMaps,
10161
+ (row) => `${String(row.service_name ?? "").trim()}|${String(
10162
+ row.helper_name ?? ""
10163
+ ).trim()}|${String(row.helper_version ?? 1).trim()}|${String(
10164
+ row.alias ?? ""
10165
+ ).trim()}|${String(row.global_name ?? "").trim()}|${String(
10166
+ row.global_version ?? 1
10167
+ ).trim()}`
10168
+ );
9357
10169
  if (!hasExplicitSignalRoutingRows) {
9358
10170
  pushUnique(
9359
10171
  explodedManifest.signalToTaskMaps,
@@ -9380,9 +10192,12 @@ var ServiceRegistry = class _ServiceRegistry {
9380
10192
  }
9381
10193
  return {
9382
10194
  serviceInstances: filteredServiceInstances,
10195
+ serviceInstanceLeases,
9383
10196
  serviceInstanceTransports: filteredServiceInstanceTransports,
9384
10197
  serviceManifests,
9385
10198
  tasks,
10199
+ helpers,
10200
+ globals,
9386
10201
  signals,
9387
10202
  intents,
9388
10203
  actors,
@@ -9390,6 +10205,10 @@ var ServiceRegistry = class _ServiceRegistry {
9390
10205
  directionalTaskMaps,
9391
10206
  actorTaskMaps,
9392
10207
  taskToRoutineMaps,
10208
+ taskToHelperMaps,
10209
+ helperToHelperMaps,
10210
+ taskToGlobalMaps,
10211
+ helperToGlobalMaps,
9393
10212
  signalToTaskMaps: filteredSignalToTaskMaps,
9394
10213
  intentToTaskMaps: filteredIntentToTaskMaps
9395
10214
  };
@@ -9815,35 +10634,37 @@ var ServiceRegistry = class _ServiceRegistry {
9815
10634
  ...context,
9816
10635
  __error: "Authority bootstrap route is not established yet. Waiting for authority handshake.",
9817
10636
  errored: true
9818
- };
9819
- }
9820
- const controller = typeof AbortController === "function" ? new AbortController() : null;
9821
- const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
9822
- try {
9823
- const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
9824
- const requestBody = stripDelegationRequestSnapshot(
9825
- ensureDelegationContextMetadata(
9826
- attachDelegationRequestSnapshot({
9827
- ...sanitizedContext,
9828
- __remoteRoutineName: remoteRoutineName,
9829
- __serviceName: "CadenzaDB",
9830
- __localServiceName: this.serviceName,
9831
- __timeout: timeoutMs,
9832
- __syncing: true,
9833
- __transportOrigin: target.origin,
9834
- __transportProtocol: "rest",
9835
- __transportProtocols: ["rest"],
9836
- __routeKey: target.routeKey,
9837
- routeKey: target.routeKey,
9838
- __fetchId: target.fetchId,
9839
- fetchId: target.fetchId,
9840
- __metadata: {
9841
- ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
10637
+ };
10638
+ }
10639
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
10640
+ const timeoutId = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
10641
+ try {
10642
+ const sanitizedContext = sanitizeAuthorityBootstrapDelegationContext(context);
10643
+ const requestBody = compactAuthorityBootstrapRequestBody(
10644
+ stripDelegationRequestSnapshot(
10645
+ ensureDelegationContextMetadata(
10646
+ attachDelegationRequestSnapshot({
10647
+ ...sanitizedContext,
10648
+ __remoteRoutineName: remoteRoutineName,
10649
+ __serviceName: "CadenzaDB",
10650
+ __localServiceName: this.serviceName,
9842
10651
  __timeout: timeoutMs,
9843
10652
  __syncing: true,
9844
- __authorityBootstrapChannel: true
9845
- }
9846
- })
10653
+ __transportOrigin: target.origin,
10654
+ __transportProtocol: "rest",
10655
+ __transportProtocols: ["rest"],
10656
+ __routeKey: target.routeKey,
10657
+ routeKey: target.routeKey,
10658
+ __fetchId: target.fetchId,
10659
+ fetchId: target.fetchId,
10660
+ __metadata: {
10661
+ ...sanitizedContext.__metadata && typeof sanitizedContext.__metadata === "object" ? sanitizedContext.__metadata : {},
10662
+ __timeout: timeoutMs,
10663
+ __syncing: true,
10664
+ __authorityBootstrapChannel: true
10665
+ }
10666
+ })
10667
+ )
9847
10668
  )
9848
10669
  );
9849
10670
  const response = await globalThis.fetch(`${target.origin}/delegation`, {
@@ -9998,12 +10819,14 @@ var ServiceRegistry = class _ServiceRegistry {
9998
10819
  };
9999
10820
  const [
10000
10821
  serviceInstances,
10822
+ serviceInstanceLeases,
10001
10823
  serviceInstanceTransports,
10002
10824
  serviceManifests,
10003
10825
  signalToTaskMaps,
10004
10826
  intentToTaskMaps
10005
10827
  ] = await Promise.all([
10006
10828
  DatabaseController.instance.queryAuthorityTableRows("service_instance"),
10829
+ queryOptionalAuthorityRoutingRows("service_instance_lease"),
10007
10830
  DatabaseController.instance.queryAuthorityTableRows(
10008
10831
  "service_instance_transport"
10009
10832
  ),
@@ -10016,6 +10839,7 @@ var ServiceRegistry = class _ServiceRegistry {
10016
10839
  __syncing: true,
10017
10840
  ...this.collectBootstrapFullSyncPayload({
10018
10841
  serviceInstances,
10842
+ serviceInstanceLeases,
10019
10843
  serviceInstanceTransports,
10020
10844
  serviceManifests,
10021
10845
  signalToTaskMaps,
@@ -10048,9 +10872,14 @@ var ServiceRegistry = class _ServiceRegistry {
10048
10872
  return false;
10049
10873
  }
10050
10874
  const scheduleRetry = (reason, error) => {
10051
- const delayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
10875
+ const baseDelayMs = SERVICE_COMMUNICATION_PERSIST_RETRY_DELAYS_MS[descriptor.retryAttempt];
10052
10876
  const nextAttempt = descriptor.retryAttempt + 1;
10053
- if (delayMs !== void 0) {
10877
+ if (baseDelayMs !== void 0) {
10878
+ const delayMs = buildDeterministicJitteredDelayMs(
10879
+ baseDelayMs,
10880
+ this.serviceCommunicationRetryJitterRatio,
10881
+ `${descriptor.serviceInstanceId}:${descriptor.communicationType}:${descriptor.retryAttempt}`
10882
+ );
10054
10883
  CadenzaService.schedule(
10055
10884
  retrySignal,
10056
10885
  buildServiceCommunicationRetryContext({
@@ -10198,6 +11027,31 @@ var ServiceRegistry = class _ServiceRegistry {
10198
11027
  })
10199
11028
  );
10200
11029
  }
11030
+ buildDeterministicInstanceJitterKey(scope) {
11031
+ const serviceName = String(this.serviceName ?? "").trim() || "unknown-service";
11032
+ const serviceInstanceId = String(this.serviceInstanceId ?? "").trim() || "pending-instance";
11033
+ return `${serviceName}:${serviceInstanceId}:${scope}`;
11034
+ }
11035
+ buildJitteredIntervalStartDate(intervalMs, scope) {
11036
+ const jitterOffsetMs = buildDeterministicJitterOffsetMs(
11037
+ intervalMs,
11038
+ this.runtimeStatusLoopJitterRatio,
11039
+ this.buildDeterministicInstanceJitterKey(scope)
11040
+ );
11041
+ if (jitterOffsetMs <= 0) {
11042
+ return void 0;
11043
+ }
11044
+ return new Date(Date.now() + intervalMs + jitterOffsetMs);
11045
+ }
11046
+ buildJitteredBootstrapRetryDelayMs(baseDelayMs, attempt) {
11047
+ return buildDeterministicJitteredDelayMs(
11048
+ baseDelayMs,
11049
+ this.bootstrapFullSyncRetryJitterRatio,
11050
+ this.buildDeterministicInstanceJitterKey(
11051
+ `bootstrap-full-sync-retry-${attempt}`
11052
+ )
11053
+ );
11054
+ }
10201
11055
  ensureAuthorityBootstrapSignalTransmissions() {
10202
11056
  if (this.serviceName !== "CadenzaDB") {
10203
11057
  return false;
@@ -10275,8 +11129,11 @@ var ServiceRegistry = class _ServiceRegistry {
10275
11129
  }
10276
11130
  const retryGeneration = this.bootstrapFullSyncRetryGeneration;
10277
11131
  const retryReason = this.bootstrapFullSyncRetryReason ?? "service_registry_bootstrap_retry";
10278
- const delayMs = EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex];
10279
11132
  const attempt = this.bootstrapFullSyncRetryIndex + 1;
11133
+ const delayMs = this.buildJitteredBootstrapRetryDelayMs(
11134
+ EARLY_FULL_SYNC_DELAYS_MS[this.bootstrapFullSyncRetryIndex],
11135
+ attempt
11136
+ );
10280
11137
  this.bootstrapFullSyncRetryIndex += 1;
10281
11138
  this.bootstrapFullSyncRetryTimer = setTimeout(() => {
10282
11139
  this.bootstrapFullSyncRetryTimer = null;
@@ -12179,6 +13036,18 @@ var ServiceRegistry = class _ServiceRegistry {
12179
13036
  isNonResponsive,
12180
13037
  isBlocked
12181
13038
  );
13039
+ const cpuUsage = this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad");
13040
+ const memoryUsage = this.readRuntimeStatusMetric(
13041
+ ctx,
13042
+ "memoryUsage",
13043
+ "memory",
13044
+ "memoryPressure"
13045
+ );
13046
+ const eventLoopLag = this.readRuntimeStatusMetric(
13047
+ ctx,
13048
+ "eventLoopLag",
13049
+ "eventLoopLagMs"
13050
+ );
12182
13051
  return {
12183
13052
  serviceName,
12184
13053
  serviceInstanceId,
@@ -12191,22 +13060,20 @@ var ServiceRegistry = class _ServiceRegistry {
12191
13060
  state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
12192
13061
  acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
12193
13062
  numberOfRunningGraphs,
12194
- cpuUsage: this.readRuntimeStatusMetric(ctx, "cpuUsage", "cpu", "cpuLoad"),
12195
- memoryUsage: this.readRuntimeStatusMetric(
12196
- ctx,
12197
- "memoryUsage",
12198
- "memory",
12199
- "memoryPressure"
12200
- ),
12201
- eventLoopLag: this.readRuntimeStatusMetric(
12202
- ctx,
12203
- "eventLoopLag",
12204
- "eventLoopLagMs"
12205
- ),
13063
+ cpuUsage,
13064
+ memoryUsage,
13065
+ eventLoopLag,
12206
13066
  isActive,
12207
13067
  isNonResponsive,
12208
13068
  isBlocked,
12209
- health: ctx.health ?? ctx.__health ?? {}
13069
+ health: sanitizeAuthorityRuntimeStatusHealth(ctx.health ?? ctx.__health, {
13070
+ state: ctx.state === "healthy" || ctx.state === "degraded" || ctx.state === "overloaded" || ctx.state === "unavailable" ? ctx.state : resolved.state,
13071
+ acceptingWork: typeof ctx.acceptingWork === "boolean" ? ctx.acceptingWork : resolved.acceptingWork,
13072
+ reportedAt: ctx.reportedAt ?? (typeof ctx.__reportedAt === "string" ? ctx.__reportedAt : void 0) ?? (/* @__PURE__ */ new Date()).toISOString(),
13073
+ cpuUsage,
13074
+ memoryUsage,
13075
+ eventLoopLag
13076
+ })
12210
13077
  };
12211
13078
  }
12212
13079
  applyRuntimeStatusReport(report) {
@@ -12247,12 +13114,14 @@ var ServiceRegistry = class _ServiceRegistry {
12247
13114
  instance.isFrontend = report.isFrontend;
12248
13115
  }
12249
13116
  instance.numberOfRunningGraphs = report.numberOfRunningGraphs;
12250
- const runtimeMetricsHealth = {
13117
+ const runtimeStatusHealth = sanitizeAuthorityRuntimeStatusHealth(report.health, {
13118
+ state: report.state,
13119
+ acceptingWork: report.acceptingWork,
13120
+ reportedAt: report.reportedAt,
12251
13121
  cpuUsage: report.cpuUsage ?? null,
12252
13122
  memoryUsage: report.memoryUsage ?? null,
12253
- eventLoopLag: report.eventLoopLag ?? null,
12254
- runtimeMetrics: report.health?.runtimeMetrics && typeof report.health.runtimeMetrics === "object" ? report.health.runtimeMetrics : void 0
12255
- };
13123
+ eventLoopLag: report.eventLoopLag ?? null
13124
+ });
12256
13125
  instance.isActive = report.isActive;
12257
13126
  instance.isNonResponsive = report.isNonResponsive;
12258
13127
  instance.isBlocked = report.isBlocked;
@@ -12261,13 +13130,7 @@ var ServiceRegistry = class _ServiceRegistry {
12261
13130
  instance.reportedAt = report.reportedAt;
12262
13131
  instance.health = {
12263
13132
  ...instance.health ?? {},
12264
- ...report.health ?? {},
12265
- ...runtimeMetricsHealth,
12266
- runtimeStatus: {
12267
- state: report.state,
12268
- acceptingWork: report.acceptingWork,
12269
- reportedAt: report.reportedAt
12270
- }
13133
+ ...runtimeStatusHealth ?? {}
12271
13134
  };
12272
13135
  this.lastHeartbeatAtByInstance.set(report.serviceInstanceId, Date.now());
12273
13136
  this.missedHeartbeatsByInstance.set(report.serviceInstanceId, 0);
@@ -12439,15 +13302,20 @@ var ServiceRegistry = class _ServiceRegistry {
12439
13302
  isActive: snapshot.isActive,
12440
13303
  isNonResponsive: snapshot.isNonResponsive,
12441
13304
  isBlocked: snapshot.isBlocked,
12442
- health: {
12443
- ...localInstance.health ?? {},
12444
- ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {},
12445
- runtimeStatus: {
13305
+ health: sanitizeAuthorityRuntimeStatusHealth(
13306
+ {
13307
+ ...localInstance.health ?? {},
13308
+ ...this.buildRuntimeMetricsHealthPayload(runtimeMetricsSnapshot) ?? {}
13309
+ },
13310
+ {
12446
13311
  state: snapshot.state,
12447
13312
  acceptingWork: snapshot.acceptingWork,
12448
- reportedAt
13313
+ reportedAt,
13314
+ cpuUsage: runtimeMetricsSnapshot?.cpuUsage ?? null,
13315
+ memoryUsage: runtimeMetricsSnapshot?.memoryUsage ?? null,
13316
+ eventLoopLag: runtimeMetricsSnapshot?.eventLoopLag ?? null
12449
13317
  }
12450
- }
13318
+ )
12451
13319
  };
12452
13320
  this.applyRuntimeStatusReport(report);
12453
13321
  return detailLevel === "full" ? report : this.stripRuntimeStatusReportForPeer(report);
@@ -12801,6 +13669,32 @@ var ServiceRegistry = class _ServiceRegistry {
12801
13669
  if (!instancePersisted) {
12802
13670
  return false;
12803
13671
  }
13672
+ await this.delegateAuthorityLifecycleUpdate(
13673
+ "Update service_instance_lease",
13674
+ {
13675
+ reason,
13676
+ graceful: true,
13677
+ data: {
13678
+ status: "inactive",
13679
+ is_ready: false,
13680
+ readiness_reason: "graceful_shutdown",
13681
+ lease_expires_at: reportedAt,
13682
+ last_lease_renewed_at: reportedAt,
13683
+ last_ready_at: null,
13684
+ last_observed_transport_at: reportedAt,
13685
+ shutdown_requested_at: reportedAt,
13686
+ deleted: false,
13687
+ modified: reportedAt
13688
+ },
13689
+ queryData: {
13690
+ filter: {
13691
+ service_instance_id: localInstance.uuid
13692
+ }
13693
+ },
13694
+ __serviceInstanceId: localInstance.uuid
13695
+ },
13696
+ Math.max(1e3, timeoutMs)
13697
+ );
12804
13698
  for (const transport of localInstance.transports) {
12805
13699
  if (!isPersistedUuid(transport.uuid)) {
12806
13700
  continue;
@@ -12952,6 +13846,7 @@ var ServiceRegistry = class _ServiceRegistry {
12952
13846
  };
12953
13847
  }
12954
13848
  reset() {
13849
+ this.clearBootstrapFullSyncRetryTimer();
12955
13850
  this.instances.clear();
12956
13851
  this.deputies.clear();
12957
13852
  this.remoteSignals.clear();
@@ -12975,6 +13870,23 @@ var ServiceRegistry = class _ServiceRegistry {
12975
13870
  this.lastRuntimeStatusSnapshot = null;
12976
13871
  this.isFrontend = false;
12977
13872
  this.localInstanceSeed = null;
13873
+ this.bootstrapFullSyncRetryIndex = 0;
13874
+ this.bootstrapFullSyncRetryGeneration = 0;
13875
+ this.bootstrapFullSyncSatisfied = false;
13876
+ this.bootstrapFullSyncRetryReason = null;
13877
+ this.knownGlobalSignalMaps.clear();
13878
+ this.authorityBootstrapRoute = {
13879
+ origin: null,
13880
+ role: "internal",
13881
+ routeKey: null,
13882
+ fetchId: null,
13883
+ serviceInstanceId: null,
13884
+ serviceTransportId: null,
13885
+ handshakeEstablished: false
13886
+ };
13887
+ this.authorityBootstrapHandshakeInFlight = false;
13888
+ this.authorityFullSyncResponderTask = null;
13889
+ this.authorityServiceCommunicationPersistenceTask = null;
12978
13890
  }
12979
13891
  };
12980
13892
 
@@ -13083,7 +13995,25 @@ var SignalTransmissionTask = class extends Task2 {
13083
13995
  ...ctx
13084
13996
  })
13085
13997
  );
13086
- return this.taskFunction(deputyContext, emit2, inquire, progressCallback);
13998
+ const resolvedTools = typeof CadenzaService.resolveToolsForOwner === "function" ? CadenzaService.resolveToolsForOwner(
13999
+ this,
14000
+ deputyContext,
14001
+ emit2,
14002
+ inquire,
14003
+ progressCallback
14004
+ ) : {
14005
+ helpers: {},
14006
+ globals: {}
14007
+ };
14008
+ const resolvedProgressCallback = typeof progressCallback === "function" ? progressCallback : () => {
14009
+ };
14010
+ return this.taskFunction(
14011
+ deputyContext,
14012
+ emit2,
14013
+ inquire,
14014
+ resolvedTools,
14015
+ resolvedProgressCallback
14016
+ );
13087
14017
  }
13088
14018
  };
13089
14019
 
@@ -13412,16 +14342,16 @@ var RestController = class _RestController {
13412
14342
  };
13413
14343
  CadenzaService.createEphemeralMetaTask(
13414
14344
  "Resolve delegation",
13415
- (endCtx) => resolveDelegation(endCtx, "success"),
14345
+ (endCtx) => resolveDelegation(
14346
+ endCtx,
14347
+ endCtx?.errored || endCtx?.failed ? "error" : "success"
14348
+ ),
13416
14349
  "Resolves a delegation request",
13417
14350
  { register: false }
13418
- ).doOn(`meta.node.graph_completed:${deputyExecId}`).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
13419
- CadenzaService.createEphemeralMetaTask(
13420
- "Resolve delegation target lookup failure",
13421
- (endCtx) => resolveDelegation(endCtx, "error"),
13422
- "Resolves delegation requests that cannot find a local task or routine",
13423
- { register: false }
13424
- ).doOn(targetNotFoundSignal);
14351
+ ).doOn(
14352
+ `meta.node.graph_completed:${deputyExecId}`,
14353
+ targetNotFoundSignal
14354
+ ).emits(`meta.rest.delegation_resolved:${deputyExecId}`);
13425
14355
  if (!CadenzaService.get(remoteRoutineName) && !CadenzaService.registry.routines.get(remoteRoutineName)) {
13426
14356
  CadenzaService.emit(targetNotFoundSignal, {
13427
14357
  ...ctx2,
@@ -16412,7 +17342,7 @@ var SignalController = class _SignalController {
16412
17342
  }
16413
17343
  const traceContext = { ...ctx };
16414
17344
  delete traceContext.__traceCreatedBySignalBroker;
16415
- const sanitizedTraceContext = stripLocalRoutinePersistenceHints(traceContext);
17345
+ const sanitizedTraceContext = sanitizeExecutionPersistenceContext(traceContext);
16416
17346
  const routineMetadata = resolveRoutinePersistenceMetadata(traceContext);
16417
17347
  const { context: routineContext, metaContext: routineMetaContext } = splitRoutinePersistenceContext(traceContext);
16418
17348
  const traceCreatedBySignalBroker = ctx.__traceCreatedBySignalBroker === true || signalEmission.__traceCreatedBySignalBroker === true;
@@ -17096,6 +18026,16 @@ function buildActorRegistrationData(actor) {
17096
18026
  version: 1
17097
18027
  };
17098
18028
  }
18029
+ function sanitizePersistedTaskSourceFields(task, data) {
18030
+ if (!task.isMeta && !task.isDeputy) {
18031
+ return data;
18032
+ }
18033
+ return {
18034
+ ...data,
18035
+ function_string: "",
18036
+ tag_id_getter: null
18037
+ };
18038
+ }
17099
18039
  function resolveSyncServiceName(task) {
17100
18040
  const ownerServiceName = typeof task?.ownerServiceName === "string" ? task.ownerServiceName.trim() : "";
17101
18041
  const taskServiceName = typeof task?.serviceName === "string" ? task.serviceName.trim() : "";
@@ -18213,40 +19153,41 @@ var GraphSyncController = class _GraphSyncController {
18213
19153
  if (task.registered) continue;
18214
19154
  const { __functionString, __getTagCallback } = task.export();
18215
19155
  this.tasksSynced = false;
19156
+ const taskRegistrationData = sanitizePersistedTaskSourceFields(task, {
19157
+ name: task.name,
19158
+ version: task.version,
19159
+ description: task.description,
19160
+ function_string: __functionString,
19161
+ tag_id_getter: __getTagCallback,
19162
+ layer_index: task.layerIndex,
19163
+ concurrency: task.concurrency,
19164
+ timeout: task.timeout,
19165
+ is_unique: task.isUnique,
19166
+ is_signal: task.isSignal,
19167
+ is_throttled: task.isThrottled,
19168
+ is_debounce: task.isDebounce,
19169
+ is_ephemeral: task.isEphemeral,
19170
+ is_meta: task.isMeta,
19171
+ is_sub_meta: task.isSubMeta,
19172
+ is_hidden: task.isHidden,
19173
+ validate_input_context: task.validateInputContext,
19174
+ validate_output_context: task.validateOutputContext,
19175
+ retry_count: task.retryCount,
19176
+ retry_delay: task.retryDelay,
19177
+ retry_delay_max: task.retryDelayMax,
19178
+ retry_delay_factor: task.retryDelayFactor,
19179
+ service_name: serviceName2,
19180
+ signals: {
19181
+ emits: Array.from(task.emitsSignals),
19182
+ signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
19183
+ signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
19184
+ observed: Array.from(task.observedSignals)
19185
+ },
19186
+ intents: Array.from(task.handlesIntents)
19187
+ });
18216
19188
  yield {
18217
19189
  __syncing: ctx.__syncing,
18218
- data: {
18219
- name: task.name,
18220
- version: task.version,
18221
- description: task.description,
18222
- function_string: __functionString,
18223
- tag_id_getter: __getTagCallback,
18224
- layer_index: task.layerIndex,
18225
- concurrency: task.concurrency,
18226
- timeout: task.timeout,
18227
- is_unique: task.isUnique,
18228
- is_signal: task.isSignal,
18229
- is_throttled: task.isThrottled,
18230
- is_debounce: task.isDebounce,
18231
- is_ephemeral: task.isEphemeral,
18232
- is_meta: task.isMeta,
18233
- is_sub_meta: task.isSubMeta,
18234
- is_hidden: task.isHidden,
18235
- validate_input_context: task.validateInputContext,
18236
- validate_output_context: task.validateOutputContext,
18237
- retry_count: task.retryCount,
18238
- retry_delay: task.retryDelay,
18239
- retry_delay_max: task.retryDelayMax,
18240
- retry_delay_factor: task.retryDelayFactor,
18241
- service_name: serviceName2,
18242
- signals: {
18243
- emits: Array.from(task.emitsSignals),
18244
- signalsToEmitAfter: Array.from(task.signalsToEmitAfter),
18245
- signalsToEmitOnFail: Array.from(task.signalsToEmitOnFail),
18246
- observed: Array.from(task.observedSignals)
18247
- },
18248
- intents: Array.from(task.handlesIntents)
18249
- },
19190
+ data: taskRegistrationData,
18250
19191
  __taskName: task.name
18251
19192
  };
18252
19193
  }
@@ -19405,13 +20346,50 @@ var GraphSyncController = class _GraphSyncController {
19405
20346
  startActorPrimitiveSyncTask,
19406
20347
  startRoutinePrimitiveSyncTask
19407
20348
  );
19408
- const getAllTasksForSyncTask = CadenzaService.registry.getAllTasks.clone();
20349
+ const getAllTasksForSyncTask = CadenzaService.createMetaTask(
20350
+ "Get all tasks for sync",
20351
+ (ctx) => ({
20352
+ ...ctx,
20353
+ tasks: Array.from(CadenzaService.registry.tasks.values())
20354
+ }),
20355
+ "Collects local tasks for the primitive sync phase.",
20356
+ {
20357
+ register: false,
20358
+ isHidden: true
20359
+ }
20360
+ );
19409
20361
  startTaskPrimitiveSyncTask.then(
19410
20362
  getAllTasksForSyncTask,
19411
20363
  gatherTaskRegistrationTask
19412
20364
  );
19413
20365
  getAllTasksForSyncTask.then(this.splitTasksForRegistration);
19414
- const getSignalsForSyncTask = CadenzaService.signalBroker.getSignalsTask.clone();
20366
+ const getSignalsForSyncTask = CadenzaService.createMetaTask(
20367
+ "Get signals for sync",
20368
+ (ctx) => {
20369
+ const uniqueSignals = Array.from(
20370
+ /* @__PURE__ */ new Set([
20371
+ ...CadenzaService.signalBroker.signalObservers.keys(),
20372
+ ...CadenzaService.signalBroker.emittedSignalsRegistry
20373
+ ])
20374
+ ).filter((signal) => !signal.includes(":"));
20375
+ const processedSignals = uniqueSignals.map((signal) => ({
20376
+ signal,
20377
+ data: {
20378
+ registered: CadenzaService.signalBroker.signalObservers.get(signal)?.registered ?? false,
20379
+ metadata: CadenzaService.signalBroker.getSignalMetadata(signal) ?? null
20380
+ }
20381
+ }));
20382
+ return {
20383
+ ...ctx,
20384
+ signals: processedSignals
20385
+ };
20386
+ },
20387
+ "Collects local signals for the primitive sync phase.",
20388
+ {
20389
+ register: false,
20390
+ isHidden: true
20391
+ }
20392
+ );
19415
20393
  startSignalPrimitiveSyncTask.then(
19416
20394
  getSignalsForSyncTask,
19417
20395
  gatherSignalRegistrationTask
@@ -19453,40 +20431,110 @@ var GraphSyncController = class _GraphSyncController {
19453
20431
  gatherActorRegistrationTask
19454
20432
  );
19455
20433
  getAllActorsForSyncTask.then(this.splitActorsForRegistration);
19456
- const getAllRoutinesForSyncTask = CadenzaService.registry.getAllRoutines.clone();
20434
+ const getAllRoutinesForSyncTask = CadenzaService.createMetaTask(
20435
+ "Get all routines for sync",
20436
+ (ctx) => ({
20437
+ ...ctx,
20438
+ routines: Array.from(CadenzaService.registry.routines.values())
20439
+ }),
20440
+ "Collects local routines for the primitive sync phase.",
20441
+ {
20442
+ register: false,
20443
+ isHidden: true
20444
+ }
20445
+ );
19457
20446
  startRoutinePrimitiveSyncTask.then(
19458
20447
  getAllRoutinesForSyncTask,
19459
20448
  gatherRoutineRegistrationTask
19460
20449
  );
19461
20450
  getAllRoutinesForSyncTask.then(this.splitRoutinesTask);
19462
- const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20451
+ const iterateTasksForDirectionalTaskMapSyncTask = CadenzaService.createMetaTask(
20452
+ "Iterate tasks for directional task map sync",
20453
+ function* (ctx) {
20454
+ for (const task of CadenzaService.registry.tasks.values()) {
20455
+ yield { ...ctx, task };
20456
+ }
20457
+ },
20458
+ "Iterates local tasks for directional task-map sync.",
20459
+ {
20460
+ register: false,
20461
+ isHidden: true
20462
+ }
20463
+ );
19463
20464
  startDirectionalTaskMapSyncTask.then(
19464
20465
  iterateTasksForDirectionalTaskMapSyncTask,
19465
20466
  gatherDirectionalTaskMapRegistrationTask
19466
20467
  );
19467
20468
  iterateTasksForDirectionalTaskMapSyncTask.then(this.registerTaskMapTask);
19468
20469
  recordTaskMapRegistrationTask.then(gatherDirectionalTaskMapRegistrationTask);
19469
- const iterateTasksForSignalTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20470
+ const iterateTasksForSignalTaskMapSyncTask = CadenzaService.createMetaTask(
20471
+ "Iterate tasks for signal task map sync",
20472
+ function* (ctx) {
20473
+ for (const task of CadenzaService.registry.tasks.values()) {
20474
+ yield { ...ctx, task };
20475
+ }
20476
+ },
20477
+ "Iterates local tasks for signal-to-task map sync.",
20478
+ {
20479
+ register: false,
20480
+ isHidden: true
20481
+ }
20482
+ );
19470
20483
  startSignalTaskMapSyncTask.then(
19471
20484
  iterateTasksForSignalTaskMapSyncTask,
19472
20485
  gatherSignalTaskMapRegistrationTask
19473
20486
  );
19474
20487
  iterateTasksForSignalTaskMapSyncTask.then(this.registerSignalToTaskMapTask);
19475
20488
  this.registerSignalToTaskMapTask.then(gatherSignalTaskMapRegistrationTask);
19476
- const iterateTasksForIntentTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20489
+ const iterateTasksForIntentTaskMapSyncTask = CadenzaService.createMetaTask(
20490
+ "Iterate tasks for intent task map sync",
20491
+ function* (ctx) {
20492
+ for (const task of CadenzaService.registry.tasks.values()) {
20493
+ yield { ...ctx, task };
20494
+ }
20495
+ },
20496
+ "Iterates local tasks for intent-to-task map sync.",
20497
+ {
20498
+ register: false,
20499
+ isHidden: true
20500
+ }
20501
+ );
19477
20502
  startIntentTaskMapSyncTask.then(
19478
20503
  iterateTasksForIntentTaskMapSyncTask,
19479
20504
  gatherIntentTaskMapRegistrationTask
19480
20505
  );
19481
20506
  iterateTasksForIntentTaskMapSyncTask.then(this.registerIntentToTaskMapTask);
19482
20507
  this.registerIntentToTaskMapTask.then(gatherIntentTaskMapRegistrationTask);
19483
- const iterateTasksForActorTaskMapSyncTask = CadenzaService.registry.doForEachTask.clone();
20508
+ const iterateTasksForActorTaskMapSyncTask = CadenzaService.createMetaTask(
20509
+ "Iterate tasks for actor task map sync",
20510
+ function* (ctx) {
20511
+ for (const task of CadenzaService.registry.tasks.values()) {
20512
+ yield { ...ctx, task };
20513
+ }
20514
+ },
20515
+ "Iterates local tasks for actor-to-task map sync.",
20516
+ {
20517
+ register: false,
20518
+ isHidden: true
20519
+ }
20520
+ );
19484
20521
  startActorTaskMapSyncTask.then(
19485
20522
  iterateTasksForActorTaskMapSyncTask,
19486
20523
  gatherActorTaskMapRegistrationTask
19487
20524
  );
19488
20525
  iterateTasksForActorTaskMapSyncTask.then(this.registerActorTaskMapTask);
19489
- const getAllRoutinesForTaskMapSyncTask = CadenzaService.registry.getAllRoutines.clone();
20526
+ const getAllRoutinesForTaskMapSyncTask = CadenzaService.createMetaTask(
20527
+ "Get all routines for task map sync",
20528
+ (ctx) => ({
20529
+ ...ctx,
20530
+ routines: Array.from(CadenzaService.registry.routines.values())
20531
+ }),
20532
+ "Collects local routines for routine-to-task map sync.",
20533
+ {
20534
+ register: false,
20535
+ isHidden: true
20536
+ }
20537
+ );
19490
20538
  startRoutineTaskMapSyncTask.then(
19491
20539
  getAllRoutinesForTaskMapSyncTask,
19492
20540
  gatherRoutineTaskMapRegistrationTask
@@ -19562,11 +20610,37 @@ function resolveTaskByName(name) {
19562
20610
  const taskName = String(name ?? "");
19563
20611
  return taskName ? CadenzaService.get(taskName) : void 0;
19564
20612
  }
20613
+ function resolveHelperFromMetadataContext(ctx) {
20614
+ const toolRuntime = CadenzaService;
20615
+ const helperName = String(
20616
+ ctx?.helperName ?? ctx?.data?.helperName ?? ctx?.data?.helper_name ?? ctx?.filter?.helperName ?? ctx?.filter?.helper_name ?? ""
20617
+ );
20618
+ return helperName ? toolRuntime.getHelper?.(helperName) : void 0;
20619
+ }
20620
+ function resolveGlobalFromMetadataContext(ctx) {
20621
+ const toolRuntime = CadenzaService;
20622
+ const globalName = String(
20623
+ ctx?.globalName ?? ctx?.data?.globalName ?? ctx?.data?.global_name ?? ctx?.filter?.globalName ?? ctx?.filter?.global_name ?? ""
20624
+ );
20625
+ return globalName ? toolRuntime.getGlobal?.(globalName) : void 0;
20626
+ }
19565
20627
  function resolvePredecessorTaskFromMetadataContext(ctx) {
19566
20628
  return resolveTaskByName(
19567
20629
  ctx?.predecessorTaskName ?? ctx?.data?.predecessorTaskName ?? ctx?.data?.predecessor_task_name ?? ctx?.filter?.predecessorTaskName ?? ctx?.filter?.predecessor_task_name
19568
20630
  );
19569
20631
  }
20632
+ function sanitizePersistedTaskSourceFields2(task, data) {
20633
+ if (!task?.isMeta && !task?.isDeputy) {
20634
+ return data;
20635
+ }
20636
+ return {
20637
+ ...data,
20638
+ functionString: "",
20639
+ function_string: "",
20640
+ tagIdGetter: null,
20641
+ tag_id_getter: null
20642
+ };
20643
+ }
19570
20644
  function shouldSkipDirectTaskMetadata(task) {
19571
20645
  return !task || !task.register || task.isHidden || task.isDeputy;
19572
20646
  }
@@ -19644,6 +20718,9 @@ function shouldPersistBusinessInquiryCompletion(ctx) {
19644
20718
  const inquiryName = String(ctx?.data?.metadata?.inquiryMeta?.inquiry ?? "");
19645
20719
  return inquiryName.length > 0 && !isMetaIntentName(inquiryName);
19646
20720
  }
20721
+ function shouldPersistExecutionTrace(ctx) {
20722
+ return ctx?.data?.isMeta !== true && ctx?.data?.is_meta !== true;
20723
+ }
19647
20724
  function shouldPersistRoutineExecution(ctx) {
19648
20725
  if (ctx?.data?.isMeta === true || ctx?.data?.is_meta === true) {
19649
20726
  return false;
@@ -19707,10 +20784,10 @@ var GraphMetadataController = class _GraphMetadataController {
19707
20784
  task.registrationRequested = true;
19708
20785
  }
19709
20786
  return buildDatabaseTriggerContext(
19710
- {
20787
+ sanitizePersistedTaskSourceFields2(task, {
19711
20788
  ...ctx.data,
19712
20789
  serviceName: CadenzaService.serviceRegistry.serviceName
19713
- },
20790
+ }),
19714
20791
  void 0,
19715
20792
  { onConflict },
19716
20793
  { onConflict }
@@ -19813,6 +20890,88 @@ var GraphMetadataController = class _GraphMetadataController {
19813
20890
  serviceName: CadenzaService.serviceRegistry.serviceName
19814
20891
  });
19815
20892
  }).doOn("meta.task.intent_associated").emits("global.meta.graph_metadata.task_intent_associated");
20893
+ const buildHelperMetadataContext = (ctx) => {
20894
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20895
+ return false;
20896
+ }
20897
+ const helper = resolveHelperFromMetadataContext(ctx);
20898
+ if (!helper) {
20899
+ return false;
20900
+ }
20901
+ return buildDatabaseTriggerContext({
20902
+ ...ctx.data,
20903
+ serviceName: CadenzaService.serviceRegistry.serviceName
20904
+ });
20905
+ };
20906
+ createLocalGraphMetadataTask("Handle helper creation", buildHelperMetadataContext).doOn("meta.helper.created").emits("global.meta.graph_metadata.helper_created");
20907
+ createLocalGraphMetadataTask("Handle helper update", buildHelperMetadataContext).doOn("meta.helper.updated").emits("global.meta.graph_metadata.helper_updated");
20908
+ const buildGlobalMetadataContext = (ctx) => {
20909
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20910
+ return false;
20911
+ }
20912
+ const globalDefinition = resolveGlobalFromMetadataContext(ctx);
20913
+ if (!globalDefinition) {
20914
+ return false;
20915
+ }
20916
+ return buildDatabaseTriggerContext({
20917
+ ...ctx.data,
20918
+ serviceName: CadenzaService.serviceRegistry.serviceName
20919
+ });
20920
+ };
20921
+ createLocalGraphMetadataTask("Handle global creation", buildGlobalMetadataContext).doOn("meta.global.created").emits("global.meta.graph_metadata.global_created");
20922
+ createLocalGraphMetadataTask("Handle global update", buildGlobalMetadataContext).doOn("meta.global.updated").emits("global.meta.graph_metadata.global_updated");
20923
+ createLocalGraphMetadataTask("Handle task helper association", (ctx) => {
20924
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20925
+ return false;
20926
+ }
20927
+ const task = resolveTaskFromMetadataContext(ctx);
20928
+ if (shouldSkipDirectTaskMetadata(task)) {
20929
+ return false;
20930
+ }
20931
+ return buildDatabaseTriggerContext({
20932
+ ...ctx.data,
20933
+ serviceName: CadenzaService.serviceRegistry.serviceName
20934
+ });
20935
+ }).doOn("meta.task.helper_associated").emits("global.meta.graph_metadata.task_helper_associated");
20936
+ createLocalGraphMetadataTask("Handle helper helper association", (ctx) => {
20937
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20938
+ return false;
20939
+ }
20940
+ const helper = resolveHelperFromMetadataContext(ctx);
20941
+ if (!helper) {
20942
+ return false;
20943
+ }
20944
+ return buildDatabaseTriggerContext({
20945
+ ...ctx.data,
20946
+ serviceName: CadenzaService.serviceRegistry.serviceName
20947
+ });
20948
+ }).doOn("meta.helper.helper_associated").emits("global.meta.graph_metadata.helper_helper_associated");
20949
+ createLocalGraphMetadataTask("Handle task global association", (ctx) => {
20950
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20951
+ return false;
20952
+ }
20953
+ const task = resolveTaskFromMetadataContext(ctx);
20954
+ if (shouldSkipDirectTaskMetadata(task)) {
20955
+ return false;
20956
+ }
20957
+ return buildDatabaseTriggerContext({
20958
+ ...ctx.data,
20959
+ serviceName: CadenzaService.serviceRegistry.serviceName
20960
+ });
20961
+ }).doOn("meta.task.global_associated").emits("global.meta.graph_metadata.task_global_associated");
20962
+ createLocalGraphMetadataTask("Handle helper global association", (ctx) => {
20963
+ if (!shouldEmitDirectPrimitiveMetadata()) {
20964
+ return false;
20965
+ }
20966
+ const helper = resolveHelperFromMetadataContext(ctx);
20967
+ if (!helper) {
20968
+ return false;
20969
+ }
20970
+ return buildDatabaseTriggerContext({
20971
+ ...ctx.data,
20972
+ serviceName: CadenzaService.serviceRegistry.serviceName
20973
+ });
20974
+ }).doOn("meta.helper.global_associated").emits("global.meta.graph_metadata.helper_global_associated");
19816
20975
  createLocalGraphMetadataTask("Handle task unsubscribing signal", (ctx) => {
19817
20976
  if (!shouldEmitDirectPrimitiveMetadata()) {
19818
20977
  return false;
@@ -19880,6 +21039,9 @@ var GraphMetadataController = class _GraphMetadataController {
19880
21039
  });
19881
21040
  }).doOn("meta.routine.task_added").emits("global.meta.graph_metadata.task_added_to_routine");
19882
21041
  createLocalGraphMetadataTask("Handle new trace", (ctx) => {
21042
+ if (!shouldPersistExecutionTrace(ctx)) {
21043
+ return false;
21044
+ }
19883
21045
  return buildDatabaseTriggerContext({
19884
21046
  ...ctx.data,
19885
21047
  service_name: CadenzaService.serviceRegistry.serviceName,
@@ -19893,10 +21055,10 @@ var GraphMetadataController = class _GraphMetadataController {
19893
21055
  return false;
19894
21056
  }
19895
21057
  const routineData = ctx.data ?? {};
19896
- const sanitizedRoutineContext = stripLocalRoutinePersistenceHints(
21058
+ const sanitizedRoutineContext = sanitizeExecutionPersistenceContext(
19897
21059
  routineData.context ?? {}
19898
21060
  );
19899
- const sanitizedRoutineMetaContext = stripLocalRoutinePersistenceHints(
21061
+ const sanitizedRoutineMetaContext = sanitizeExecutionPersistenceContext(
19900
21062
  routineData.metaContext ?? {}
19901
21063
  );
19902
21064
  const routineExecutionRow = {
@@ -20031,12 +21193,13 @@ var GraphMetadataController = class _GraphMetadataController {
20031
21193
  createLocalGraphMetadataTask(
20032
21194
  "Handle routine execution ended",
20033
21195
  (ctx) => {
21196
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21197
+ ...ctx.data,
21198
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21199
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21200
+ });
20034
21201
  return buildDatabaseTriggerContext(
20035
- {
20036
- ...ctx.data,
20037
- serviceName: CadenzaService.serviceRegistry.serviceName,
20038
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
20039
- },
21202
+ sanitizedData,
20040
21203
  ctx.filter ?? void 0
20041
21204
  );
20042
21205
  },
@@ -20050,10 +21213,10 @@ var GraphMetadataController = class _GraphMetadataController {
20050
21213
  return false;
20051
21214
  }
20052
21215
  const taskExecutionData = ctx.data ?? {};
20053
- const sanitizedTaskContext = stripLocalRoutinePersistenceHints(
21216
+ const sanitizedTaskContext = sanitizeExecutionPersistenceContext(
20054
21217
  taskExecutionData.context ?? {}
20055
21218
  );
20056
- const sanitizedTaskMetaContext = stripLocalRoutinePersistenceHints(
21219
+ const sanitizedTaskMetaContext = sanitizeExecutionPersistenceContext(
20057
21220
  taskExecutionData.metaContext ?? {}
20058
21221
  );
20059
21222
  const routineMetadata = resolveRoutinePersistenceMetadata(
@@ -20286,12 +21449,13 @@ var GraphMetadataController = class _GraphMetadataController {
20286
21449
  if (!shouldPersistTaskExecutionMetadata(ctx)) {
20287
21450
  return false;
20288
21451
  }
21452
+ const sanitizedData = sanitizeExecutionPersistenceResultPayload({
21453
+ ...ctx.data,
21454
+ serviceName: CadenzaService.serviceRegistry.serviceName,
21455
+ serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
21456
+ });
20289
21457
  return buildDatabaseTriggerContext(
20290
- {
20291
- ...ctx.data,
20292
- serviceName: CadenzaService.serviceRegistry.serviceName,
20293
- serviceInstanceId: resolveExecutionObservabilityServiceInstanceId2()
20294
- },
21458
+ sanitizedData,
20295
21459
  ctx.filter ?? void 0
20296
21460
  );
20297
21461
  },
@@ -21356,9 +22520,17 @@ var CadenzaService = class {
21356
22520
  "meta.task.relationship_added",
21357
22521
  "meta.task.relationship_removed",
21358
22522
  "meta.task.intent_associated",
22523
+ "meta.task.helper_associated",
22524
+ "meta.task.global_associated",
21359
22525
  "meta.task.observed_signal",
21360
22526
  "meta.task.attached_signal",
21361
22527
  "meta.task.detached_signal",
22528
+ "meta.helper.created",
22529
+ "meta.helper.updated",
22530
+ "meta.global.created",
22531
+ "meta.global.updated",
22532
+ "meta.helper.helper_associated",
22533
+ "meta.helper.global_associated",
21362
22534
  "meta.actor.created",
21363
22535
  "meta.actor.task_associated",
21364
22536
  "meta.fetch.handshake_complete",